From f0c9297b90f4620a62c124cdd7302431ae5b6417 Mon Sep 17 00:00:00 2001 From: Shen Shen Date: Mon, 23 Jan 2023 22:56:45 -0500 Subject: [PATCH] simple renderer --- renderer/README.md | 84 + renderer/build/three.cjs | 50591 +++++++++++++++ renderer/build/three.js | 50597 ++++++++++++++++ renderer/build/three.min.js | 6 + renderer/build/three.module.js | 50183 +++++++++++++++ renderer/index.html | 197 + .../jsm/animation/AnimationClipCreator.js | 114 + renderer/jsm/animation/CCDIKSolver.js | 482 + renderer/jsm/animation/MMDAnimationHelper.js | 1207 + renderer/jsm/animation/MMDPhysics.js | 1406 + renderer/jsm/cameras/CinematicCamera.js | 209 + renderer/jsm/capabilities/WebGL.js | 91 + renderer/jsm/capabilities/WebGPU.js | 41 + renderer/jsm/controls/ArcballControls.js | 3223 + renderer/jsm/controls/DragControls.js | 220 + renderer/jsm/controls/FirstPersonControls.js | 325 + renderer/jsm/controls/FlyControls.js | 284 + renderer/jsm/controls/OrbitControls.js | 1287 + renderer/jsm/controls/PointerLockControls.js | 157 + renderer/jsm/controls/TrackballControls.js | 814 + renderer/jsm/controls/TransformControls.js | 1557 + renderer/jsm/csm/CSM.js | 386 + renderer/jsm/csm/CSMFrustum.js | 152 + renderer/jsm/csm/CSMHelper.js | 193 + renderer/jsm/csm/CSMShader.js | 252 + renderer/jsm/curves/CurveExtras.js | 422 + renderer/jsm/curves/NURBSCurve.js | 80 + renderer/jsm/curves/NURBSSurface.js | 52 + renderer/jsm/curves/NURBSUtils.js | 487 + renderer/jsm/effects/AnaglyphEffect.js | 168 + renderer/jsm/effects/AsciiEffect.js | 263 + renderer/jsm/effects/OutlineEffect.js | 553 + renderer/jsm/effects/ParallaxBarrierEffect.js | 116 + renderer/jsm/effects/PeppersGhostEffect.js | 153 + renderer/jsm/effects/StereoEffect.js | 55 + renderer/jsm/environments/DebugEnvironment.js | 52 + renderer/jsm/environments/RoomEnvironment.js | 144 + renderer/jsm/exporters/ColladaExporter.js | 725 + renderer/jsm/exporters/DRACOExporter.js | 227 + renderer/jsm/exporters/EXRExporter.js | 501 + renderer/jsm/exporters/GLTFExporter.js | 2698 + renderer/jsm/exporters/KTX2Exporter.js | 281 + renderer/jsm/exporters/MMDExporter.js | 217 + renderer/jsm/exporters/OBJExporter.js | 284 + renderer/jsm/exporters/PLYExporter.js | 528 + renderer/jsm/exporters/STLExporter.js | 199 + renderer/jsm/exporters/USDZExporter.js | 661 + renderer/jsm/geometries/BoxLineGeometry.js | 69 + renderer/jsm/geometries/ConvexGeometry.js | 53 + renderer/jsm/geometries/DecalGeometry.js | 356 + renderer/jsm/geometries/LightningStrike.js | 1017 + .../jsm/geometries/ParametricGeometries.js | 254 + renderer/jsm/geometries/ParametricGeometry.js | 129 + renderer/jsm/geometries/RoundedBoxGeometry.js | 155 + renderer/jsm/geometries/TeapotGeometry.js | 704 + renderer/jsm/geometries/TextGeometry.js | 57 + renderer/jsm/helpers/LightProbeHelper.js | 130 + renderer/jsm/helpers/OctreeHelper.js | 73 + renderer/jsm/helpers/PositionalAudioHelper.js | 109 + renderer/jsm/helpers/RectAreaLightHelper.js | 85 + renderer/jsm/helpers/VertexNormalsHelper.js | 96 + renderer/jsm/helpers/VertexTangentsHelper.js | 88 + renderer/jsm/helpers/ViewHelper.js | 333 + renderer/jsm/interactive/HTMLMesh.js | 552 + renderer/jsm/interactive/InteractiveGroup.js | 116 + renderer/jsm/interactive/SelectionBox.js | 227 + renderer/jsm/interactive/SelectionHelper.js | 97 + renderer/jsm/libs/OimoPhysics/OimoPhysics.js | 37071 +++++++++++ renderer/jsm/libs/OimoPhysics/index.js | 43 + renderer/jsm/libs/ammo.wasm.js | 822 + renderer/jsm/libs/ammo.wasm.wasm | Bin 0 -> 651386 bytes renderer/jsm/libs/basis/README.md | 46 + renderer/jsm/libs/basis/basis_transcoder.js | 21 + renderer/jsm/libs/basis/basis_transcoder.wasm | Bin 0 -> 499935 bytes renderer/jsm/libs/chevrotain.module.min.js | 141 + renderer/jsm/libs/draco/README.md | 32 + renderer/jsm/libs/draco/draco_decoder.js | 52 + renderer/jsm/libs/draco/draco_decoder.wasm | Bin 0 -> 281481 bytes renderer/jsm/libs/draco/draco_encoder.js | 33 + renderer/jsm/libs/draco/draco_wasm_wrapper.js | 104 + renderer/jsm/libs/draco/gltf/draco_decoder.js | 48 + .../jsm/libs/draco/gltf/draco_decoder.wasm | Bin 0 -> 194983 bytes renderer/jsm/libs/draco/gltf/draco_encoder.js | 33 + .../jsm/libs/draco/gltf/draco_wasm_wrapper.js | 104 + renderer/jsm/libs/ecsy.module.js | 1792 + renderer/jsm/libs/fflate.module.js | 2474 + renderer/jsm/libs/flow.module.js | 4552 ++ renderer/jsm/libs/ktx-parse.module.js | 1 + renderer/jsm/libs/lil-gui.module.min.js | 8 + renderer/jsm/libs/lottie_canvas.module.js | 14844 +++++ renderer/jsm/libs/meshopt_decoder.module.js | 178 + renderer/jsm/libs/mikktspace.module.js | 128 + renderer/jsm/libs/mmdparser.module.js | 11530 ++++ .../jsm/libs/motion-controllers.module.js | 397 + renderer/jsm/libs/opentype.module.js | 14568 +++++ renderer/jsm/libs/potpack.module.js | 125 + renderer/jsm/libs/rhino3dm/rhino3dm.js | 21 + renderer/jsm/libs/rhino3dm/rhino3dm.module.js | 16 + renderer/jsm/libs/rhino3dm/rhino3dm.wasm | Bin 0 -> 2803968 bytes renderer/jsm/libs/stats.module.js | 167 + renderer/jsm/libs/tween.module.min.js | 3 + renderer/jsm/libs/utif.module.js | 1579 + renderer/jsm/libs/zstddec.module.js | 1 + renderer/jsm/lights/IESSpotLight.js | 25 + renderer/jsm/lights/LightProbeGenerator.js | 250 + .../jsm/lights/RectAreaLightUniformsLib.js | 79 + renderer/jsm/lines/Line2.js | 19 + renderer/jsm/lines/LineGeometry.js | 79 + renderer/jsm/lines/LineMaterial.js | 702 + renderer/jsm/lines/LineSegments2.js | 361 + renderer/jsm/lines/LineSegmentsGeometry.js | 241 + renderer/jsm/lines/Wireframe.js | 56 + renderer/jsm/lines/WireframeGeometry2.js | 24 + renderer/jsm/loaders/3DMLoader.js | 1494 + renderer/jsm/loaders/3MFLoader.js | 1474 + renderer/jsm/loaders/AMFLoader.js | 517 + renderer/jsm/loaders/BVHLoader.js | 437 + renderer/jsm/loaders/BasisTextureLoader.js | 790 + renderer/jsm/loaders/ColladaLoader.js | 4119 ++ renderer/jsm/loaders/DDSLoader.js | 274 + renderer/jsm/loaders/DRACOLoader.js | 567 + renderer/jsm/loaders/EXRLoader.js | 2298 + renderer/jsm/loaders/FBXLoader.js | 4137 ++ renderer/jsm/loaders/FontLoader.js | 183 + renderer/jsm/loaders/GCodeLoader.js | 261 + renderer/jsm/loaders/GLTFLoader.js | 4311 ++ renderer/jsm/loaders/HDRCubeTextureLoader.js | 115 + renderer/jsm/loaders/IESLoader.js | 337 + renderer/jsm/loaders/IFCLoader.js | 2430 + renderer/jsm/loaders/KMZLoader.js | 130 + renderer/jsm/loaders/KTX2Loader.js | 792 + renderer/jsm/loaders/KTXLoader.js | 176 + renderer/jsm/loaders/LDrawLoader.js | 2465 + renderer/jsm/loaders/LUT3dlLoader.js | 151 + renderer/jsm/loaders/LUTCubeLoader.js | 153 + renderer/jsm/loaders/LWOLoader.js | 1069 + renderer/jsm/loaders/LogLuvLoader.js | 606 + renderer/jsm/loaders/LottieLoader.js | 75 + renderer/jsm/loaders/MD2Loader.js | 399 + renderer/jsm/loaders/MDDLoader.js | 102 + renderer/jsm/loaders/MMDLoader.js | 2237 + renderer/jsm/loaders/MTLLoader.js | 567 + renderer/jsm/loaders/MaterialXLoader.js | 734 + renderer/jsm/loaders/NRRDLoader.js | 671 + renderer/jsm/loaders/OBJLoader.js | 905 + renderer/jsm/loaders/PCDLoader.js | 452 + renderer/jsm/loaders/PDBLoader.js | 227 + renderer/jsm/loaders/PLYLoader.js | 736 + renderer/jsm/loaders/PRWMLoader.js | 299 + renderer/jsm/loaders/PVRLoader.js | 251 + renderer/jsm/loaders/RGBELoader.js | 468 + renderer/jsm/loaders/RGBMLoader.js | 1065 + renderer/jsm/loaders/STLLoader.js | 398 + renderer/jsm/loaders/SVGLoader.js | 3167 + renderer/jsm/loaders/TDSLoader.js | 1124 + renderer/jsm/loaders/TGALoader.js | 517 + renderer/jsm/loaders/TIFFLoader.js | 36 + renderer/jsm/loaders/TTFLoader.js | 214 + renderer/jsm/loaders/TiltLoader.js | 514 + renderer/jsm/loaders/USDZLoader.js | 633 + renderer/jsm/loaders/VOXLoader.js | 305 + renderer/jsm/loaders/VRMLLoader.js | 3485 ++ renderer/jsm/loaders/VTKLoader.js | 1155 + renderer/jsm/loaders/XYZLoader.js | 100 + renderer/jsm/loaders/ifc/web-ifc-api.js | 47504 +++++++++++++++ renderer/jsm/loaders/ifc/web-ifc.wasm | Bin 0 -> 428259 bytes renderer/jsm/loaders/lwo/IFFParser.js | 1218 + renderer/jsm/loaders/lwo/LWO2Parser.js | 414 + renderer/jsm/loaders/lwo/LWO3Parser.js | 373 + renderer/jsm/materials/MeshGouraudMaterial.js | 423 + renderer/jsm/math/Capsule.js | 137 + renderer/jsm/math/ColorConverter.js | 36 + renderer/jsm/math/ConvexHull.js | 1271 + renderer/jsm/math/ImprovedNoise.js | 71 + renderer/jsm/math/Lut.js | 203 + renderer/jsm/math/MeshSurfaceSampler.js | 211 + renderer/jsm/math/OBB.js | 423 + renderer/jsm/math/Octree.js | 462 + renderer/jsm/math/SimplexNoise.js | 444 + renderer/jsm/misc/ConvexObjectBreaker.js | 525 + renderer/jsm/misc/GPUComputationRenderer.js | 454 + renderer/jsm/misc/Gyroscope.js | 66 + renderer/jsm/misc/MD2Character.js | 276 + renderer/jsm/misc/MD2CharacterComplex.js | 576 + renderer/jsm/misc/MorphAnimMesh.js | 75 + renderer/jsm/misc/MorphBlendMesh.js | 322 + renderer/jsm/misc/ProgressiveLightMap.js | 321 + renderer/jsm/misc/RollerCoaster.js | 560 + renderer/jsm/misc/TubePainter.js | 205 + renderer/jsm/misc/Volume.js | 460 + renderer/jsm/misc/VolumeSlice.js | 227 + renderer/jsm/modifiers/CurveModifier.js | 325 + renderer/jsm/modifiers/EdgeSplitModifier.js | 279 + renderer/jsm/modifiers/SimplifyModifier.js | 525 + renderer/jsm/modifiers/TessellateModifier.js | 307 + renderer/jsm/node-editor/NodeEditor.js | 857 + .../node-editor/accessors/MatcapUVEditor.js | 14 + .../jsm/node-editor/accessors/NormalEditor.js | 30 + .../node-editor/accessors/PositionEditor.js | 30 + .../jsm/node-editor/accessors/UVEditor.js | 25 + renderer/jsm/node-editor/core/BaseNode.js | 96 + renderer/jsm/node-editor/core/DataFile.js | 59 + renderer/jsm/node-editor/core/FileEditor.js | 20 + .../jsm/node-editor/core/FileURLEditor.js | 29 + .../jsm/node-editor/display/BlendEditor.js | 44 + .../node-editor/display/NormalMapEditor.js | 49 + .../jsm/node-editor/examples/animate-uv.json | 1 + .../node-editor/examples/fake-top-light.json | 1 + renderer/jsm/node-editor/examples/matcap.json | 1 + .../examples/oscillator-color.json | 1 + renderer/jsm/node-editor/examples/rim.json | 1 + .../jsm/node-editor/inputs/ColorEditor.js | 96 + .../jsm/node-editor/inputs/FloatEditor.js | 23 + .../jsm/node-editor/inputs/SliderEditor.js | 67 + .../jsm/node-editor/inputs/TextureEditor.js | 155 + .../jsm/node-editor/inputs/Vector2Editor.js | 28 + .../jsm/node-editor/inputs/Vector3Editor.js | 30 + .../jsm/node-editor/inputs/Vector4Editor.js | 37 + .../materials/BasicMaterialEditor.js | 84 + .../materials/PointsMaterialEditor.js | 102 + .../materials/StandardMaterialEditor.js | 118 + renderer/jsm/node-editor/math/AngleEditor.js | 40 + renderer/jsm/node-editor/math/DotEditor.js | 35 + renderer/jsm/node-editor/math/InvertEditor.js | 39 + .../jsm/node-editor/math/LimiterEditor.js | 62 + .../jsm/node-editor/math/NormalizeEditor.js | 28 + .../jsm/node-editor/math/OperatorEditor.js | 63 + renderer/jsm/node-editor/math/PowerEditor.js | 44 + .../node-editor/math/TrigonometryEditor.js | 45 + .../node-editor/procedural/CheckerEditor.js | 27 + renderer/jsm/node-editor/scene/MeshEditor.js | 102 + .../jsm/node-editor/scene/Object3DEditor.js | 160 + .../jsm/node-editor/scene/PointsEditor.js | 99 + renderer/jsm/node-editor/utils/JoinEditor.js | 58 + .../jsm/node-editor/utils/OscillatorEditor.js | 43 + .../jsm/node-editor/utils/PreviewEditor.js | 170 + renderer/jsm/node-editor/utils/SplitEditor.js | 39 + renderer/jsm/node-editor/utils/TimerEditor.js | 58 + renderer/jsm/nodes/Nodes.js | 391 + renderer/jsm/nodes/accessors/BitangentNode.js | 62 + renderer/jsm/nodes/accessors/BufferNode.js | 24 + renderer/jsm/nodes/accessors/CameraNode.js | 67 + .../jsm/nodes/accessors/CubeTextureNode.js | 98 + .../nodes/accessors/ExtendedMaterialNode.js | 52 + renderer/jsm/nodes/accessors/InstanceNode.js | 58 + renderer/jsm/nodes/accessors/MaterialNode.js | 257 + .../nodes/accessors/MaterialReferenceNode.js | 33 + renderer/jsm/nodes/accessors/ModelNode.js | 21 + .../accessors/ModelViewProjectionNode.js | 30 + renderer/jsm/nodes/accessors/NormalNode.js | 85 + renderer/jsm/nodes/accessors/Object3DNode.js | 131 + renderer/jsm/nodes/accessors/PointUVNode.js | 21 + renderer/jsm/nodes/accessors/PositionNode.js | 95 + renderer/jsm/nodes/accessors/ReferenceNode.js | 67 + .../jsm/nodes/accessors/ReflectVectorNode.js | 30 + renderer/jsm/nodes/accessors/SkinningNode.js | 109 + .../jsm/nodes/accessors/StorageBufferNode.js | 21 + renderer/jsm/nodes/accessors/TangentNode.js | 95 + renderer/jsm/nodes/accessors/TextureNode.js | 150 + renderer/jsm/nodes/accessors/UVNode.js | 41 + renderer/jsm/nodes/accessors/UserDataNode.js | 23 + renderer/jsm/nodes/core/ArrayUniformNode.js | 23 + renderer/jsm/nodes/core/AttributeNode.js | 94 + renderer/jsm/nodes/core/BypassNode.js | 38 + renderer/jsm/nodes/core/CacheNode.js | 39 + renderer/jsm/nodes/core/CodeNode.js | 50 + renderer/jsm/nodes/core/ConstNode.js | 29 + renderer/jsm/nodes/core/ContextNode.js | 52 + renderer/jsm/nodes/core/ExpressionNode.js | 32 + renderer/jsm/nodes/core/FunctionCallNode.js | 82 + renderer/jsm/nodes/core/FunctionNode.js | 105 + renderer/jsm/nodes/core/InputNode.js | 66 + renderer/jsm/nodes/core/InstanceIndexNode.js | 21 + renderer/jsm/nodes/core/LightingModel.js | 14 + renderer/jsm/nodes/core/Node.js | 368 + renderer/jsm/nodes/core/NodeAttribute.js | 14 + renderer/jsm/nodes/core/NodeBuilder.js | 844 + renderer/jsm/nodes/core/NodeCache.js | 26 + renderer/jsm/nodes/core/NodeCode.js | 15 + renderer/jsm/nodes/core/NodeFrame.js | 59 + renderer/jsm/nodes/core/NodeFunction.js | 22 + renderer/jsm/nodes/core/NodeFunctionInput.js | 17 + renderer/jsm/nodes/core/NodeKeywords.js | 80 + renderer/jsm/nodes/core/NodeParser.js | 11 + renderer/jsm/nodes/core/NodeUniform.js | 28 + renderer/jsm/nodes/core/NodeUtils.js | 125 + renderer/jsm/nodes/core/NodeVar.js | 14 + renderer/jsm/nodes/core/NodeVarying.js | 17 + renderer/jsm/nodes/core/PropertyNode.js | 42 + renderer/jsm/nodes/core/StackNode.js | 53 + renderer/jsm/nodes/core/TempNode.js | 56 + renderer/jsm/nodes/core/UniformNode.js | 46 + renderer/jsm/nodes/core/VarNode.js | 103 + renderer/jsm/nodes/core/VaryingNode.js | 62 + renderer/jsm/nodes/core/constants.js | 21 + renderer/jsm/nodes/display/BlendModeNode.js | 85 + .../jsm/nodes/display/ColorAdjustmentNode.js | 84 + renderer/jsm/nodes/display/ColorSpaceNode.js | 95 + renderer/jsm/nodes/display/FrontFacingNode.js | 21 + renderer/jsm/nodes/display/NormalMapNode.js | 93 + renderer/jsm/nodes/display/PosterizeNode.js | 25 + renderer/jsm/nodes/display/ToneMappingNode.js | 127 + renderer/jsm/nodes/display/ViewportNode.js | 104 + renderer/jsm/nodes/fog/FogExp2Node.js | 27 + renderer/jsm/nodes/fog/FogNode.js | 31 + renderer/jsm/nodes/fog/FogRangeNode.js | 25 + .../nodes/functions/BSDF/BRDF_BlinnPhong.js | 27 + renderer/jsm/nodes/functions/BSDF/BRDF_GGX.js | 33 + .../jsm/nodes/functions/BSDF/BRDF_Lambert.js | 9 + .../jsm/nodes/functions/BSDF/DFGApprox.js | 27 + renderer/jsm/nodes/functions/BSDF/D_GGX.js | 18 + .../jsm/nodes/functions/BSDF/F_Schlick.js | 18 + .../functions/BSDF/V_GGX_SmithCorrelated.js | 18 + .../jsm/nodes/functions/PhongLightingModel.js | 29 + .../nodes/functions/PhysicalLightingModel.js | 89 + .../functions/light/getDirectionVector.js | 16 + .../functions/light/getDistanceAttenuation.js | 22 + .../material/getGeometryRoughness.js | 12 + .../nodes/functions/material/getRoughness.js | 18 + renderer/jsm/nodes/geometry/RangeNode.js | 109 + renderer/jsm/nodes/gpgpu/ComputeNode.js | 65 + renderer/jsm/nodes/lighting/AONode.js | 25 + .../jsm/nodes/lighting/AmbientLightNode.js | 24 + .../jsm/nodes/lighting/AnalyticLightNode.js | 37 + .../nodes/lighting/DirectionalLightNode.js | 50 + .../jsm/nodes/lighting/EnvironmentNode.js | 129 + .../jsm/nodes/lighting/HemisphereLightNode.js | 50 + .../jsm/nodes/lighting/IESSpotLightNode.js | 35 + .../jsm/nodes/lighting/LightingContextNode.js | 75 + renderer/jsm/nodes/lighting/LightingNode.js | 19 + renderer/jsm/nodes/lighting/LightsNode.js | 120 + renderer/jsm/nodes/lighting/PointLightNode.js | 66 + renderer/jsm/nodes/lighting/SpotLightNode.js | 90 + renderer/jsm/nodes/loaders/NodeLoader.js | 107 + .../jsm/nodes/loaders/NodeMaterialLoader.js | 75 + .../jsm/nodes/loaders/NodeObjectLoader.js | 70 + .../nodes/materials/LineBasicNodeMaterial.js | 49 + renderer/jsm/nodes/materials/Materials.js | 58 + .../nodes/materials/MeshBasicNodeMaterial.js | 48 + .../nodes/materials/MeshPhongNodeMaterial.js | 83 + .../materials/MeshPhysicalNodeMaterial.js | 70 + .../materials/MeshStandardNodeMaterial.js | 100 + renderer/jsm/nodes/materials/NodeMaterial.js | 365 + .../jsm/nodes/materials/PointsNodeMaterial.js | 55 + .../jsm/nodes/materials/SpriteNodeMaterial.js | 107 + renderer/jsm/nodes/materialx/DISCLAIMER.md | 199 + .../jsm/nodes/materialx/MaterialXNodes.js | 59 + renderer/jsm/nodes/materialx/lib/mx_hsv.js | 56 + renderer/jsm/nodes/materialx/lib/mx_noise.js | 617 + .../nodes/materialx/lib/mx_transform_color.js | 18 + renderer/jsm/nodes/math/CondNode.js | 72 + renderer/jsm/nodes/math/MathNode.js | 248 + renderer/jsm/nodes/math/OperatorNode.js | 225 + .../jsm/nodes/parsers/GLSLNodeFunction.js | 152 + renderer/jsm/nodes/parsers/GLSLNodeParser.js | 14 + .../jsm/nodes/parsers/WGSLNodeFunction.js | 104 + renderer/jsm/nodes/parsers/WGSLNodeParser.js | 14 + renderer/jsm/nodes/procedural/CheckerNode.js | 34 + renderer/jsm/nodes/shadernode/ShaderNode.js | 289 + .../shadernode/ShaderNodeBaseElements.js | 321 + .../nodes/shadernode/ShaderNodeElements.js | 158 + renderer/jsm/nodes/utils/ArrayElementNode.js | 31 + renderer/jsm/nodes/utils/ConvertNode.js | 47 + renderer/jsm/nodes/utils/DiscardNode.js | 18 + renderer/jsm/nodes/utils/EquirectUVNode.js | 27 + renderer/jsm/nodes/utils/JoinNode.js | 48 + renderer/jsm/nodes/utils/MatcapUVNode.js | 23 + renderer/jsm/nodes/utils/MaxMipLevelNode.js | 40 + renderer/jsm/nodes/utils/OscNode.js | 74 + renderer/jsm/nodes/utils/RemapNode.js | 34 + renderer/jsm/nodes/utils/RotateUVNode.js | 32 + .../jsm/nodes/utils/SpecularMIPLevelNode.js | 32 + renderer/jsm/nodes/utils/SplitNode.js | 102 + renderer/jsm/nodes/utils/SpriteSheetUVNode.js | 56 + renderer/jsm/nodes/utils/TimerNode.js | 84 + .../jsm/nodes/utils/TriplanarTexturesNode.js | 51 + renderer/jsm/objects/GroundProjectedEnv.js | 174 + renderer/jsm/objects/Lensflare.js | 378 + renderer/jsm/objects/LightningStorm.js | 245 + renderer/jsm/objects/MarchingCubes.js | 1172 + renderer/jsm/objects/Reflector.js | 269 + renderer/jsm/objects/ReflectorForSSRPass.js | 349 + renderer/jsm/objects/Refractor.js | 332 + renderer/jsm/objects/ShadowMesh.js | 80 + renderer/jsm/objects/Sky.js | 219 + renderer/jsm/objects/Water.js | 329 + renderer/jsm/objects/Water2.js | 358 + renderer/jsm/offscreen/jank.js | 45 + renderer/jsm/offscreen/offscreen.js | 8 + renderer/jsm/offscreen/scene.js | 86 + renderer/jsm/physics/AmmoPhysics.js | 286 + renderer/jsm/physics/OimoPhysics.js | 231 + .../postprocessing/AdaptiveToneMappingPass.js | 361 + renderer/jsm/postprocessing/AfterimagePass.js | 101 + renderer/jsm/postprocessing/BloomPass.js | 167 + renderer/jsm/postprocessing/BokehPass.js | 139 + renderer/jsm/postprocessing/ClearPass.js | 46 + .../jsm/postprocessing/CubeTexturePass.js | 85 + renderer/jsm/postprocessing/DotScreenPass.js | 64 + renderer/jsm/postprocessing/EffectComposer.js | 228 + renderer/jsm/postprocessing/FilmPass.js | 65 + renderer/jsm/postprocessing/GlitchPass.js | 128 + renderer/jsm/postprocessing/HalftonePass.js | 79 + renderer/jsm/postprocessing/LUTPass.js | 173 + renderer/jsm/postprocessing/MaskPass.js | 101 + renderer/jsm/postprocessing/OutlinePass.js | 655 + renderer/jsm/postprocessing/Pass.js | 82 + renderer/jsm/postprocessing/RenderPass.js | 81 + .../jsm/postprocessing/RenderPixelatedPass.js | 234 + renderer/jsm/postprocessing/SAOPass.js | 409 + renderer/jsm/postprocessing/SMAAPass.js | 198 + renderer/jsm/postprocessing/SSAARenderPass.js | 236 + renderer/jsm/postprocessing/SSAOPass.js | 438 + renderer/jsm/postprocessing/SSRPass.js | 639 + renderer/jsm/postprocessing/SavePass.js | 76 + renderer/jsm/postprocessing/ShaderPass.js | 76 + renderer/jsm/postprocessing/TAARenderPass.js | 176 + renderer/jsm/postprocessing/TexturePass.js | 66 + .../jsm/postprocessing/UnrealBloomPass.js | 411 + renderer/jsm/renderers/CSS2DRenderer.js | 210 + renderer/jsm/renderers/CSS3DRenderer.js | 313 + renderer/jsm/renderers/Projector.js | 918 + renderer/jsm/renderers/SVGRenderer.js | 553 + .../jsm/renderers/webgl/nodes/SlotNode.js | 26 + .../renderers/webgl/nodes/WebGLNodeBuilder.js | 756 + .../jsm/renderers/webgl/nodes/WebGLNodes.js | 49 + .../jsm/renderers/webgpu/WebGPUAnimation.js | 58 + .../jsm/renderers/webgpu/WebGPUAttributes.js | 187 + .../jsm/renderers/webgpu/WebGPUBackground.js | 179 + .../jsm/renderers/webgpu/WebGPUBinding.js | 22 + .../jsm/renderers/webgpu/WebGPUBindings.js | 255 + renderer/jsm/renderers/webgpu/WebGPUBuffer.js | 43 + .../jsm/renderers/webgpu/WebGPUBufferUtils.js | 33 + .../webgpu/WebGPUComputePipelines.js | 78 + .../jsm/renderers/webgpu/WebGPUGeometries.js | 185 + renderer/jsm/renderers/webgpu/WebGPUInfo.js | 74 + .../jsm/renderers/webgpu/WebGPUObjects.js | 38 + .../webgpu/WebGPUProgrammableStage.js | 22 + .../jsm/renderers/webgpu/WebGPUProperties.js | 38 + .../jsm/renderers/webgpu/WebGPURenderLists.js | 199 + .../renderers/webgpu/WebGPURenderPipeline.js | 735 + .../renderers/webgpu/WebGPURenderPipelines.js | 296 + .../renderers/webgpu/WebGPURenderStates.js | 66 + .../jsm/renderers/webgpu/WebGPURenderer.js | 1007 + .../renderers/webgpu/WebGPUSampledTexture.js | 73 + .../jsm/renderers/webgpu/WebGPUSampler.js | 29 + .../renderers/webgpu/WebGPUStorageBuffer.js | 20 + .../renderers/webgpu/WebGPUTextureRenderer.js | 40 + .../renderers/webgpu/WebGPUTextureUtils.js | 183 + .../jsm/renderers/webgpu/WebGPUTextures.js | 794 + .../jsm/renderers/webgpu/WebGPUUniform.js | 136 + .../renderers/webgpu/WebGPUUniformBuffer.js | 18 + .../renderers/webgpu/WebGPUUniformsGroup.js | 299 + renderer/jsm/renderers/webgpu/WebGPUUtils.js | 81 + renderer/jsm/renderers/webgpu/constants.js | 261 + .../webgpu/nodes/WebGPUNodeBuilder.js | 820 + .../webgpu/nodes/WebGPUNodeSampledTexture.js | 39 + .../webgpu/nodes/WebGPUNodeSampler.js | 21 + .../webgpu/nodes/WebGPUNodeUniform.js | 135 + .../jsm/renderers/webgpu/nodes/WebGPUNodes.js | 83 + .../shaders/ACESFilmicToneMappingShader.js | 87 + renderer/jsm/shaders/AfterimageShader.js | 56 + renderer/jsm/shaders/BasicShader.js | 27 + renderer/jsm/shaders/BleachBypassShader.js | 60 + renderer/jsm/shaders/BlendShader.js | 48 + renderer/jsm/shaders/BokehShader.js | 143 + renderer/jsm/shaders/BokehShader2.js | 390 + .../jsm/shaders/BrightnessContrastShader.js | 54 + renderer/jsm/shaders/ColorCorrectionShader.js | 50 + renderer/jsm/shaders/ColorifyShader.js | 49 + renderer/jsm/shaders/ConvolutionShader.js | 101 + renderer/jsm/shaders/CopyShader.js | 43 + renderer/jsm/shaders/DOFMipMapShader.js | 54 + .../jsm/shaders/DepthLimitedBlurShader.js | 166 + renderer/jsm/shaders/DigitalGlitch.js | 101 + renderer/jsm/shaders/DotScreenShader.js | 68 + renderer/jsm/shaders/FXAAShader.js | 286 + renderer/jsm/shaders/FilmShader.js | 100 + renderer/jsm/shaders/FocusShader.js | 87 + renderer/jsm/shaders/FreiChenShader.js | 94 + renderer/jsm/shaders/GammaCorrectionShader.js | 41 + renderer/jsm/shaders/GodRaysShader.js | 313 + renderer/jsm/shaders/HalftoneShader.js | 310 + renderer/jsm/shaders/HorizontalBlurShader.js | 57 + .../jsm/shaders/HorizontalTiltShiftShader.js | 61 + renderer/jsm/shaders/HueSaturationShader.js | 65 + renderer/jsm/shaders/KaleidoShader.js | 56 + .../jsm/shaders/LuminosityHighPassShader.js | 64 + renderer/jsm/shaders/LuminosityShader.js | 46 + renderer/jsm/shaders/MMDToonShader.js | 132 + renderer/jsm/shaders/MirrorShader.js | 54 + renderer/jsm/shaders/NormalMapShader.js | 53 + renderer/jsm/shaders/RGBShiftShader.js | 52 + renderer/jsm/shaders/SAOShader.js | 188 + renderer/jsm/shaders/SMAAShader.js | 460 + renderer/jsm/shaders/SSAOShader.js | 288 + renderer/jsm/shaders/SSRShader.js | 364 + renderer/jsm/shaders/SepiaShader.js | 50 + renderer/jsm/shaders/SobelOperatorShader.js | 90 + .../jsm/shaders/SubsurfaceScatteringShader.js | 88 + renderer/jsm/shaders/TechnicolorShader.js | 43 + renderer/jsm/shaders/ToneMapShader.js | 73 + renderer/jsm/shaders/ToonShader.js | 318 + renderer/jsm/shaders/TriangleBlurShader.js | 72 + renderer/jsm/shaders/UnpackDepthRGBAShader.js | 45 + renderer/jsm/shaders/VelocityShader.js | 128 + renderer/jsm/shaders/VerticalBlurShader.js | 57 + .../jsm/shaders/VerticalTiltShiftShader.js | 61 + renderer/jsm/shaders/VignetteShader.js | 49 + renderer/jsm/shaders/VolumeShader.js | 289 + renderer/jsm/shaders/WaterRefractionShader.js | 90 + renderer/jsm/textures/FlakesTexture.js | 40 + renderer/jsm/utils/BufferGeometryUtils.js | 1346 + renderer/jsm/utils/CameraUtils.js | 73 + renderer/jsm/utils/GPUStatsPanel.js | 128 + .../jsm/utils/GeometryCompressionUtils.js | 639 + renderer/jsm/utils/GeometryUtils.js | 221 + renderer/jsm/utils/LDrawUtils.js | 202 + renderer/jsm/utils/PackedPhongMaterial.js | 180 + renderer/jsm/utils/SceneUtils.js | 254 + renderer/jsm/utils/ShadowMapViewer.js | 210 + renderer/jsm/utils/SkeletonUtils.js | 596 + renderer/jsm/utils/UVsDebug.js | 165 + renderer/jsm/utils/WorkerPool.js | 102 + renderer/jsm/webxr/ARButton.js | 208 + renderer/jsm/webxr/OculusHandModel.js | 109 + renderer/jsm/webxr/OculusHandPointerModel.js | 392 + renderer/jsm/webxr/Text2D.js | 38 + renderer/jsm/webxr/VRButton.js | 200 + .../jsm/webxr/XRControllerModelFactory.js | 299 + renderer/jsm/webxr/XREstimatedLight.js | 223 + renderer/jsm/webxr/XRHandMeshModel.js | 112 + renderer/jsm/webxr/XRHandModelFactory.js | 105 + renderer/jsm/webxr/XRHandPrimitiveModel.js | 102 + renderer/main.css | 91 + renderer/package-lock.json | 9673 +++ renderer/package.json | 168 + renderer/utils/build/rollup.config.js | 323 + renderer/utils/packLDrawModel.js | 304 + 539 files changed, 435432 insertions(+) create mode 100644 renderer/README.md create mode 100644 renderer/build/three.cjs create mode 100644 renderer/build/three.js create mode 100644 renderer/build/three.min.js create mode 100644 renderer/build/three.module.js create mode 100644 renderer/index.html create mode 100644 renderer/jsm/animation/AnimationClipCreator.js create mode 100644 renderer/jsm/animation/CCDIKSolver.js create mode 100644 renderer/jsm/animation/MMDAnimationHelper.js create mode 100644 renderer/jsm/animation/MMDPhysics.js create mode 100644 renderer/jsm/cameras/CinematicCamera.js create mode 100644 renderer/jsm/capabilities/WebGL.js create mode 100644 renderer/jsm/capabilities/WebGPU.js create mode 100644 renderer/jsm/controls/ArcballControls.js create mode 100644 renderer/jsm/controls/DragControls.js create mode 100644 renderer/jsm/controls/FirstPersonControls.js create mode 100644 renderer/jsm/controls/FlyControls.js create mode 100644 renderer/jsm/controls/OrbitControls.js create mode 100644 renderer/jsm/controls/PointerLockControls.js create mode 100644 renderer/jsm/controls/TrackballControls.js create mode 100644 renderer/jsm/controls/TransformControls.js create mode 100644 renderer/jsm/csm/CSM.js create mode 100644 renderer/jsm/csm/CSMFrustum.js create mode 100644 renderer/jsm/csm/CSMHelper.js create mode 100644 renderer/jsm/csm/CSMShader.js create mode 100644 renderer/jsm/curves/CurveExtras.js create mode 100644 renderer/jsm/curves/NURBSCurve.js create mode 100644 renderer/jsm/curves/NURBSSurface.js create mode 100644 renderer/jsm/curves/NURBSUtils.js create mode 100644 renderer/jsm/effects/AnaglyphEffect.js create mode 100644 renderer/jsm/effects/AsciiEffect.js create mode 100644 renderer/jsm/effects/OutlineEffect.js create mode 100644 renderer/jsm/effects/ParallaxBarrierEffect.js create mode 100644 renderer/jsm/effects/PeppersGhostEffect.js create mode 100644 renderer/jsm/effects/StereoEffect.js create mode 100644 renderer/jsm/environments/DebugEnvironment.js create mode 100644 renderer/jsm/environments/RoomEnvironment.js create mode 100644 renderer/jsm/exporters/ColladaExporter.js create mode 100644 renderer/jsm/exporters/DRACOExporter.js create mode 100644 renderer/jsm/exporters/EXRExporter.js create mode 100644 renderer/jsm/exporters/GLTFExporter.js create mode 100644 renderer/jsm/exporters/KTX2Exporter.js create mode 100644 renderer/jsm/exporters/MMDExporter.js create mode 100644 renderer/jsm/exporters/OBJExporter.js create mode 100644 renderer/jsm/exporters/PLYExporter.js create mode 100644 renderer/jsm/exporters/STLExporter.js create mode 100644 renderer/jsm/exporters/USDZExporter.js create mode 100644 renderer/jsm/geometries/BoxLineGeometry.js create mode 100644 renderer/jsm/geometries/ConvexGeometry.js create mode 100644 renderer/jsm/geometries/DecalGeometry.js create mode 100644 renderer/jsm/geometries/LightningStrike.js create mode 100644 renderer/jsm/geometries/ParametricGeometries.js create mode 100644 renderer/jsm/geometries/ParametricGeometry.js create mode 100644 renderer/jsm/geometries/RoundedBoxGeometry.js create mode 100644 renderer/jsm/geometries/TeapotGeometry.js create mode 100644 renderer/jsm/geometries/TextGeometry.js create mode 100644 renderer/jsm/helpers/LightProbeHelper.js create mode 100644 renderer/jsm/helpers/OctreeHelper.js create mode 100644 renderer/jsm/helpers/PositionalAudioHelper.js create mode 100644 renderer/jsm/helpers/RectAreaLightHelper.js create mode 100644 renderer/jsm/helpers/VertexNormalsHelper.js create mode 100644 renderer/jsm/helpers/VertexTangentsHelper.js create mode 100644 renderer/jsm/helpers/ViewHelper.js create mode 100644 renderer/jsm/interactive/HTMLMesh.js create mode 100644 renderer/jsm/interactive/InteractiveGroup.js create mode 100644 renderer/jsm/interactive/SelectionBox.js create mode 100644 renderer/jsm/interactive/SelectionHelper.js create mode 100644 renderer/jsm/libs/OimoPhysics/OimoPhysics.js create mode 100644 renderer/jsm/libs/OimoPhysics/index.js create mode 100644 renderer/jsm/libs/ammo.wasm.js create mode 100644 renderer/jsm/libs/ammo.wasm.wasm create mode 100644 renderer/jsm/libs/basis/README.md create mode 100644 renderer/jsm/libs/basis/basis_transcoder.js create mode 100644 renderer/jsm/libs/basis/basis_transcoder.wasm create mode 100644 renderer/jsm/libs/chevrotain.module.min.js create mode 100644 renderer/jsm/libs/draco/README.md create mode 100644 renderer/jsm/libs/draco/draco_decoder.js create mode 100644 renderer/jsm/libs/draco/draco_decoder.wasm create mode 100644 renderer/jsm/libs/draco/draco_encoder.js create mode 100644 renderer/jsm/libs/draco/draco_wasm_wrapper.js create mode 100644 renderer/jsm/libs/draco/gltf/draco_decoder.js create mode 100644 renderer/jsm/libs/draco/gltf/draco_decoder.wasm create mode 100755 renderer/jsm/libs/draco/gltf/draco_encoder.js create mode 100644 renderer/jsm/libs/draco/gltf/draco_wasm_wrapper.js create mode 100644 renderer/jsm/libs/ecsy.module.js create mode 100644 renderer/jsm/libs/fflate.module.js create mode 100644 renderer/jsm/libs/flow.module.js create mode 100644 renderer/jsm/libs/ktx-parse.module.js create mode 100644 renderer/jsm/libs/lil-gui.module.min.js create mode 100644 renderer/jsm/libs/lottie_canvas.module.js create mode 100644 renderer/jsm/libs/meshopt_decoder.module.js create mode 100644 renderer/jsm/libs/mikktspace.module.js create mode 100644 renderer/jsm/libs/mmdparser.module.js create mode 100644 renderer/jsm/libs/motion-controllers.module.js create mode 100644 renderer/jsm/libs/opentype.module.js create mode 100644 renderer/jsm/libs/potpack.module.js create mode 100644 renderer/jsm/libs/rhino3dm/rhino3dm.js create mode 100644 renderer/jsm/libs/rhino3dm/rhino3dm.module.js create mode 100644 renderer/jsm/libs/rhino3dm/rhino3dm.wasm create mode 100644 renderer/jsm/libs/stats.module.js create mode 100644 renderer/jsm/libs/tween.module.min.js create mode 100644 renderer/jsm/libs/utif.module.js create mode 100644 renderer/jsm/libs/zstddec.module.js create mode 100644 renderer/jsm/lights/IESSpotLight.js create mode 100644 renderer/jsm/lights/LightProbeGenerator.js create mode 100644 renderer/jsm/lights/RectAreaLightUniformsLib.js create mode 100644 renderer/jsm/lines/Line2.js create mode 100644 renderer/jsm/lines/LineGeometry.js create mode 100644 renderer/jsm/lines/LineMaterial.js create mode 100644 renderer/jsm/lines/LineSegments2.js create mode 100644 renderer/jsm/lines/LineSegmentsGeometry.js create mode 100644 renderer/jsm/lines/Wireframe.js create mode 100644 renderer/jsm/lines/WireframeGeometry2.js create mode 100644 renderer/jsm/loaders/3DMLoader.js create mode 100644 renderer/jsm/loaders/3MFLoader.js create mode 100644 renderer/jsm/loaders/AMFLoader.js create mode 100644 renderer/jsm/loaders/BVHLoader.js create mode 100644 renderer/jsm/loaders/BasisTextureLoader.js create mode 100644 renderer/jsm/loaders/ColladaLoader.js create mode 100644 renderer/jsm/loaders/DDSLoader.js create mode 100644 renderer/jsm/loaders/DRACOLoader.js create mode 100644 renderer/jsm/loaders/EXRLoader.js create mode 100644 renderer/jsm/loaders/FBXLoader.js create mode 100644 renderer/jsm/loaders/FontLoader.js create mode 100644 renderer/jsm/loaders/GCodeLoader.js create mode 100644 renderer/jsm/loaders/GLTFLoader.js create mode 100644 renderer/jsm/loaders/HDRCubeTextureLoader.js create mode 100644 renderer/jsm/loaders/IESLoader.js create mode 100644 renderer/jsm/loaders/IFCLoader.js create mode 100644 renderer/jsm/loaders/KMZLoader.js create mode 100644 renderer/jsm/loaders/KTX2Loader.js create mode 100644 renderer/jsm/loaders/KTXLoader.js create mode 100644 renderer/jsm/loaders/LDrawLoader.js create mode 100644 renderer/jsm/loaders/LUT3dlLoader.js create mode 100644 renderer/jsm/loaders/LUTCubeLoader.js create mode 100644 renderer/jsm/loaders/LWOLoader.js create mode 100644 renderer/jsm/loaders/LogLuvLoader.js create mode 100644 renderer/jsm/loaders/LottieLoader.js create mode 100644 renderer/jsm/loaders/MD2Loader.js create mode 100644 renderer/jsm/loaders/MDDLoader.js create mode 100644 renderer/jsm/loaders/MMDLoader.js create mode 100644 renderer/jsm/loaders/MTLLoader.js create mode 100644 renderer/jsm/loaders/MaterialXLoader.js create mode 100644 renderer/jsm/loaders/NRRDLoader.js create mode 100644 renderer/jsm/loaders/OBJLoader.js create mode 100644 renderer/jsm/loaders/PCDLoader.js create mode 100644 renderer/jsm/loaders/PDBLoader.js create mode 100644 renderer/jsm/loaders/PLYLoader.js create mode 100644 renderer/jsm/loaders/PRWMLoader.js create mode 100644 renderer/jsm/loaders/PVRLoader.js create mode 100644 renderer/jsm/loaders/RGBELoader.js create mode 100644 renderer/jsm/loaders/RGBMLoader.js create mode 100644 renderer/jsm/loaders/STLLoader.js create mode 100644 renderer/jsm/loaders/SVGLoader.js create mode 100644 renderer/jsm/loaders/TDSLoader.js create mode 100644 renderer/jsm/loaders/TGALoader.js create mode 100644 renderer/jsm/loaders/TIFFLoader.js create mode 100644 renderer/jsm/loaders/TTFLoader.js create mode 100644 renderer/jsm/loaders/TiltLoader.js create mode 100644 renderer/jsm/loaders/USDZLoader.js create mode 100644 renderer/jsm/loaders/VOXLoader.js create mode 100644 renderer/jsm/loaders/VRMLLoader.js create mode 100644 renderer/jsm/loaders/VTKLoader.js create mode 100644 renderer/jsm/loaders/XYZLoader.js create mode 100644 renderer/jsm/loaders/ifc/web-ifc-api.js create mode 100644 renderer/jsm/loaders/ifc/web-ifc.wasm create mode 100644 renderer/jsm/loaders/lwo/IFFParser.js create mode 100644 renderer/jsm/loaders/lwo/LWO2Parser.js create mode 100644 renderer/jsm/loaders/lwo/LWO3Parser.js create mode 100644 renderer/jsm/materials/MeshGouraudMaterial.js create mode 100644 renderer/jsm/math/Capsule.js create mode 100644 renderer/jsm/math/ColorConverter.js create mode 100644 renderer/jsm/math/ConvexHull.js create mode 100644 renderer/jsm/math/ImprovedNoise.js create mode 100644 renderer/jsm/math/Lut.js create mode 100644 renderer/jsm/math/MeshSurfaceSampler.js create mode 100644 renderer/jsm/math/OBB.js create mode 100644 renderer/jsm/math/Octree.js create mode 100644 renderer/jsm/math/SimplexNoise.js create mode 100644 renderer/jsm/misc/ConvexObjectBreaker.js create mode 100644 renderer/jsm/misc/GPUComputationRenderer.js create mode 100644 renderer/jsm/misc/Gyroscope.js create mode 100644 renderer/jsm/misc/MD2Character.js create mode 100644 renderer/jsm/misc/MD2CharacterComplex.js create mode 100644 renderer/jsm/misc/MorphAnimMesh.js create mode 100644 renderer/jsm/misc/MorphBlendMesh.js create mode 100644 renderer/jsm/misc/ProgressiveLightMap.js create mode 100644 renderer/jsm/misc/RollerCoaster.js create mode 100644 renderer/jsm/misc/TubePainter.js create mode 100644 renderer/jsm/misc/Volume.js create mode 100644 renderer/jsm/misc/VolumeSlice.js create mode 100644 renderer/jsm/modifiers/CurveModifier.js create mode 100644 renderer/jsm/modifiers/EdgeSplitModifier.js create mode 100644 renderer/jsm/modifiers/SimplifyModifier.js create mode 100644 renderer/jsm/modifiers/TessellateModifier.js create mode 100644 renderer/jsm/node-editor/NodeEditor.js create mode 100644 renderer/jsm/node-editor/accessors/MatcapUVEditor.js create mode 100644 renderer/jsm/node-editor/accessors/NormalEditor.js create mode 100644 renderer/jsm/node-editor/accessors/PositionEditor.js create mode 100644 renderer/jsm/node-editor/accessors/UVEditor.js create mode 100644 renderer/jsm/node-editor/core/BaseNode.js create mode 100644 renderer/jsm/node-editor/core/DataFile.js create mode 100644 renderer/jsm/node-editor/core/FileEditor.js create mode 100644 renderer/jsm/node-editor/core/FileURLEditor.js create mode 100644 renderer/jsm/node-editor/display/BlendEditor.js create mode 100644 renderer/jsm/node-editor/display/NormalMapEditor.js create mode 100644 renderer/jsm/node-editor/examples/animate-uv.json create mode 100644 renderer/jsm/node-editor/examples/fake-top-light.json create mode 100644 renderer/jsm/node-editor/examples/matcap.json create mode 100644 renderer/jsm/node-editor/examples/oscillator-color.json create mode 100644 renderer/jsm/node-editor/examples/rim.json create mode 100644 renderer/jsm/node-editor/inputs/ColorEditor.js create mode 100644 renderer/jsm/node-editor/inputs/FloatEditor.js create mode 100644 renderer/jsm/node-editor/inputs/SliderEditor.js create mode 100644 renderer/jsm/node-editor/inputs/TextureEditor.js create mode 100644 renderer/jsm/node-editor/inputs/Vector2Editor.js create mode 100644 renderer/jsm/node-editor/inputs/Vector3Editor.js create mode 100644 renderer/jsm/node-editor/inputs/Vector4Editor.js create mode 100644 renderer/jsm/node-editor/materials/BasicMaterialEditor.js create mode 100644 renderer/jsm/node-editor/materials/PointsMaterialEditor.js create mode 100644 renderer/jsm/node-editor/materials/StandardMaterialEditor.js create mode 100644 renderer/jsm/node-editor/math/AngleEditor.js create mode 100644 renderer/jsm/node-editor/math/DotEditor.js create mode 100644 renderer/jsm/node-editor/math/InvertEditor.js create mode 100644 renderer/jsm/node-editor/math/LimiterEditor.js create mode 100644 renderer/jsm/node-editor/math/NormalizeEditor.js create mode 100644 renderer/jsm/node-editor/math/OperatorEditor.js create mode 100644 renderer/jsm/node-editor/math/PowerEditor.js create mode 100644 renderer/jsm/node-editor/math/TrigonometryEditor.js create mode 100644 renderer/jsm/node-editor/procedural/CheckerEditor.js create mode 100644 renderer/jsm/node-editor/scene/MeshEditor.js create mode 100644 renderer/jsm/node-editor/scene/Object3DEditor.js create mode 100644 renderer/jsm/node-editor/scene/PointsEditor.js create mode 100644 renderer/jsm/node-editor/utils/JoinEditor.js create mode 100644 renderer/jsm/node-editor/utils/OscillatorEditor.js create mode 100644 renderer/jsm/node-editor/utils/PreviewEditor.js create mode 100644 renderer/jsm/node-editor/utils/SplitEditor.js create mode 100644 renderer/jsm/node-editor/utils/TimerEditor.js create mode 100644 renderer/jsm/nodes/Nodes.js create mode 100644 renderer/jsm/nodes/accessors/BitangentNode.js create mode 100644 renderer/jsm/nodes/accessors/BufferNode.js create mode 100644 renderer/jsm/nodes/accessors/CameraNode.js create mode 100644 renderer/jsm/nodes/accessors/CubeTextureNode.js create mode 100644 renderer/jsm/nodes/accessors/ExtendedMaterialNode.js create mode 100644 renderer/jsm/nodes/accessors/InstanceNode.js create mode 100644 renderer/jsm/nodes/accessors/MaterialNode.js create mode 100644 renderer/jsm/nodes/accessors/MaterialReferenceNode.js create mode 100644 renderer/jsm/nodes/accessors/ModelNode.js create mode 100644 renderer/jsm/nodes/accessors/ModelViewProjectionNode.js create mode 100644 renderer/jsm/nodes/accessors/NormalNode.js create mode 100644 renderer/jsm/nodes/accessors/Object3DNode.js create mode 100644 renderer/jsm/nodes/accessors/PointUVNode.js create mode 100644 renderer/jsm/nodes/accessors/PositionNode.js create mode 100644 renderer/jsm/nodes/accessors/ReferenceNode.js create mode 100644 renderer/jsm/nodes/accessors/ReflectVectorNode.js create mode 100644 renderer/jsm/nodes/accessors/SkinningNode.js create mode 100644 renderer/jsm/nodes/accessors/StorageBufferNode.js create mode 100644 renderer/jsm/nodes/accessors/TangentNode.js create mode 100644 renderer/jsm/nodes/accessors/TextureNode.js create mode 100644 renderer/jsm/nodes/accessors/UVNode.js create mode 100644 renderer/jsm/nodes/accessors/UserDataNode.js create mode 100644 renderer/jsm/nodes/core/ArrayUniformNode.js create mode 100644 renderer/jsm/nodes/core/AttributeNode.js create mode 100644 renderer/jsm/nodes/core/BypassNode.js create mode 100644 renderer/jsm/nodes/core/CacheNode.js create mode 100644 renderer/jsm/nodes/core/CodeNode.js create mode 100644 renderer/jsm/nodes/core/ConstNode.js create mode 100644 renderer/jsm/nodes/core/ContextNode.js create mode 100644 renderer/jsm/nodes/core/ExpressionNode.js create mode 100644 renderer/jsm/nodes/core/FunctionCallNode.js create mode 100644 renderer/jsm/nodes/core/FunctionNode.js create mode 100644 renderer/jsm/nodes/core/InputNode.js create mode 100644 renderer/jsm/nodes/core/InstanceIndexNode.js create mode 100644 renderer/jsm/nodes/core/LightingModel.js create mode 100644 renderer/jsm/nodes/core/Node.js create mode 100644 renderer/jsm/nodes/core/NodeAttribute.js create mode 100644 renderer/jsm/nodes/core/NodeBuilder.js create mode 100644 renderer/jsm/nodes/core/NodeCache.js create mode 100644 renderer/jsm/nodes/core/NodeCode.js create mode 100644 renderer/jsm/nodes/core/NodeFrame.js create mode 100644 renderer/jsm/nodes/core/NodeFunction.js create mode 100644 renderer/jsm/nodes/core/NodeFunctionInput.js create mode 100644 renderer/jsm/nodes/core/NodeKeywords.js create mode 100644 renderer/jsm/nodes/core/NodeParser.js create mode 100644 renderer/jsm/nodes/core/NodeUniform.js create mode 100644 renderer/jsm/nodes/core/NodeUtils.js create mode 100644 renderer/jsm/nodes/core/NodeVar.js create mode 100644 renderer/jsm/nodes/core/NodeVarying.js create mode 100644 renderer/jsm/nodes/core/PropertyNode.js create mode 100644 renderer/jsm/nodes/core/StackNode.js create mode 100644 renderer/jsm/nodes/core/TempNode.js create mode 100644 renderer/jsm/nodes/core/UniformNode.js create mode 100644 renderer/jsm/nodes/core/VarNode.js create mode 100644 renderer/jsm/nodes/core/VaryingNode.js create mode 100644 renderer/jsm/nodes/core/constants.js create mode 100644 renderer/jsm/nodes/display/BlendModeNode.js create mode 100644 renderer/jsm/nodes/display/ColorAdjustmentNode.js create mode 100644 renderer/jsm/nodes/display/ColorSpaceNode.js create mode 100644 renderer/jsm/nodes/display/FrontFacingNode.js create mode 100644 renderer/jsm/nodes/display/NormalMapNode.js create mode 100644 renderer/jsm/nodes/display/PosterizeNode.js create mode 100644 renderer/jsm/nodes/display/ToneMappingNode.js create mode 100644 renderer/jsm/nodes/display/ViewportNode.js create mode 100644 renderer/jsm/nodes/fog/FogExp2Node.js create mode 100644 renderer/jsm/nodes/fog/FogNode.js create mode 100644 renderer/jsm/nodes/fog/FogRangeNode.js create mode 100644 renderer/jsm/nodes/functions/BSDF/BRDF_BlinnPhong.js create mode 100644 renderer/jsm/nodes/functions/BSDF/BRDF_GGX.js create mode 100644 renderer/jsm/nodes/functions/BSDF/BRDF_Lambert.js create mode 100644 renderer/jsm/nodes/functions/BSDF/DFGApprox.js create mode 100644 renderer/jsm/nodes/functions/BSDF/D_GGX.js create mode 100644 renderer/jsm/nodes/functions/BSDF/F_Schlick.js create mode 100644 renderer/jsm/nodes/functions/BSDF/V_GGX_SmithCorrelated.js create mode 100644 renderer/jsm/nodes/functions/PhongLightingModel.js create mode 100644 renderer/jsm/nodes/functions/PhysicalLightingModel.js create mode 100644 renderer/jsm/nodes/functions/light/getDirectionVector.js create mode 100644 renderer/jsm/nodes/functions/light/getDistanceAttenuation.js create mode 100644 renderer/jsm/nodes/functions/material/getGeometryRoughness.js create mode 100644 renderer/jsm/nodes/functions/material/getRoughness.js create mode 100644 renderer/jsm/nodes/geometry/RangeNode.js create mode 100644 renderer/jsm/nodes/gpgpu/ComputeNode.js create mode 100644 renderer/jsm/nodes/lighting/AONode.js create mode 100644 renderer/jsm/nodes/lighting/AmbientLightNode.js create mode 100644 renderer/jsm/nodes/lighting/AnalyticLightNode.js create mode 100644 renderer/jsm/nodes/lighting/DirectionalLightNode.js create mode 100644 renderer/jsm/nodes/lighting/EnvironmentNode.js create mode 100644 renderer/jsm/nodes/lighting/HemisphereLightNode.js create mode 100644 renderer/jsm/nodes/lighting/IESSpotLightNode.js create mode 100644 renderer/jsm/nodes/lighting/LightingContextNode.js create mode 100644 renderer/jsm/nodes/lighting/LightingNode.js create mode 100644 renderer/jsm/nodes/lighting/LightsNode.js create mode 100644 renderer/jsm/nodes/lighting/PointLightNode.js create mode 100644 renderer/jsm/nodes/lighting/SpotLightNode.js create mode 100644 renderer/jsm/nodes/loaders/NodeLoader.js create mode 100644 renderer/jsm/nodes/loaders/NodeMaterialLoader.js create mode 100644 renderer/jsm/nodes/loaders/NodeObjectLoader.js create mode 100644 renderer/jsm/nodes/materials/LineBasicNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/Materials.js create mode 100644 renderer/jsm/nodes/materials/MeshBasicNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/MeshPhongNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/MeshPhysicalNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/MeshStandardNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/NodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/PointsNodeMaterial.js create mode 100644 renderer/jsm/nodes/materials/SpriteNodeMaterial.js create mode 100644 renderer/jsm/nodes/materialx/DISCLAIMER.md create mode 100644 renderer/jsm/nodes/materialx/MaterialXNodes.js create mode 100644 renderer/jsm/nodes/materialx/lib/mx_hsv.js create mode 100644 renderer/jsm/nodes/materialx/lib/mx_noise.js create mode 100644 renderer/jsm/nodes/materialx/lib/mx_transform_color.js create mode 100644 renderer/jsm/nodes/math/CondNode.js create mode 100644 renderer/jsm/nodes/math/MathNode.js create mode 100644 renderer/jsm/nodes/math/OperatorNode.js create mode 100644 renderer/jsm/nodes/parsers/GLSLNodeFunction.js create mode 100644 renderer/jsm/nodes/parsers/GLSLNodeParser.js create mode 100644 renderer/jsm/nodes/parsers/WGSLNodeFunction.js create mode 100644 renderer/jsm/nodes/parsers/WGSLNodeParser.js create mode 100644 renderer/jsm/nodes/procedural/CheckerNode.js create mode 100644 renderer/jsm/nodes/shadernode/ShaderNode.js create mode 100644 renderer/jsm/nodes/shadernode/ShaderNodeBaseElements.js create mode 100644 renderer/jsm/nodes/shadernode/ShaderNodeElements.js create mode 100644 renderer/jsm/nodes/utils/ArrayElementNode.js create mode 100644 renderer/jsm/nodes/utils/ConvertNode.js create mode 100644 renderer/jsm/nodes/utils/DiscardNode.js create mode 100644 renderer/jsm/nodes/utils/EquirectUVNode.js create mode 100644 renderer/jsm/nodes/utils/JoinNode.js create mode 100644 renderer/jsm/nodes/utils/MatcapUVNode.js create mode 100644 renderer/jsm/nodes/utils/MaxMipLevelNode.js create mode 100644 renderer/jsm/nodes/utils/OscNode.js create mode 100644 renderer/jsm/nodes/utils/RemapNode.js create mode 100644 renderer/jsm/nodes/utils/RotateUVNode.js create mode 100644 renderer/jsm/nodes/utils/SpecularMIPLevelNode.js create mode 100644 renderer/jsm/nodes/utils/SplitNode.js create mode 100644 renderer/jsm/nodes/utils/SpriteSheetUVNode.js create mode 100644 renderer/jsm/nodes/utils/TimerNode.js create mode 100644 renderer/jsm/nodes/utils/TriplanarTexturesNode.js create mode 100644 renderer/jsm/objects/GroundProjectedEnv.js create mode 100644 renderer/jsm/objects/Lensflare.js create mode 100644 renderer/jsm/objects/LightningStorm.js create mode 100644 renderer/jsm/objects/MarchingCubes.js create mode 100644 renderer/jsm/objects/Reflector.js create mode 100644 renderer/jsm/objects/ReflectorForSSRPass.js create mode 100644 renderer/jsm/objects/Refractor.js create mode 100644 renderer/jsm/objects/ShadowMesh.js create mode 100644 renderer/jsm/objects/Sky.js create mode 100644 renderer/jsm/objects/Water.js create mode 100644 renderer/jsm/objects/Water2.js create mode 100644 renderer/jsm/offscreen/jank.js create mode 100644 renderer/jsm/offscreen/offscreen.js create mode 100644 renderer/jsm/offscreen/scene.js create mode 100644 renderer/jsm/physics/AmmoPhysics.js create mode 100644 renderer/jsm/physics/OimoPhysics.js create mode 100644 renderer/jsm/postprocessing/AdaptiveToneMappingPass.js create mode 100644 renderer/jsm/postprocessing/AfterimagePass.js create mode 100644 renderer/jsm/postprocessing/BloomPass.js create mode 100644 renderer/jsm/postprocessing/BokehPass.js create mode 100644 renderer/jsm/postprocessing/ClearPass.js create mode 100644 renderer/jsm/postprocessing/CubeTexturePass.js create mode 100644 renderer/jsm/postprocessing/DotScreenPass.js create mode 100644 renderer/jsm/postprocessing/EffectComposer.js create mode 100644 renderer/jsm/postprocessing/FilmPass.js create mode 100644 renderer/jsm/postprocessing/GlitchPass.js create mode 100644 renderer/jsm/postprocessing/HalftonePass.js create mode 100644 renderer/jsm/postprocessing/LUTPass.js create mode 100644 renderer/jsm/postprocessing/MaskPass.js create mode 100644 renderer/jsm/postprocessing/OutlinePass.js create mode 100644 renderer/jsm/postprocessing/Pass.js create mode 100644 renderer/jsm/postprocessing/RenderPass.js create mode 100644 renderer/jsm/postprocessing/RenderPixelatedPass.js create mode 100644 renderer/jsm/postprocessing/SAOPass.js create mode 100644 renderer/jsm/postprocessing/SMAAPass.js create mode 100644 renderer/jsm/postprocessing/SSAARenderPass.js create mode 100644 renderer/jsm/postprocessing/SSAOPass.js create mode 100644 renderer/jsm/postprocessing/SSRPass.js create mode 100644 renderer/jsm/postprocessing/SavePass.js create mode 100644 renderer/jsm/postprocessing/ShaderPass.js create mode 100644 renderer/jsm/postprocessing/TAARenderPass.js create mode 100644 renderer/jsm/postprocessing/TexturePass.js create mode 100644 renderer/jsm/postprocessing/UnrealBloomPass.js create mode 100644 renderer/jsm/renderers/CSS2DRenderer.js create mode 100644 renderer/jsm/renderers/CSS3DRenderer.js create mode 100644 renderer/jsm/renderers/Projector.js create mode 100644 renderer/jsm/renderers/SVGRenderer.js create mode 100644 renderer/jsm/renderers/webgl/nodes/SlotNode.js create mode 100644 renderer/jsm/renderers/webgl/nodes/WebGLNodeBuilder.js create mode 100644 renderer/jsm/renderers/webgl/nodes/WebGLNodes.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUAnimation.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUAttributes.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUBackground.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUBinding.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUBindings.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUBuffer.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUBufferUtils.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUComputePipelines.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUGeometries.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUInfo.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUObjects.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUProgrammableStage.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUProperties.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPURenderLists.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPURenderPipeline.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPURenderPipelines.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPURenderStates.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPURenderer.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUSampledTexture.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUSampler.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUStorageBuffer.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUTextureRenderer.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUTextureUtils.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUTextures.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUUniform.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUUniformBuffer.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUUniformsGroup.js create mode 100644 renderer/jsm/renderers/webgpu/WebGPUUtils.js create mode 100644 renderer/jsm/renderers/webgpu/constants.js create mode 100644 renderer/jsm/renderers/webgpu/nodes/WebGPUNodeBuilder.js create mode 100644 renderer/jsm/renderers/webgpu/nodes/WebGPUNodeSampledTexture.js create mode 100644 renderer/jsm/renderers/webgpu/nodes/WebGPUNodeSampler.js create mode 100644 renderer/jsm/renderers/webgpu/nodes/WebGPUNodeUniform.js create mode 100644 renderer/jsm/renderers/webgpu/nodes/WebGPUNodes.js create mode 100644 renderer/jsm/shaders/ACESFilmicToneMappingShader.js create mode 100644 renderer/jsm/shaders/AfterimageShader.js create mode 100644 renderer/jsm/shaders/BasicShader.js create mode 100644 renderer/jsm/shaders/BleachBypassShader.js create mode 100644 renderer/jsm/shaders/BlendShader.js create mode 100644 renderer/jsm/shaders/BokehShader.js create mode 100644 renderer/jsm/shaders/BokehShader2.js create mode 100644 renderer/jsm/shaders/BrightnessContrastShader.js create mode 100644 renderer/jsm/shaders/ColorCorrectionShader.js create mode 100644 renderer/jsm/shaders/ColorifyShader.js create mode 100644 renderer/jsm/shaders/ConvolutionShader.js create mode 100644 renderer/jsm/shaders/CopyShader.js create mode 100644 renderer/jsm/shaders/DOFMipMapShader.js create mode 100644 renderer/jsm/shaders/DepthLimitedBlurShader.js create mode 100644 renderer/jsm/shaders/DigitalGlitch.js create mode 100644 renderer/jsm/shaders/DotScreenShader.js create mode 100644 renderer/jsm/shaders/FXAAShader.js create mode 100644 renderer/jsm/shaders/FilmShader.js create mode 100644 renderer/jsm/shaders/FocusShader.js create mode 100644 renderer/jsm/shaders/FreiChenShader.js create mode 100644 renderer/jsm/shaders/GammaCorrectionShader.js create mode 100644 renderer/jsm/shaders/GodRaysShader.js create mode 100644 renderer/jsm/shaders/HalftoneShader.js create mode 100644 renderer/jsm/shaders/HorizontalBlurShader.js create mode 100644 renderer/jsm/shaders/HorizontalTiltShiftShader.js create mode 100644 renderer/jsm/shaders/HueSaturationShader.js create mode 100644 renderer/jsm/shaders/KaleidoShader.js create mode 100644 renderer/jsm/shaders/LuminosityHighPassShader.js create mode 100644 renderer/jsm/shaders/LuminosityShader.js create mode 100644 renderer/jsm/shaders/MMDToonShader.js create mode 100644 renderer/jsm/shaders/MirrorShader.js create mode 100644 renderer/jsm/shaders/NormalMapShader.js create mode 100644 renderer/jsm/shaders/RGBShiftShader.js create mode 100644 renderer/jsm/shaders/SAOShader.js create mode 100644 renderer/jsm/shaders/SMAAShader.js create mode 100644 renderer/jsm/shaders/SSAOShader.js create mode 100644 renderer/jsm/shaders/SSRShader.js create mode 100644 renderer/jsm/shaders/SepiaShader.js create mode 100644 renderer/jsm/shaders/SobelOperatorShader.js create mode 100644 renderer/jsm/shaders/SubsurfaceScatteringShader.js create mode 100644 renderer/jsm/shaders/TechnicolorShader.js create mode 100644 renderer/jsm/shaders/ToneMapShader.js create mode 100644 renderer/jsm/shaders/ToonShader.js create mode 100644 renderer/jsm/shaders/TriangleBlurShader.js create mode 100644 renderer/jsm/shaders/UnpackDepthRGBAShader.js create mode 100644 renderer/jsm/shaders/VelocityShader.js create mode 100644 renderer/jsm/shaders/VerticalBlurShader.js create mode 100644 renderer/jsm/shaders/VerticalTiltShiftShader.js create mode 100644 renderer/jsm/shaders/VignetteShader.js create mode 100644 renderer/jsm/shaders/VolumeShader.js create mode 100644 renderer/jsm/shaders/WaterRefractionShader.js create mode 100644 renderer/jsm/textures/FlakesTexture.js create mode 100644 renderer/jsm/utils/BufferGeometryUtils.js create mode 100644 renderer/jsm/utils/CameraUtils.js create mode 100644 renderer/jsm/utils/GPUStatsPanel.js create mode 100644 renderer/jsm/utils/GeometryCompressionUtils.js create mode 100644 renderer/jsm/utils/GeometryUtils.js create mode 100644 renderer/jsm/utils/LDrawUtils.js create mode 100644 renderer/jsm/utils/PackedPhongMaterial.js create mode 100644 renderer/jsm/utils/SceneUtils.js create mode 100644 renderer/jsm/utils/ShadowMapViewer.js create mode 100644 renderer/jsm/utils/SkeletonUtils.js create mode 100644 renderer/jsm/utils/UVsDebug.js create mode 100644 renderer/jsm/utils/WorkerPool.js create mode 100644 renderer/jsm/webxr/ARButton.js create mode 100644 renderer/jsm/webxr/OculusHandModel.js create mode 100644 renderer/jsm/webxr/OculusHandPointerModel.js create mode 100644 renderer/jsm/webxr/Text2D.js create mode 100644 renderer/jsm/webxr/VRButton.js create mode 100644 renderer/jsm/webxr/XRControllerModelFactory.js create mode 100644 renderer/jsm/webxr/XREstimatedLight.js create mode 100644 renderer/jsm/webxr/XRHandMeshModel.js create mode 100644 renderer/jsm/webxr/XRHandModelFactory.js create mode 100644 renderer/jsm/webxr/XRHandPrimitiveModel.js create mode 100644 renderer/main.css create mode 100644 renderer/package-lock.json create mode 100644 renderer/package.json create mode 100644 renderer/utils/build/rollup.config.js create mode 100644 renderer/utils/packLDrawModel.js diff --git a/renderer/README.md b/renderer/README.md new file mode 100644 index 0000000..a032a35 --- /dev/null +++ b/renderer/README.md @@ -0,0 +1,84 @@ +# three.js + +[![NPM Package][npm]][npm-url] +[![Build Size][build-size]][build-size-url] +[![NPM Downloads][npm-downloads]][npmtrends-url] +[![DeepScan][deepscan]][deepscan-url] +[![Discord][discord]][discord-url] + +#### JavaScript 3D library + +The aim of the project is to create an easy to use, lightweight, cross-browser, general purpose 3D library. The current builds only include a WebGL renderer but WebGPU (experimental), SVG and CSS3D renderers are also available as addons. + +[Examples](https://threejs.org/examples/) — +[Docs](https://threejs.org/docs/) — +[Manual](https://threejs.org/manual/) — +[Wiki](https://github.com/mrdoob/three.js/wiki) — +[Migrating](https://github.com/mrdoob/three.js/wiki/Migration-Guide) — +[Questions](https://stackoverflow.com/questions/tagged/three.js) — +[Forum](https://discourse.threejs.org/) — +[Discord](https://discord.gg/56GBJwAnUS) + +### Usage + +This code creates a scene, a camera, and a geometric cube, and it adds the cube to the scene. It then creates a `WebGL` renderer for the scene and camera, and it adds that viewport to the `document.body` element. Finally, it animates the cube within the scene for the camera. + +```javascript +import * as THREE from 'three'; + +// init + +const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 ); +camera.position.z = 1; + +const scene = new THREE.Scene(); + +const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 ); +const material = new THREE.MeshNormalMaterial(); + +const mesh = new THREE.Mesh( geometry, material ); +scene.add( mesh ); + +const renderer = new THREE.WebGLRenderer( { antialias: true } ); +renderer.setSize( window.innerWidth, window.innerHeight ); +renderer.setAnimationLoop( animation ); +document.body.appendChild( renderer.domElement ); + +// animation + +function animation( time ) { + + mesh.rotation.x = time / 2000; + mesh.rotation.y = time / 1000; + + renderer.render( scene, camera ); + +} +``` + +If everything went well, you should see [this](https://jsfiddle.net/7u84j6kp/). + +### Cloning this repository + +Cloning the repo with all its history results in a ~2 GB download. If you don't need the whole history you can use the `depth` parameter to significantly reduce download size. + +```sh +git clone --depth=1 https://github.com/mrdoob/three.js.git +``` + +### Change log + +[Releases](https://github.com/mrdoob/three.js/releases) + + +[npm]: https://img.shields.io/npm/v/three +[npm-url]: https://www.npmjs.com/package/three +[build-size]: https://badgen.net/bundlephobia/minzip/three +[build-size-url]: https://bundlephobia.com/result?p=three +[npm-downloads]: https://img.shields.io/npm/dw/three +[npmtrends-url]: https://www.npmtrends.com/three +[deepscan]: https://deepscan.io/api/teams/16600/projects/19901/branches/525701/badge/grade.svg +[deepscan-url]: https://deepscan.io/dashboard#view=project&tid=16600&pid=19901&bid=525701 +[discord]: https://img.shields.io/discord/685241246557667386 +[discord-url]: https://discord.gg/56GBJwAnUS + diff --git a/renderer/build/three.cjs b/renderer/build/three.cjs new file mode 100644 index 0000000..02538f8 --- /dev/null +++ b/renderer/build/three.cjs @@ -0,0 +1,50591 @@ +/** + * @license + * Copyright 2010-2023 Three.js Authors + * SPDX-License-Identifier: MIT + */ +'use strict'; + +const REVISION = '149dev'; +const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; +const CullFaceNone = 0; +const CullFaceBack = 1; +const CullFaceFront = 2; +const CullFaceFrontBack = 3; +const BasicShadowMap = 0; +const PCFShadowMap = 1; +const PCFSoftShadowMap = 2; +const VSMShadowMap = 3; +const FrontSide = 0; +const BackSide = 1; +const DoubleSide = 2; +const TwoPassDoubleSide = 3; +const NoBlending = 0; +const NormalBlending = 1; +const AdditiveBlending = 2; +const SubtractiveBlending = 3; +const MultiplyBlending = 4; +const CustomBlending = 5; +const AddEquation = 100; +const SubtractEquation = 101; +const ReverseSubtractEquation = 102; +const MinEquation = 103; +const MaxEquation = 104; +const ZeroFactor = 200; +const OneFactor = 201; +const SrcColorFactor = 202; +const OneMinusSrcColorFactor = 203; +const SrcAlphaFactor = 204; +const OneMinusSrcAlphaFactor = 205; +const DstAlphaFactor = 206; +const OneMinusDstAlphaFactor = 207; +const DstColorFactor = 208; +const OneMinusDstColorFactor = 209; +const SrcAlphaSaturateFactor = 210; +const NeverDepth = 0; +const AlwaysDepth = 1; +const LessDepth = 2; +const LessEqualDepth = 3; +const EqualDepth = 4; +const GreaterEqualDepth = 5; +const GreaterDepth = 6; +const NotEqualDepth = 7; +const MultiplyOperation = 0; +const MixOperation = 1; +const AddOperation = 2; +const NoToneMapping = 0; +const LinearToneMapping = 1; +const ReinhardToneMapping = 2; +const CineonToneMapping = 3; +const ACESFilmicToneMapping = 4; +const CustomToneMapping = 5; + +const UVMapping = 300; +const CubeReflectionMapping = 301; +const CubeRefractionMapping = 302; +const EquirectangularReflectionMapping = 303; +const EquirectangularRefractionMapping = 304; +const CubeUVReflectionMapping = 306; +const RepeatWrapping = 1000; +const ClampToEdgeWrapping = 1001; +const MirroredRepeatWrapping = 1002; +const NearestFilter = 1003; +const NearestMipmapNearestFilter = 1004; +const NearestMipMapNearestFilter = 1004; +const NearestMipmapLinearFilter = 1005; +const NearestMipMapLinearFilter = 1005; +const LinearFilter = 1006; +const LinearMipmapNearestFilter = 1007; +const LinearMipMapNearestFilter = 1007; +const LinearMipmapLinearFilter = 1008; +const LinearMipMapLinearFilter = 1008; +const UnsignedByteType = 1009; +const ByteType = 1010; +const ShortType = 1011; +const UnsignedShortType = 1012; +const IntType = 1013; +const UnsignedIntType = 1014; +const FloatType = 1015; +const HalfFloatType = 1016; +const UnsignedShort4444Type = 1017; +const UnsignedShort5551Type = 1018; +const UnsignedInt248Type = 1020; +const AlphaFormat = 1021; +const RGBAFormat = 1023; +const LuminanceFormat = 1024; +const LuminanceAlphaFormat = 1025; +const DepthFormat = 1026; +const DepthStencilFormat = 1027; +const RedFormat = 1028; +const RedIntegerFormat = 1029; +const RGFormat = 1030; +const RGIntegerFormat = 1031; +const RGBAIntegerFormat = 1033; + +const RGB_S3TC_DXT1_Format = 33776; +const RGBA_S3TC_DXT1_Format = 33777; +const RGBA_S3TC_DXT3_Format = 33778; +const RGBA_S3TC_DXT5_Format = 33779; +const RGB_PVRTC_4BPPV1_Format = 35840; +const RGB_PVRTC_2BPPV1_Format = 35841; +const RGBA_PVRTC_4BPPV1_Format = 35842; +const RGBA_PVRTC_2BPPV1_Format = 35843; +const RGB_ETC1_Format = 36196; +const RGB_ETC2_Format = 37492; +const RGBA_ETC2_EAC_Format = 37496; +const RGBA_ASTC_4x4_Format = 37808; +const RGBA_ASTC_5x4_Format = 37809; +const RGBA_ASTC_5x5_Format = 37810; +const RGBA_ASTC_6x5_Format = 37811; +const RGBA_ASTC_6x6_Format = 37812; +const RGBA_ASTC_8x5_Format = 37813; +const RGBA_ASTC_8x6_Format = 37814; +const RGBA_ASTC_8x8_Format = 37815; +const RGBA_ASTC_10x5_Format = 37816; +const RGBA_ASTC_10x6_Format = 37817; +const RGBA_ASTC_10x8_Format = 37818; +const RGBA_ASTC_10x10_Format = 37819; +const RGBA_ASTC_12x10_Format = 37820; +const RGBA_ASTC_12x12_Format = 37821; +const RGBA_BPTC_Format = 36492; +const RED_RGTC1_Format = 36283; +const SIGNED_RED_RGTC1_Format = 36284; +const RED_GREEN_RGTC2_Format = 36285; +const SIGNED_RED_GREEN_RGTC2_Format = 36286; +const LoopOnce = 2200; +const LoopRepeat = 2201; +const LoopPingPong = 2202; +const InterpolateDiscrete = 2300; +const InterpolateLinear = 2301; +const InterpolateSmooth = 2302; +const ZeroCurvatureEnding = 2400; +const ZeroSlopeEnding = 2401; +const WrapAroundEnding = 2402; +const NormalAnimationBlendMode = 2500; +const AdditiveAnimationBlendMode = 2501; +const TrianglesDrawMode = 0; +const TriangleStripDrawMode = 1; +const TriangleFanDrawMode = 2; +const LinearEncoding = 3000; +const sRGBEncoding = 3001; +const BasicDepthPacking = 3200; +const RGBADepthPacking = 3201; +const TangentSpaceNormalMap = 0; +const ObjectSpaceNormalMap = 1; + +// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. +const NoColorSpace = ''; +const SRGBColorSpace = 'srgb'; +const LinearSRGBColorSpace = 'srgb-linear'; + +const ZeroStencilOp = 0; +const KeepStencilOp = 7680; +const ReplaceStencilOp = 7681; +const IncrementStencilOp = 7682; +const DecrementStencilOp = 7683; +const IncrementWrapStencilOp = 34055; +const DecrementWrapStencilOp = 34056; +const InvertStencilOp = 5386; + +const NeverStencilFunc = 512; +const LessStencilFunc = 513; +const EqualStencilFunc = 514; +const LessEqualStencilFunc = 515; +const GreaterStencilFunc = 516; +const NotEqualStencilFunc = 517; +const GreaterEqualStencilFunc = 518; +const AlwaysStencilFunc = 519; + +const StaticDrawUsage = 35044; +const DynamicDrawUsage = 35048; +const StreamDrawUsage = 35040; +const StaticReadUsage = 35045; +const DynamicReadUsage = 35049; +const StreamReadUsage = 35041; +const StaticCopyUsage = 35046; +const DynamicCopyUsage = 35050; +const StreamCopyUsage = 35042; + +const GLSL1 = '100'; +const GLSL3 = '300 es'; + +const _SRGBAFormat = 1035; // fallback for WebGL 1 + +/** + * https://github.com/mrdoob/eventdispatcher.js/ + */ + +class EventDispatcher { + + addEventListener( type, listener ) { + + if ( this._listeners === undefined ) this._listeners = {}; + + const listeners = this._listeners; + + if ( listeners[ type ] === undefined ) { + + listeners[ type ] = []; + + } + + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + + listeners[ type ].push( listener ); + + } + + } + + hasEventListener( type, listener ) { + + if ( this._listeners === undefined ) return false; + + const listeners = this._listeners; + + return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; + + } + + removeEventListener( type, listener ) { + + if ( this._listeners === undefined ) return; + + const listeners = this._listeners; + const listenerArray = listeners[ type ]; + + if ( listenerArray !== undefined ) { + + const index = listenerArray.indexOf( listener ); + + if ( index !== - 1 ) { + + listenerArray.splice( index, 1 ); + + } + + } + + } + + dispatchEvent( event ) { + + if ( this._listeners === undefined ) return; + + const listeners = this._listeners; + const listenerArray = listeners[ event.type ]; + + if ( listenerArray !== undefined ) { + + event.target = this; + + // Make a copy, in case listeners are removed while iterating. + const array = listenerArray.slice( 0 ); + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + array[ i ].call( this, event ); + + } + + event.target = null; + + } + + } + +} + +const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + +let _seed = 1234567; + + +const DEG2RAD = Math.PI / 180; +const RAD2DEG = 180 / Math.PI; + +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 +function generateUUID() { + + const d0 = Math.random() * 0xffffffff | 0; + const d1 = Math.random() * 0xffffffff | 0; + const d2 = Math.random() * 0xffffffff | 0; + const d3 = Math.random() * 0xffffffff | 0; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; + + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); + +} + +function clamp( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); + +} + +// compute euclidean modulo of m % n +// https://en.wikipedia.org/wiki/Modulo_operation +function euclideanModulo( n, m ) { + + return ( ( n % m ) + m ) % m; + +} + +// Linear mapping from range to range +function mapLinear( x, a1, a2, b1, b2 ) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + +} + +// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ +function inverseLerp( x, y, value ) { + + if ( x !== y ) { + + return ( value - x ) / ( y - x ); + + } else { + + return 0; + + } + +} + +// https://en.wikipedia.org/wiki/Linear_interpolation +function lerp( x, y, t ) { + + return ( 1 - t ) * x + t * y; + +} + +// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ +function damp( x, y, lambda, dt ) { + + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); + +} + +// https://www.desmos.com/calculator/vcsjnyz7x4 +function pingpong( x, length = 1 ) { + + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); + +} + +// http://en.wikipedia.org/wiki/Smoothstep +function smoothstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * ( 3 - 2 * x ); + +} + +function smootherstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + +} + +// Random integer from interval +function randInt( low, high ) { + + return low + Math.floor( Math.random() * ( high - low + 1 ) ); + +} + +// Random float from interval +function randFloat( low, high ) { + + return low + Math.random() * ( high - low ); + +} + +// Random float from <-range/2, range/2> interval +function randFloatSpread( range ) { + + return range * ( 0.5 - Math.random() ); + +} + +// Deterministic pseudo-random float in the interval [ 0, 1 ] +function seededRandom( s ) { + + if ( s !== undefined ) _seed = s; + + // Mulberry32 generator + + let t = _seed += 0x6D2B79F5; + + t = Math.imul( t ^ t >>> 15, t | 1 ); + + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); + + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; + +} + +function degToRad( degrees ) { + + return degrees * DEG2RAD; + +} + +function radToDeg( radians ) { + + return radians * RAD2DEG; + +} + +function isPowerOfTwo( value ) { + + return ( value & ( value - 1 ) ) === 0 && value !== 0; + +} + +function ceilPowerOfTwo( value ) { + + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + +} + +function floorPowerOfTwo( value ) { + + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + +} + +function setQuaternionFromProperEuler( q, a, b, c, order ) { + + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles + + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians + + const cos = Math.cos; + const sin = Math.sin; + + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); + + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); + + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); + + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); + + switch ( order ) { + + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; + + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; + + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; + + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; + + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; + + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; + + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + + } + +} + +function denormalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return value / 65535.0; + + case Uint8Array: + + return value / 255.0; + + case Int16Array: + + return Math.max( value / 32767.0, - 1.0 ); + + case Int8Array: + + return Math.max( value / 127.0, - 1.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + + return Math.round( value * 255.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +var MathUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + ceilPowerOfTwo: ceilPowerOfTwo, + clamp: clamp, + damp: damp, + degToRad: degToRad, + denormalize: denormalize, + euclideanModulo: euclideanModulo, + floorPowerOfTwo: floorPowerOfTwo, + generateUUID: generateUUID, + inverseLerp: inverseLerp, + isPowerOfTwo: isPowerOfTwo, + lerp: lerp, + mapLinear: mapLinear, + normalize: normalize, + pingpong: pingpong, + radToDeg: radToDeg, + randFloat: randFloat, + randFloatSpread: randFloatSpread, + randInt: randInt, + seededRandom: seededRandom, + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + smootherstep: smootherstep, + smoothstep: smoothstep +}); + +class Vector2 { + + constructor( x = 0, y = 0 ) { + + Vector2.prototype.isVector2 = true; + + this.x = x; + this.y = y; + + } + + get width() { + + return this.x; + + } + + set width( value ) { + + this.x = value; + + } + + get height() { + + return this.y; + + } + + set height( value ) { + + this.y = value; + + } + + set( x, y ) { + + this.x = x; + this.y = y; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + + return this; + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + + return this; + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + + return this; + + } + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y; + + } + + cross( v ) { + + return this.x * v.y - this.y * v.x; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + angle() { + + // computes the angle in radians with respect to the positive x-axis + + const angle = Math.atan2( - this.y, - this.x ) + Math.PI; + + return angle; + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + + return this; + + } + + rotateAround( center, angle ) { + + const c = Math.cos( angle ), s = Math.sin( angle ); + + const x = this.x - center.x; + const y = this.y - center.y; + + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } + +} + +class Matrix3 { + + constructor() { + + Matrix3.prototype.isMatrix3 = true; + + this.elements = [ + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + + const te = this.elements; + + 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; + + } + + identity() { + + this.set( + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ); + + return this; + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); + + return this; + + } + + setFromMatrix4( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] + + ); + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + + const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + + return this; + + } + + multiplyScalar( s ) { + + const te = this.elements; + + 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; + + return this; + + } + + determinant() { + + const te = this.elements; + + const 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 a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + + } + + invert() { + + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], + n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], + n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], + + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, + + det = n11 * t11 + n21 * t12 + n31 * t13; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + + return this; + + } + + transpose() { + + let tmp; + const 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; + + return this; + + } + + getNormalMatrix( matrix4 ) { + + return this.setFromMatrix4( matrix4 ).invert().transpose(); + + } + + transposeIntoArray( r ) { + + const m = this.elements; + + 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 ]; + + return this; + + } + + setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { + + const c = Math.cos( rotation ); + const s = Math.sin( rotation ); + + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); + + return this; + + } + + // + + scale( sx, sy ) { + + this.premultiply( _m3.makeScale( sx, sy ) ); + + return this; + + } + + rotate( theta ) { + + this.premultiply( _m3.makeRotation( - theta ) ); + + return this; + + } + + translate( tx, ty ) { + + this.premultiply( _m3.makeTranslation( tx, ty ) ); + + return this; + + } + + // for 2D Transforms + + makeTranslation( x, y ) { + + this.set( + + 1, 0, x, + 0, 1, y, + 0, 0, 1 + + ); + + return this; + + } + + makeRotation( theta ) { + + // counterclockwise + + const c = Math.cos( theta ); + const s = Math.sin( theta ); + + this.set( + + c, - s, 0, + s, c, 0, + 0, 0, 1 + + ); + + return this; + + } + + makeScale( x, y ) { + + this.set( + + x, 0, 0, + 0, y, 0, + 0, 0, 1 + + ); + + return this; + + } + + // + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 9; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; + + return array; + + } + + clone() { + + return new this.constructor().fromArray( this.elements ); + + } + +} + +const _m3 = /*@__PURE__*/ new Matrix3(); + +function arrayNeedsUint32( array ) { + + // assumes larger values usually on last + + for ( let i = array.length - 1; i >= 0; -- i ) { + + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + + } + + return false; + +} + +const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; + +function getTypedArray( type, buffer ) { + + return new TYPED_ARRAYS[ type ]( buffer ); + +} + +function createElementNS( name ) { + + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); + +} + +function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + +} + +function LinearToSRGB( c ) { + + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + +} + +// JavaScript RGB-to-RGB transforms, defined as +// FN[InputColorSpace][OutputColorSpace] callback functions. +const FN = { + [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear }, + [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB }, +}; + +const ColorManagement = { + + legacyMode: true, + + get workingColorSpace() { + + return LinearSRGBColorSpace; + + }, + + set workingColorSpace( colorSpace ) { + + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); + + }, + + convert: function ( color, sourceColorSpace, targetColorSpace ) { + + if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { + + return color; + + } + + if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) { + + const fn = FN[ sourceColorSpace ][ targetColorSpace ]; + + color.r = fn( color.r ); + color.g = fn( color.g ); + color.b = fn( color.b ); + + return color; + + } + + throw new Error( 'Unsupported color space conversion.' ); + + }, + + fromWorkingColorSpace: function ( color, targetColorSpace ) { + + return this.convert( color, this.workingColorSpace, targetColorSpace ); + + }, + + toWorkingColorSpace: function ( color, sourceColorSpace ) { + + return this.convert( color, sourceColorSpace, this.workingColorSpace ); + + }, + +}; + +const _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, 'rebeccapurple': 0x663399, '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 }; + +const _rgb$1 = { r: 0, g: 0, b: 0 }; +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; + +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; + +} + +function toComponents( source, target ) { + + target.r = source.r; + target.g = source.g; + target.b = source.b; + + return target; + +} + +class Color { + + constructor( r, g, b ) { + + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + return this.set( r ); + + } + + return this.setRGB( r, g, b ); + + } + + set( value ) { + + if ( value && value.isColor ) { + + this.copy( value ); + + } else if ( typeof value === 'number' ) { + + this.setHex( value ); + + } else if ( typeof value === 'string' ) { + + this.setStyle( value ); + + } + + return this; + + } + + setScalar( scalar ) { + + this.r = scalar; + this.g = scalar; + this.b = scalar; + + return this; + + } + + setHex( hex, colorSpace = SRGBColorSpace ) { + + hex = Math.floor( hex ); + + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { + + this.r = r; + this.g = g; + this.b = b; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); + + if ( s === 0 ) { + + this.r = this.g = this.b = l; + + } else { + + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const 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 ); + + } + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setStyle( style, colorSpace = SRGBColorSpace ) { + + function handleAlpha( string ) { + + if ( string === undefined ) return; + + if ( parseFloat( string ) < 1 ) { + + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + + } + + } + + + let m; + + if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { + + // rgb / hsl + + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; + + switch ( name ) { + + case 'rgb': + case 'rgba': + + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // 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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + break; + + case 'hsl': + case 'hsla': + + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + const h = parseFloat( color[ 1 ] ) / 360; + const s = parseFloat( color[ 2 ] ) / 100; + const l = parseFloat( color[ 3 ] ) / 100; + + handleAlpha( color[ 4 ] ); + + return this.setHSL( h, s, l, colorSpace ); + + } + + break; + + } + + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + + // hex color + + const hex = m[ 1 ]; + const size = hex.length; + + if ( size === 3 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } else if ( size === 6 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + } + + if ( style && style.length > 0 ) { + + return this.setColorName( style, colorSpace ); + + } + + return this; + + } + + setColorName( style, colorSpace = SRGBColorSpace ) { + + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; + + if ( hex !== undefined ) { + + // red + this.setHex( hex, colorSpace ); + + } else { + + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); + + } + + return this; + + } + + clone() { + + return new this.constructor( this.r, this.g, this.b ); + + } + + copy( color ) { + + this.r = color.r; + this.g = color.g; + this.b = color.b; + + return this; + + } + + copySRGBToLinear( color ) { + + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); + + return this; + + } + + copyLinearToSRGB( color ) { + + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); + + return this; + + } + + convertSRGBToLinear() { + + this.copySRGBToLinear( this ); + + return this; + + } + + convertLinearToSRGB() { + + this.copyLinearToSRGB( this ); + + return this; + + } + + getHex( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0; + + } + + getHexString( colorSpace = SRGBColorSpace ) { + + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); + + } + + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b; + + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); + + let hue, saturation; + const lightness = ( min + max ) / 2.0; + + if ( min === max ) { + + hue = 0; + saturation = 0; + + } else { + + const delta = max - min; + + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + 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; + + } + + hue /= 6; + + } + + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + + } + + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + target.r = _rgb$1.r; + target.g = _rgb$1.g; + target.b = _rgb$1.b; + + return target; + + } + + getStyle( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + if ( colorSpace !== SRGBColorSpace ) { + + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`; + + } + + return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`; + + } + + offsetHSL( h, s, l ) { + + this.getHSL( _hslA ); + + _hslA.h += h; _hslA.s += s; _hslA.l += l; + + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + + return this; + + } + + add( color ) { + + this.r += color.r; + this.g += color.g; + this.b += color.b; + + return this; + + } + + addColors( color1, color2 ) { + + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + + return this; + + } + + addScalar( s ) { + + this.r += s; + this.g += s; + this.b += s; + + return this; + + } + + sub( color ) { + + 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; + + } + + multiply( color ) { + + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + + return this; + + } + + multiplyScalar( s ) { + + this.r *= s; + this.g *= s; + this.b *= s; + + return this; + + } + + lerp( color, alpha ) { + + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; + + return this; + + } + + lerpColors( color1, color2, alpha ) { + + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; + + return this; + + } + + lerpHSL( color, alpha ) { + + this.getHSL( _hslA ); + color.getHSL( _hslB ); + + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); + + return this; + + } + + equals( c ) { + + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + + } + + fromArray( array, offset = 0 ) { + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); + + return this; + + } + + toJSON() { + + return this.getHex(); + + } + + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + +} + +Color.NAMES = _colorKeywords; + +let _canvas; + +class ImageUtils { + + static getDataURL( image ) { + + if ( /^data:/i.test( image.src ) ) { + + return image.src; + + } + + if ( typeof HTMLCanvasElement == 'undefined' ) { + + return image.src; + + } + + let canvas; + + if ( image instanceof HTMLCanvasElement ) { + + canvas = image; + + } else { + + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); + + _canvas.width = image.width; + _canvas.height = image.height; + + const context = _canvas.getContext( '2d' ); + + if ( image instanceof ImageData ) { + + context.putImageData( image, 0, 0 ); + + } else { + + context.drawImage( image, 0, 0, image.width, image.height ); + + } + + canvas = _canvas; + + } + + if ( canvas.width > 2048 || canvas.height > 2048 ) { + + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); + + return canvas.toDataURL( 'image/jpeg', 0.6 ); + + } else { + + return canvas.toDataURL( 'image/png' ); + + } + + } + + static sRGBToLinear( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const canvas = createElementNS( 'canvas' ); + + canvas.width = image.width; + canvas.height = image.height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); + + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; + + for ( let i = 0; i < data.length; i ++ ) { + + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; + + } + + context.putImageData( imageData, 0, 0 ); + + return canvas; + + } else if ( image.data ) { + + const data = image.data.slice( 0 ); + + for ( let i = 0; i < data.length; i ++ ) { + + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { + + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); + + } else { + + // assuming float + + data[ i ] = SRGBToLinear( data[ i ] ); + + } + + } + + return { + data: data, + width: image.width, + height: image.height + }; + + } else { + + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; + + } + + } + +} + +class Source { + + constructor( data = null ) { + + this.isSource = true; + + this.uuid = generateUUID(); + + this.data = data; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { + + return meta.images[ this.uuid ]; + + } + + const output = { + uuid: this.uuid, + url: '' + }; + + const data = this.data; + + if ( data !== null ) { + + let url; + + if ( Array.isArray( data ) ) { + + // cube texture + + url = []; + + for ( let i = 0, l = data.length; i < l; i ++ ) { + + if ( data[ i ].isDataTexture ) { + + url.push( serializeImage( data[ i ].image ) ); + + } else { + + url.push( serializeImage( data[ i ] ) ); + + } + + } + + } else { + + // texture + + url = serializeImage( data ); + + } + + output.url = url; + + } + + if ( ! isRootObject ) { + + meta.images[ this.uuid ] = output; + + } + + return output; + + } + +} + +function serializeImage( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + // default images + + return ImageUtils.getDataURL( image ); + + } else { + + if ( image.data ) { + + // images of DataTexture + + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + + } else { + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); + return {}; + + } + + } + +} + +let textureId = 0; + +class Texture extends EventDispatcher { + + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding ) { + + super(); + + this.isTexture = true; + + Object.defineProperty( this, 'id', { value: textureId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + + this.source = new Source( image ); + this.mipmaps = []; + + this.mapping = mapping; + + this.wrapS = wrapS; + this.wrapT = wrapT; + + this.magFilter = magFilter; + this.minFilter = minFilter; + + this.anisotropy = anisotropy; + + this.format = format; + this.internalFormat = null; + this.type = type; + + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; + + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + + 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) + + // 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; + + this.userData = {}; + + this.version = 0; + this.onUpdate = null; + + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not + this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) + + } + + get image() { + + return this.source.data; + + } + + set image( value ) { + + this.source.data = value; + + } + + updateMatrix() { + + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); + + this.mapping = source.mapping; + + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + + this.anisotropy = source.anisotropy; + + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); + + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + this.needsUpdate = true; + + return this; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + + return meta.textures[ this.uuid ]; + + } + + const output = { + + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, + + uuid: this.uuid, + name: this.name, + + image: this.source.toJSON( meta ).uuid, + + mapping: this.mapping, + + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, + + wrap: [ this.wrapS, this.wrapT ], + + format: this.format, + type: this.type, + encoding: this.encoding, + + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + + flipY: this.flipY, + + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + + }; + + if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData; + + if ( ! isRootObject ) { + + meta.textures[ this.uuid ] = output; + + } + + return output; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + transformUv( uv ) { + + if ( this.mapping !== UVMapping ) return uv; + + uv.applyMatrix3( this.matrix ); + + if ( uv.x < 0 || uv.x > 1 ) { + + switch ( this.wrapS ) { + + case RepeatWrapping: + + uv.x = uv.x - Math.floor( uv.x ); + break; + + case ClampToEdgeWrapping: + + uv.x = uv.x < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + + uv.x = Math.ceil( uv.x ) - uv.x; + + } else { + + uv.x = uv.x - Math.floor( uv.x ); + + } + + break; + + } + + } + + if ( uv.y < 0 || uv.y > 1 ) { + + switch ( this.wrapT ) { + + case RepeatWrapping: + + uv.y = uv.y - Math.floor( uv.y ); + break; + + case ClampToEdgeWrapping: + + uv.y = uv.y < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + + uv.y = Math.ceil( uv.y ) - uv.y; + + } else { + + uv.y = uv.y - Math.floor( uv.y ); + + } + + break; + + } + + } + + if ( this.flipY ) { + + uv.y = 1 - uv.y; + + } + + return uv; + + } + + set needsUpdate( value ) { + + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } + + } + +} + +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; + +class Vector4 { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + Vector4.prototype.isVector4 = true; + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + } + + get width() { + + return this.z; + + } + + set width( value ) { + + this.z = value; + + } + + get height() { + + return this.w; + + } + + set height( value ) { + + this.w = value; + + } + + set( x, y, z, w ) { + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setW( w ) { + + this.w = w; + + return this; + + } + + setComponent( index, value ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z, this.w ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + this.w += s; + + return this; + + } + + addVectors( 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( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + + return this; + + } + + subVectors( 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; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + + return this; + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z, w = this.w; + const 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; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + setAxisAngleFromQuaternion( q ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + + // q is assumed to be normalized + + this.w = 2 * Math.acos( q.w ); + + const s = Math.sqrt( 1 - q.w * q.w ); + + if ( s < 0.0001 ) { + + this.x = 1; + this.y = 0; + this.z = 0; + + } else { + + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + + } + + return this; + + } + + setAxisAngleFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + + 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 ]; + + 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 + + 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 + + this.set( 1, 0, 0, 0 ); + + return this; // zero angle, arbitrary axis + + } + + // otherwise this singularity is angle = 180 + + angle = Math.PI; + + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; + + if ( ( xx > yy ) && ( xx > zz ) ) { + + // m11 is the largest diagonal term + + if ( xx < epsilon ) { + + x = 0; + y = 0.707106781; + z = 0.707106781; + + } else { + + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; + + } + + } else if ( yy > zz ) { + + // m22 is the largest diagonal term + + if ( yy < epsilon ) { + + x = 0.707106781; + y = 0; + z = 0.707106781; + + } else { + + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; + + } + + } else { + + // m33 is the largest diagonal term so base result on this + + if ( zz < epsilon ) { + + x = 0.707106781; + y = 0.707106781; + z = 0; + + } else { + + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; + + } + + } + + this.set( x, y, z, angle ); + + return this; // return 180 deg rotation + + } + + // as we have reached here there are no singularities so we can handle normally + + let 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 ); + + return this; + + } + + min( v ) { + + 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; + + } + + max( 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 ); + this.w = Math.max( this.w, v.w ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + 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() { + + 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() { + + 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() { + + 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; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + 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; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + yield this.w; + + } + +} + +/* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers +*/ +class WebGLRenderTarget extends EventDispatcher { + + constructor( width = 1, height = 1, options = {} ) { + + super(); + + this.isWebGLRenderTarget = true; + + this.width = width; + this.height = height; + this.depth = 1; + + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; + + this.viewport = new Vector4( 0, 0, width, height ); + + const image = { width: width, height: height, depth: 1 }; + + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; + + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; + + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + + this.samples = options.samples !== undefined ? options.samples : 0; + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.copy( source.viewport ); + + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; + + // ensure image object is not shared, see #20328 + + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.samples = source.samples; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class DataArrayTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + super( null ); + + this.isDataArrayTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +class WebGLArrayRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGLArrayRenderTarget = true; + + this.depth = depth; + + this.texture = new DataArrayTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +class Data3DTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + super( null ); + + this.isData3DTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +class WebGL3DRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGL3DRenderTarget = true; + + this.depth = depth; + + this.texture = new Data3DTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +class WebGLMultipleRenderTargets extends WebGLRenderTarget { + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + super( width, height, options ); + + this.isWebGLMultipleRenderTargets = true; + + const texture = this.texture; + + this.texture = []; + + for ( let i = 0; i < count; i ++ ) { + + this.texture[ i ] = texture.clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + for ( let i = 0, il = this.texture.length; i < il; i ++ ) { + + this.texture[ i ].image.width = width; + this.texture[ i ].image.height = height; + this.texture[ i ].image.depth = depth; + + } + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + return this; + + } + + copy( source ) { + + this.dispose(); + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.set( 0, 0, this.width, this.height ); + this.scissor.set( 0, 0, this.width, this.height ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.texture.length = 0; + + for ( let i = 0, il = source.texture.length; i < il; i ++ ) { + + this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + return this; + + } + +} + +class Quaternion { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + this.isQuaternion = true; + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + } + + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + + // fuzz-free, array-based Quaternion SLERP operation + + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; + + if ( t === 0 ) { + + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; + + } + + if ( t === 1 ) { + + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; + + } + + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; + + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { + + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); + + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; + + } + + const tDir = t * dir; + + 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 ) { + + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + + } + + } + + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + + } + + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; + + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + + return dst; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get w() { + + return this._w; + + } + + set w( value ) { + + this._w = value; + this._onChangeCallback(); + + } + + set( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._w ); + + } + + copy( quaternion ) { + + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); + + return this; + + } + + setFromEuler( euler, update ) { + + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m + + const cos = Math.cos; + const sin = Math.sin; + + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); + + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); + + switch ( order ) { + + case 'XYZ': + 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; + break; + + case '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; + break; + + case 'ZXY': + 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; + break; + + case '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; + break; + + case '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; + break; + + case 'XZY': + 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; + break; + + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + + } + + if ( update !== false ) this._onChangeCallback(); + + return this; + + } + + setFromAxisAngle( axis, angle ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + + // assumes axis is normalized + + const halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const 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 ], + + trace = m11 + m22 + m33; + + if ( trace > 0 ) { + + const s = 0.5 / Math.sqrt( trace + 1.0 ); + + 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 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; + + } else { + + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._onChangeCallback(); + + return this; + + } + + setFromUnitVectors( vFrom, vTo ) { + + // assumes direction vectors vFrom and vTo are normalized + + let r = vFrom.dot( vTo ) + 1; + + if ( r < Number.EPSILON ) { + + // vFrom and vTo point in opposite directions + + r = 0; + + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + + } else { + + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; + + } + + } else { + + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + + } + + return this.normalize(); + + } + + angleTo( q ) { + + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); + + } + + rotateTowards( q, step ) { + + const angle = this.angleTo( q ); + + if ( angle === 0 ) return this; + + const t = Math.min( 1, step / angle ); + + this.slerp( q, t ); + + return this; + + } + + identity() { + + return this.set( 0, 0, 0, 1 ); + + } + + invert() { + + // quaternion is assumed to have unit length + + return this.conjugate(); + + } + + conjugate() { + + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); + + return this; + + } + + dot( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + + } + + lengthSq() { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + + } + + length() { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + + } + + normalize() { + + let l = this.length(); + + if ( l === 0 ) { + + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + + } else { + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + + } + + this._onChangeCallback(); + + return this; + + } + + multiply( q ) { + + return this.multiplyQuaternions( this, q ); + + } + + premultiply( q ) { + + return this.multiplyQuaternions( q, this ); + + } + + multiplyQuaternions( a, b ) { + + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + 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(); + + return this; + + } + + slerp( qb, t ) { + + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); + + const x = this._x, y = this._y, z = this._z, w = this._w; + + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + + if ( cosHalfTheta < 0 ) { + + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; + + cosHalfTheta = - cosHalfTheta; + + } else { + + this.copy( qb ); + + } + + if ( cosHalfTheta >= 1.0 ) { + + this._w = w; + this._x = x; + this._y = y; + this._z = z; + + return this; + + } + + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); + + return this; + + } + + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const 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 ); + + this._onChangeCallback(); + + return this; + + } + + slerpQuaternions( qa, qb, t ) { + + return this.copy( qa ).slerp( qb, t ); + + } + + random() { + + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. + + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); + + const u2 = 2 * Math.PI * Math.random(); + + const u3 = 2 * Math.PI * Math.random(); + + return this.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), + ); + + } + + equals( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + + } + + fromArray( array, offset = 0 ) { + + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); + + return this; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + +} + +class Vector3 { + + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; + + } + + set( x, y, z ) { + + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + + this.x = x; + this.y = y; + this.z = z; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + + return this; + + } + + multiplyVectors( a, b ) { + + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + + return this; + + } + + applyEuler( euler ) { + + return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) ); + + } + + applyAxisAngle( axis, angle ) { + + return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y, z = this.z; + const 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; + + } + + applyNormalMatrix( m ) { + + return this.applyMatrix3( m ).normalize(); + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + 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; + + return this; + + } + + applyQuaternion( q ) { + + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vector + + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; + + // 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; + + return this; + + } + + project( camera ) { + + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + + } + + unproject( camera ) { + + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + + } + + transformDirection( m ) { + + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + 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; + + return this.normalize(); + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + + return this; + + } + + max( 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 ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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 ) ); + + return this; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z; + + } + + // TODO lengthSquared? + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + + return this; + + } + + cross( v ) { + + return this.crossVectors( this, v ); + + } + + crossVectors( a, b ) { + + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + + } + + projectOnVector( v ) { + + const denominator = v.lengthSq(); + + if ( denominator === 0 ) return this.set( 0, 0, 0 ); + + const scalar = v.dot( this ) / denominator; + + return this.copy( v ).multiplyScalar( scalar ); + + } + + projectOnPlane( planeNormal ) { + + _vector$c.copy( this ).projectOnVector( planeNormal ); + + return this.sub( _vector$c ); + + } + + reflect( normal ) { + + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length + + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + + } + + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, - 1, 1 ) ); + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + + return dx * dx + dy * dy + dz * dz; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + + } + + setFromSpherical( s ) { + + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + + } + + setFromSphericalCoords( radius, phi, theta ) { + + const sinPhiRadius = Math.sin( phi ) * radius; + + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); + + return this; + + } + + setFromCylindrical( c ) { + + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + + } + + setFromCylindricalCoords( radius, theta, y ) { + + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); + + return this; + + } + + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + + return this; + + } + + setFromMatrixScale( m ) { + + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); + + this.x = sx; + this.y = sy; + this.z = sz; + + return this; + + } + + setFromMatrixColumn( m, index ) { + + return this.fromArray( m.elements, index * 4 ); + + } + + setFromMatrix3Column( m, index ) { + + return this.fromArray( m.elements, index * 3 ); + + } + + setFromEuler( e ) { + + this.x = e._x; + this.y = e._y; + this.z = e._z; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; + + } + + randomDirection() { + + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); + + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + + } + +} + +const _vector$c = /*@__PURE__*/ new Vector3(); +const _quaternion$4 = /*@__PURE__*/ new Quaternion(); + +class Box3 { + + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + + this.isBox3 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromArray( array ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const x = array[ i ]; + const y = array[ i + 1 ]; + const z = array[ i + 2 ]; + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromBufferAttribute( attribute ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = attribute.count; i < l; i ++ ) { + + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + setFromObject( object, precise = false ) { + + this.makeEmpty(); + + return this.expandByObject( object, precise ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ) || ( this.max.z < this.min.z ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + expandByObject( object, precise = false ) { + + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms + + object.updateWorldMatrix( false, false ); + + const geometry = object.geometry; + + if ( geometry !== undefined ) { + + if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) { + + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { + + _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); + + } + + } else { + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + _box$3.copy( geometry.boundingBox ); + _box$3.applyMatrix4( object.matrixWorld ); + + this.union( _box$3 ); + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } + + return this; + + } + + containsPoint( point ) { + + return 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 ? false : true; + + } + + containsBox( box ) { + + return 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; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.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 ) + ); + + } + + intersectsBox( box ) { + + // using 6 splitting planes to rule out intersections. + return 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 ? false : true; + + } + + intersectsSphere( sphere ) { + + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); + + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + intersectsPlane( plane ) { + + // 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. + + let min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + + } else { + + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + + } + + if ( plane.normal.y > 0 ) { + + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + + } else { + + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + + } + + if ( plane.normal.z > 0 ) { + + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + + } else { + + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); + + } + + intersectsTriangle( triangle ) { + + if ( this.isEmpty() ) { + + return false; + + } + + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); + + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$7.subVectors( triangle.b, _center ); + _v2$4.subVectors( triangle.c, _center ); + + // compute edge vectors for triangle + _f0.subVectors( _v1$7, _v0$2 ); + _f1.subVectors( _v2$4, _v1$7 ); + _f2.subVectors( _v0$2, _v2$4 ); + + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + + return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ); + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max ); + + return clampedPoint.sub( point ).length(); + + } + + getBoundingSphere( target ) { + + this.getCenter( target.center ); + + target.radius = this.getSize( _vector$b ).length() * 0.5; + + return target; + + } + + intersect( box ) { + + 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(); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + applyMatrix4( matrix ) { + + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; + + // 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 + + this.setFromPoints( _points ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + +} + +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; + +const _vector$b = /*@__PURE__*/ new Vector3(); + +const _box$3 = /*@__PURE__*/ new Box3(); + +// triangle centered vertices + +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$7 = /*@__PURE__*/ new Vector3(); +const _v2$4 = /*@__PURE__*/ new Vector3(); + +// triangle edge vectors + +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); + +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); + +function satForAxes( axes, v0, v1, v2, extents ) { + + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; + + } + + } + + return true; + +} + +const _box$2 = /*@__PURE__*/ new Box3(); +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); + +class Sphere { + + constructor( center = new Vector3(), radius = - 1 ) { + + this.center = center; + this.radius = radius; + + } + + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; + + } + + setFromPoints( points, optionalCenter ) { + + const center = this.center; + + if ( optionalCenter !== undefined ) { + + center.copy( optionalCenter ); + + } else { + + _box$2.setFromPoints( points ).getCenter( center ); + + } + + let maxRadiusSq = 0; + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + + } + + this.radius = Math.sqrt( maxRadiusSq ); + + return this; + + } + + copy( sphere ) { + + this.center.copy( sphere.center ); + this.radius = sphere.radius; + + return this; + + } + + isEmpty() { + + return ( this.radius < 0 ); + + } + + makeEmpty() { + + this.center.set( 0, 0, 0 ); + this.radius = - 1; + + return this; + + } + + containsPoint( point ) { + + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + + } + + distanceToPoint( point ) { + + return ( point.distanceTo( this.center ) - this.radius ); + + } + + intersectsSphere( sphere ) { + + const radiusSum = this.radius + sphere.radius; + + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + + } + + intersectsBox( box ) { + + return box.intersectsSphere( this ); + + } + + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + + } + + clampPoint( point, target ) { + + const deltaLengthSq = this.center.distanceToSquared( point ); + + target.copy( point ); + + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); + + } + + return target; + + } + + getBoundingBox( target ) { + + if ( this.isEmpty() ) { + + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; + + } + + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); + + return target; + + } + + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + + return this; + + } + + translate( offset ) { + + this.center.add( offset ); + + return this; + + } + + expandByPoint( point ) { + + if ( this.isEmpty() ) { + + this.center.copy( point ); + + this.radius = 0; + + return this; + + } + + _v1$6.subVectors( point, this.center ); + + const lengthSq = _v1$6.lengthSq(); + + if ( lengthSq > ( this.radius * this.radius ) ) { + + // calculate the minimal sphere + + const length = Math.sqrt( lengthSq ); + + const delta = ( length - this.radius ) * 0.5; + + this.center.addScaledVector( _v1$6, delta / length ); + + this.radius += delta; + + } + + return this; + + } + + union( sphere ) { + + if ( sphere.isEmpty() ) { + + return this; + + } + + if ( this.isEmpty() ) { + + this.copy( sphere ); + + return this; + + } + + if ( this.center.equals( sphere.center ) === true ) { + + this.radius = Math.max( this.radius, sphere.radius ); + + } else { + + _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius ); + + this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) ); + + this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) ); + + } + + return this; + + } + + equals( sphere ) { + + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$a = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); + +const _edge1 = /*@__PURE__*/ new Vector3(); +const _edge2 = /*@__PURE__*/ new Vector3(); +const _normal$1 = /*@__PURE__*/ new Vector3(); + +class Ray { + + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + + this.origin = origin; + this.direction = direction; + + } + + set( origin, direction ) { + + this.origin.copy( origin ); + this.direction.copy( direction ); + + return this; + + } + + copy( ray ) { + + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); + + return this; + + } + + at( t, target ) { + + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + + } + + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); + + return this; + + } + + recast( t ) { + + this.origin.copy( this.at( t, _vector$a ) ); + + return this; + + } + + closestPointToPoint( point, target ) { + + target.subVectors( point, this.origin ); + + const directionDistance = target.dot( this.direction ); + + if ( directionDistance < 0 ) { + + return target.copy( this.origin ); + + } + + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + } + + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); + + } + + distanceSqToPoint( point ) { + + const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction ); + + // point behind the ray + + if ( directionDistance < 0 ) { + + return this.origin.distanceToSquared( point ); + + } + + _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + return _vector$a.distanceToSquared( point ); + + } + + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + + // from https://github.com/pmjoniak/GeometricTools/blob/master/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 + + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); + + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; + + if ( det > 0 ) { + + // The ray and segment are not parallel. + + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { + + if ( s1 >= - extDet ) { + + if ( s1 <= extDet ) { + + // region 0 + // Minimum at interior points of ray and segment. + + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + + } else { + + // region 1 + + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + if ( s1 <= - extDet ) { + + // 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 ) { + + // region 3 + + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; + + } else { + + // region 2 + + 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 { + + // Ray and segment are parallel. + + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + if ( optionalPointOnRay ) { + + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + + } + + if ( optionalPointOnSegment ) { + + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + + } + + return sqrDist; + + } + + intersectSphere( sphere, target ) { + + _vector$a.subVectors( sphere.center, this.origin ); + const tca = _vector$a.dot( this.direction ); + const d2 = _vector$a.dot( _vector$a ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + const thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + const 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; + + // 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, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); + + } + + intersectsSphere( sphere ) { + + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + distanceToPlane( plane ) { + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { + + return 0; + + } + + // Null is preferable to undefined since undefined means.... it is undefined + + return null; + + } + + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + + // Return if the ray never intersects the plane + + return t >= 0 ? t : null; + + } + + intersectPlane( plane, target ) { + + const t = this.distanceToPlane( plane ); + + if ( t === null ) { + + return null; + + } + + return this.at( t, target ); + + } + + intersectsPlane( plane ) { + + // check if the ray lies on the plane first + + const distToPoint = plane.distanceToPoint( this.origin ); + + if ( distToPoint === 0 ) { + + return true; + + } + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator * distToPoint < 0 ) { + + return true; + + } + + // ray origin is behind the plane (and is pointing behind it) + + return false; + + } + + intersectBox( box, target ) { + + let tmin, tmax, tymin, tymax, tzmin, tzmax; + + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; + + const origin = this.origin; + + if ( invdirx >= 0 ) { + + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; + + } else { + + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + + } + + if ( invdiry >= 0 ) { + + 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; + + } + + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + + if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin; + + if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; + + } else { + + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + + } + + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + + //return point closest to the ray (positive side) + + if ( tmax < 0 ) return null; + + return this.at( tmin >= 0 ? tmin : tmax, target ); + + } + + intersectsBox( box ) { + + return this.intersectBox( box, _vector$a ) !== null; + + } + + intersectTriangle( a, b, c, backfaceCulling, target ) { + + // Compute the offset origin, edges, and normal. + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.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) + let DdN = this.direction.dot( _normal$1 ); + let sign; + + if ( DdN > 0 ) { + + if ( backfaceCulling ) return null; + sign = 1; + + } else if ( DdN < 0 ) { + + sign = - 1; + DdN = - DdN; + + } else { + + return null; + + } + + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { + + return null; + + } + + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { + + return null; + + } + + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { + + return null; + + } + + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); + + // t < 0, no intersection + if ( QdN < 0 ) { + + return null; + + } + + // Ray intersects triangle. + return this.at( QdN / DdN, target ); + + } + + applyMatrix4( matrix4 ) { + + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); + + return this; + + } + + equals( ray ) { + + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class Matrix4 { + + constructor() { + + Matrix4.prototype.isMatrix4 = true; + + this.elements = [ + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + const 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; + + return this; + + } + + identity() { + + this.set( + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + clone() { + + return new Matrix4().fromArray( this.elements ); + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + + return this; + + } + + copyPosition( m ) { + + const te = this.elements, me = m.elements; + + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; + + return this; + + } + + setFromMatrix3( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); + + return this; + + } + + makeBasis( xAxis, yAxis, zAxis ) { + + 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; + + } + + extractRotation( m ) { + + // this method does not support reflection matrices + + const te = this.elements; + const me = m.elements; + + const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length(); + + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; + + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; + + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; + + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromEuler( euler ) { + + const te = this.elements; + + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); + + if ( euler.order === 'XYZ' ) { + + const ae = a * e, af = a * f, be = b * e, bf = b * f; + + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; + + 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; + + } else if ( euler.order === 'YXZ' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZXY' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZYX' ) { + + const 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; + + 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; + + } else if ( euler.order === 'YZX' ) { + + const 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' ) { + + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; + + 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; + + } + + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; + + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromQuaternion( q ) { + + return this.compose( _zero, q, _one ); + + } + + lookAt( eye, target, up ) { + + const te = this.elements; + + _z.subVectors( eye, target ); + + if ( _z.lengthSq() === 0 ) { + + // eye and target are in the same position + + _z.z = 1; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + if ( _x.lengthSq() === 0 ) { + + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { + + _z.x += 0.0001; + + } else { + + _z.z += 0.0001; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + } + + _x.normalize(); + _y.crossVectors( _z, _x ); + + 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; + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const 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; + + 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; + + } + + multiplyScalar( s ) { + + const 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; + + } + + determinant() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + + 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 + ) + + ); + + } + + transpose() { + + const te = this.elements; + let 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; + + 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; + + } + + setPosition( x, y, z ) { + + const te = this.elements; + + if ( x.isVector3 ) { + + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; + + } else { + + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; + + } + + return this; + + } + + invert() { + + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 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; + + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + 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; + + 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; + + 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; + + return this; + + } + + scale( v ) { + + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + + 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; + + return this; + + } + + getMaxScaleOnAxis() { + + const te = this.elements; + + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + + } + + makeTranslation( x, y, z ) { + + this.set( + + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationX( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationY( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationZ( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationAxis( axis, angle ) { + + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + + this.set( + + 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 + + ); + + return this; + + } + + makeScale( x, y, z ) { + + this.set( + + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeShear( xy, xz, yx, yz, zx, zy ) { + + this.set( + + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + compose( position, quaternion, scale ) { + + const te = this.elements; + + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + + const sx = scale.x, sy = scale.y, sz = scale.z; + + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; + + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; + + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; + + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; + + return this; + + } + + decompose( position, quaternion, scale ) { + + const te = this.elements; + + let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; + + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; + + // scale the rotation part + _m1$2.copy( this ); + + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; + + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; + + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; + + quaternion.setFromRotationMatrix( _m1$2 ); + + scale.x = sx; + scale.y = sy; + scale.z = sz; + + return this; + + } + + makePerspective( left, right, top, bottom, near, far ) { + + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); + + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + const c = - ( far + near ) / ( far - near ); + const 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; + + return this; + + } + + makeOrthographic( left, right, top, bottom, near, far ) { + + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); + + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; + const 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; + + return this; + + } + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 16; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 16; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + 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 ]; + + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; + + return array; + + } + +} + +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); + +const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _quaternion$3 = /*@__PURE__*/ new Quaternion(); + +class Euler { + + constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) { + + this.isEuler = true; + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get order() { + + return this._order; + + } + + set order( value ) { + + this._order = value; + this._onChangeCallback(); + + } + + set( x, y, z, order = this._order ) { + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._order ); + + } + + copy( euler ) { + + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m, order = this._order, update = true ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + switch ( order ) { + + case 'XYZ': + + this._y = Math.asin( clamp( m13, - 1, 1 ) ); + + if ( Math.abs( m13 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); + + } else { + + this._x = Math.atan2( m32, m22 ); + this._z = 0; + + } + + break; + + case 'YXZ': + + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + + if ( Math.abs( m23 ) < 0.9999999 ) { + + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); + + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; + + } + + break; + + case 'ZXY': + + this._x = Math.asin( clamp( m32, - 1, 1 ) ); + + if ( Math.abs( m32 ) < 0.9999999 ) { + + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); + + } else { + + this._y = 0; + this._z = Math.atan2( m21, m11 ); + + } + + break; + + case 'ZYX': + + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + + if ( Math.abs( m31 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); + + } else { + + this._x = 0; + this._z = Math.atan2( - m12, m22 ); + + } + + break; + + case 'YZX': + + this._z = Math.asin( clamp( m21, - 1, 1 ) ); + + if ( Math.abs( m21 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); + + } else { + + this._x = 0; + this._y = Math.atan2( m13, m33 ); + + } + + break; + + case 'XZY': + + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + + if ( Math.abs( m12 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); + + } else { + + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + break; + + default: + + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + + } + + this._order = order; + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + setFromQuaternion( q, order, update ) { + + _matrix$1.makeRotationFromQuaternion( q ); + + return this.setFromRotationMatrix( _matrix$1, order, update ); + + } + + setFromVector3( v, order = this._order ) { + + return this.set( v.x, v.y, v.z, order ); + + } + + reorder( newOrder ) { + + // WARNING: this discards revolution information -bhouston + + _quaternion$3.setFromEuler( this ); + + return this.setFromQuaternion( _quaternion$3, newOrder ); + + } + + equals( euler ) { + + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + + } + + fromArray( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; + + return array; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + +} + +Euler.DEFAULT_ORDER = 'XYZ'; + +class Layers { + + constructor() { + + this.mask = 1 | 0; + + } + + set( channel ) { + + this.mask = ( 1 << channel | 0 ) >>> 0; + + } + + enable( channel ) { + + this.mask |= 1 << channel | 0; + + } + + enableAll() { + + this.mask = 0xffffffff | 0; + + } + + toggle( channel ) { + + this.mask ^= 1 << channel | 0; + + } + + disable( channel ) { + + this.mask &= ~ ( 1 << channel | 0 ); + + } + + disableAll() { + + this.mask = 0; + + } + + test( layers ) { + + return ( this.mask & layers.mask ) !== 0; + + } + + isEnabled( channel ) { + + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; + + } + +} + +let _object3DId = 0; + +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); + +const _position$3 = /*@__PURE__*/ new Vector3(); +const _scale$2 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); + +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); + +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; + +class Object3D extends EventDispatcher { + + constructor() { + + super(); + + this.isObject3D = true; + + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Object3D'; + + this.parent = null; + this.children = []; + + this.up = Object3D.DEFAULT_UP.clone(); + + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); + + function onRotationChange() { + + quaternion.setFromEuler( rotation, false ); + + } + + function onQuaternionChange() { + + rotation.setFromQuaternion( quaternion, undefined, false ); + + } + + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); + + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); + + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer + + this.layers = new Layers(); + this.visible = true; + + this.castShadow = false; + this.receiveShadow = false; + + this.frustumCulled = true; + this.renderOrder = 0; + + this.animations = []; + + this.userData = {}; + + } + + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + applyMatrix4( matrix ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + this.matrix.premultiply( matrix ); + + this.matrix.decompose( this.position, this.quaternion, this.scale ); + + } + + applyQuaternion( q ) { + + this.quaternion.premultiply( q ); + + return this; + + } + + setRotationFromAxisAngle( axis, angle ) { + + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); + + } + + setRotationFromEuler( euler ) { + + this.quaternion.setFromEuler( euler, true ); + + } + + setRotationFromMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + this.quaternion.setFromRotationMatrix( m ); + + } + + setRotationFromQuaternion( q ) { + + // assumes q is normalized + + this.quaternion.copy( q ); + + } + + rotateOnAxis( axis, angle ) { + + // rotate object on axis in object space + // axis is assumed to be normalized + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.multiply( _q1 ); + + return this; + + } + + rotateOnWorldAxis( axis, angle ) { + + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.premultiply( _q1 ); + + return this; + + } + + rotateX( angle ) { + + return this.rotateOnAxis( _xAxis, angle ); + + } + + rotateY( angle ) { + + return this.rotateOnAxis( _yAxis, angle ); + + } + + rotateZ( angle ) { + + return this.rotateOnAxis( _zAxis, angle ); + + } + + translateOnAxis( axis, distance ) { + + // translate object by distance along axis in object space + // axis is assumed to be normalized + + _v1$4.copy( axis ).applyQuaternion( this.quaternion ); + + this.position.add( _v1$4.multiplyScalar( distance ) ); + + return this; + + } + + translateX( distance ) { + + return this.translateOnAxis( _xAxis, distance ); + + } + + translateY( distance ) { + + return this.translateOnAxis( _yAxis, distance ); + + } + + translateZ( distance ) { + + return this.translateOnAxis( _zAxis, distance ); + + } + + localToWorld( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( this.matrixWorld ); + + } + + worldToLocal( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + + } + + lookAt( x, y, z ) { + + // This method does not support objects having non-uniformly-scaled parent(s) + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + const parent = this.parent; + + this.updateWorldMatrix( true, false ); + + _position$3.setFromMatrixPosition( this.matrixWorld ); + + if ( this.isCamera || this.isLight ) { + + _m1$1.lookAt( _position$3, _target, this.up ); + + } else { + + _m1$1.lookAt( _target, _position$3, this.up ); + + } + + this.quaternion.setFromRotationMatrix( _m1$1 ); + + if ( parent ) { + + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); + + } + + } + + add( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + } + + if ( object === this ) { + + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; + + } + + if ( object && object.isObject3D ) { + + if ( object.parent !== null ) { + + object.parent.remove( object ); + + } + + object.parent = this; + this.children.push( object ); + + object.dispatchEvent( _addedEvent ); + + } else { + + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + + } + + return this; + + } + + remove( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.remove( arguments[ i ] ); + + } + + return this; + + } + + const index = this.children.indexOf( object ); + + if ( index !== - 1 ) { + + object.parent = null; + this.children.splice( index, 1 ); + + object.dispatchEvent( _removedEvent ); + + } + + return this; + + } + + removeFromParent() { + + const parent = this.parent; + + if ( parent !== null ) { + + parent.remove( this ); + + } + + return this; + + } + + clear() { + + for ( let i = 0; i < this.children.length; i ++ ) { + + const object = this.children[ i ]; + + object.parent = null; + + object.dispatchEvent( _removedEvent ); + + } + + this.children.length = 0; + + return this; + + + } + + attach( object ) { + + // adds object as a child of this, while maintaining the object's world transform + + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + + this.updateWorldMatrix( true, false ); + + _m1$1.copy( this.matrixWorld ).invert(); + + if ( object.parent !== null ) { + + object.parent.updateWorldMatrix( true, false ); + + _m1$1.multiply( object.parent.matrixWorld ); + + } + + object.applyMatrix4( _m1$1 ); + + this.add( object ); + + object.updateWorldMatrix( false, true ); + + return this; + + } + + getObjectById( id ) { + + return this.getObjectByProperty( 'id', id ); + + } + + getObjectByName( name ) { + + return this.getObjectByProperty( 'name', name ); + + } + + getObjectByProperty( name, value ) { + + if ( this[ name ] === value ) return this; + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); + + if ( object !== undefined ) { + + return object; + + } + + } + + return undefined; + + } + + getObjectsByProperty( name, value ) { + + let result = []; + + if ( this[ name ] === value ) result.push( this ); + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const childResult = this.children[ i ].getObjectsByProperty( name, value ); + + if ( childResult.length > 0 ) { + + result = result.concat( childResult ); + + } + + } + + return result; + + } + + getWorldPosition( target ) { + + this.updateWorldMatrix( true, false ); + + return target.setFromMatrixPosition( this.matrixWorld ); + + } + + getWorldQuaternion( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, target, _scale$2 ); + + return target; + + } + + getWorldScale( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, _quaternion$2, target ); + + return target; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + + } + + raycast( /* raycaster, intersects */ ) {} + + traverse( callback ) { + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverse( callback ); + + } + + } + + traverseVisible( callback ) { + + if ( this.visible === false ) return; + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverseVisible( callback ); + + } + + } + + traverseAncestors( callback ) { + + const parent = this.parent; + + if ( parent !== null ) { + + callback( parent ); + + parent.traverseAncestors( callback ); + + } + + } + + updateMatrix() { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + this.matrixWorldNeedsUpdate = true; + + } + + updateMatrixWorld( force ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // update children + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } + + } + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + const parent = this.parent; + + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { + + parent.updateWorldMatrix( true, false ); + + } + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + // update children + + if ( updateChildren === true ) { + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true ) { + + child.updateWorldMatrix( false, true ); + + } + + } + + } + + } + + toJSON( meta ) { + + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + const output = {}; + + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { + + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; + + } + + // standard Object3D serialization + + const object = {}; + + object.uuid = this.uuid; + object.type = this.type; + + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData; + + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + + // object specific properties + + if ( this.isInstancedMesh ) { + + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); + + } + + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); + + } + + return element.uuid; + + } + + if ( this.isScene ) { + + if ( this.background ) { + + if ( this.background.isColor ) { + + object.background = this.background.toJSON(); + + } else if ( this.background.isTexture ) { + + object.background = this.background.toJSON( meta ).uuid; + + } + + } + + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { + + object.environment = this.environment.toJSON( meta ).uuid; + + } + + } else if ( this.isMesh || this.isLine || this.isPoints ) { + + object.geometry = serialize( meta.geometries, this.geometry ); + + const parameters = this.geometry.parameters; + + if ( parameters !== undefined && parameters.shapes !== undefined ) { + + const shapes = parameters.shapes; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + serialize( meta.shapes, shape ); + + } + + } else { + + serialize( meta.shapes, shapes ); + + } + + } + + } + + if ( this.isSkinnedMesh ) { + + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + + if ( this.skeleton !== undefined ) { + + serialize( meta.skeletons, this.skeleton ); + + object.skeleton = this.skeleton.uuid; + + } + + } + + if ( this.material !== undefined ) { + + if ( Array.isArray( this.material ) ) { + + const uuids = []; + + for ( let i = 0, l = this.material.length; i < l; i ++ ) { + + uuids.push( serialize( meta.materials, this.material[ i ] ) ); + + } + + object.material = uuids; + + } else { + + object.material = serialize( meta.materials, this.material ); + + } + + } + + // + + if ( this.children.length > 0 ) { + + object.children = []; + + for ( let i = 0; i < this.children.length; i ++ ) { + + object.children.push( this.children[ i ].toJSON( meta ).object ); + + } + + } + + // + + if ( this.animations.length > 0 ) { + + object.animations = []; + + for ( let i = 0; i < this.animations.length; i ++ ) { + + const animation = this.animations[ i ]; + + object.animations.push( serialize( meta.animations, animation ) ); + + } + + } + + if ( isRootObject ) { + + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); + + 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; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; + + } + + output.object = object; + + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { + + const values = []; + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + } + + clone( recursive ) { + + return new this.constructor().copy( this, recursive ); + + } + + copy( source, recursive = true ) { + + this.name = source.name; + + this.up.copy( source.up ); + + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); + + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + + this.layers.mask = source.layers.mask; + this.visible = source.visible; + + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { + + for ( let i = 0; i < source.children.length; i ++ ) { + + const child = source.children[ i ]; + this.add( child.clone() ); + + } + + } + + return this; + + } + +} + +Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); +const _v3$1 = /*@__PURE__*/ new Vector3(); + +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); + +class Triangle { + + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + + this.a = a; + this.b = b; + this.c = c; + + } + + static getNormal( a, b, c, target ) { + + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); + + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { + + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + + } + + return target.set( 0, 0, 0 ); + + } + + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { + + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$2.subVectors( point, a ); + + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$3 ); + const dot02 = _v0$1.dot( _v2$2 ); + const dot11 = _v1$3.dot( _v1$3 ); + const dot12 = _v1$3.dot( _v2$2 ); + + const denom = ( dot00 * dot11 - dot01 * dot01 ); + + // 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 target.set( - 2, - 1, - 1 ); + + } + + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); + + } + + static containsPoint( point, a, b, c ) { + + this.getBarycoord( point, a, b, c, _v3$1 ); + + return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + + } + + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { + + this.getBarycoord( point, p1, p2, p3, _v3$1 ); + + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3$1.x ); + target.addScaledVector( uv2, _v3$1.y ); + target.addScaledVector( uv3, _v3$1.z ); + + return target; + + } + + static isFrontFacing( a, b, c, direction ) { + + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); + + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); + + return this; + + } + + setFromPointsAndIndices( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; + + } + + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { + + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( triangle ) { + + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; + + } + + getArea() { + + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); + + return _v0$1.cross( _v1$3 ).length() * 0.5; + + } + + getMidpoint( target ) { + + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + + } + + getNormal( target ) { + + return Triangle.getNormal( this.a, this.b, this.c, target ); + + } + + getPlane( target ) { + + return target.setFromCoplanarPoints( this.a, this.b, this.c ); + + } + + getBarycoord( point, target ) { + + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + + } + + getUV( point, uv1, uv2, uv3, target ) { + + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + + } + + containsPoint( point ) { + + return Triangle.containsPoint( point, this.a, this.b, this.c ); + + } + + isFrontFacing( direction ) { + + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + + } + + intersectsBox( box ) { + + return box.intersectsTriangle( this ); + + } + + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; + + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. + + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { + + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); + + } + + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { + + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } + + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); + + } + + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { + + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } + + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); + + } + + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + + } + + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; + + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + + } + + equals( triangle ) { + + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + + } + +} + +let materialId = 0; + +class Material extends EventDispatcher { + + constructor() { + + super(); + + this.isMaterial = true; + + Object.defineProperty( this, 'id', { value: materialId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Material'; + + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + + 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; + + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + + this.shadowSide = null; + + this.colorWrite = true; + + this.precision = null; // override the renderer's default precision for this material + + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + + this.dithering = false; + + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + + this.visible = true; + + this.toneMapped = true; + + this.userData = {}; + + this.version = 0; + + this._alphaTest = 0; + + } + + get alphaTest() { + + return this._alphaTest; + + } + + set alphaTest( value ) { + + if ( this._alphaTest > 0 !== value > 0 ) { + + this.version ++; + + } + + this._alphaTest = value; + + } + + onBuild( /* shaderobject, renderer */ ) {} + + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} + + onBeforeCompile( /* shaderobject, renderer */ ) {} + + customProgramCacheKey() { + + return this.onBeforeCompile.toString(); + + } + + setValues( values ) { + + if ( values === undefined ) return; + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); + continue; + + } + + if ( currentValue && currentValue.isColor ) { + + currentValue.set( newValue ); + + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( isRootObject ) { + + meta = { + textures: {}, + images: {} + }; + + } + + const data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; + + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; + + if ( this.name !== '' ) data.name = this.name; + + 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.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + + } + + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.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; + data.lightMapIntensity = this.lightMapIntensity; + + } + + if ( this.aoMap && this.aoMap.isTexture ) { + + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; + + } + + if ( this.bumpMap && this.bumpMap.isTexture ) { + + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; + + } + + if ( this.normalMap && this.normalMap.isTexture ) { + + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + + } + + if ( this.displacementMap && this.displacementMap.isTexture ) { + + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + + } + + 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 && 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.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; + + if ( this.envMap && this.envMap.isTexture ) { + + data.envMap = this.envMap.toJSON( meta ).uuid; + + if ( this.combine !== undefined ) data.combine = this.combine; + + } + + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; + + if ( this.gradientMap && this.gradientMap.isTexture ) { + + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + + } + + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); + + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; + + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; + + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; + + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; + + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; + + if ( this.dithering === true ) data.dithering = true; + + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + + if ( this.flatShading === true ) data.flatShading = this.flatShading; + + if ( this.visible === false ) data.visible = false; + + if ( this.toneMapped === false ) data.toneMapped = false; + + if ( this.fog === false ) data.fog = false; + + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + // TODO: Copied from Object3D.toJSON + + function extractFromCache( cache ) { + + const values = []; + + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + if ( isRootObject ) { + + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + + if ( srcPlanes !== null ) { + + const n = srcPlanes.length; + dstPlanes = new Array( n ); + + for ( let i = 0; i !== n; ++ i ) { + + dstPlanes[ i ] = srcPlanes[ i ].clone(); + + } + + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + 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'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _vector$9 = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector2(); + +class BufferAttribute { + + constructor( array, itemSize, normalized = false ) { + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + + } + + this.isBufferAttribute = true; + + this.name = ''; + + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.itemSize; + index2 *= attribute.itemSize; + + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + copyArray( array ) { + + this.array.set( array ); + + return this; + + } + + applyMatrix3( m ) { + + if ( this.itemSize === 2 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector2$1.fromBufferAttribute( this, i ); + _vector2$1.applyMatrix3( m ); + + this.setXY( i, _vector2$1.x, _vector2$1.y ); + + } + + } else if ( this.itemSize === 3 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + _vector$9.applyMatrix3( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + } + + return this; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyMatrix4( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.transformDirection( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + set( value, offset = 0 ) { + + // Matching BufferAttribute constructor, do not normalize the array. + this.array.set( value, offset ); + + return this; + + } + + getX( index ) { + + let x = this.array[ index * this.itemSize ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = x; + + return this; + + } + + getY( index ) { + + let y = this.array[ index * this.itemSize + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = y; + + return this; + + } + + getZ( index ) { + + let z = this.array[ index * this.itemSize + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = z; + + return this; + + } + + getW( index ) { + + let w = this.array[ index * this.itemSize + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = w; + + return this; + + } + + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; + + return this; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + clone() { + + return new this.constructor( this.array, this.itemSize ).copy( this ); + + } + + toJSON() { + + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from( this.array ), + normalized: this.normalized + }; + + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; + + return data; + + } + + // @deprecated + + copyColorsArray() { + + console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' ); + + } + + copyVector2sArray() { + + console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' ); + + } + + copyVector3sArray() { + + console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' ); + + } + + copyVector4sArray() { + + console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' ); + + } + +} + +// + +class Int8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int8Array( array ), itemSize, normalized ); + + } + +} + +class Uint8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8Array( array ), itemSize, normalized ); + + } + +} + +class Uint8ClampedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8ClampedArray( array ), itemSize, normalized ); + + } + +} + +class Int16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int16Array( array ), itemSize, normalized ); + + } + +} + +class Uint16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + } + +} + +class Int32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int32Array( array ), itemSize, normalized ); + + } + +} + +class Uint32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint32Array( array ), itemSize, normalized ); + + } + +} + +class Float16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + this.isFloat16BufferAttribute = true; + + } + +} + + +class Float32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } + +} + +class Float64BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float64Array( array ), itemSize, normalized ); + + } + +} + +let _id$1 = 0; + +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box$1 = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$8 = /*@__PURE__*/ new Vector3(); + +class BufferGeometry extends EventDispatcher { + + constructor() { + + super(); + + this.isBufferGeometry = true; + + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'BufferGeometry'; + + this.index = null; + this.attributes = {}; + + this.morphAttributes = {}; + this.morphTargetsRelative = false; + + this.groups = []; + + this.boundingBox = null; + this.boundingSphere = null; + + this.drawRange = { start: 0, count: Infinity }; + + this.userData = {}; + + } + + getIndex() { + + return this.index; + + } + + setIndex( index ) { + + if ( Array.isArray( index ) ) { + + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; + + } + + return this; + + } + + getAttribute( name ) { + + return this.attributes[ name ]; + + } + + setAttribute( name, attribute ) { + + this.attributes[ name ] = attribute; + + return this; + + } + + deleteAttribute( name ) { + + delete this.attributes[ name ]; + + return this; + + } + + hasAttribute( name ) { + + return this.attributes[ name ] !== undefined; + + } + + addGroup( start, count, materialIndex = 0 ) { + + this.groups.push( { + + start: start, + count: count, + materialIndex: materialIndex + + } ); + + } + + clearGroups() { + + this.groups = []; + + } + + setDrawRange( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; + + } + + applyMatrix4( matrix ) { + + const position = this.attributes.position; + + if ( position !== undefined ) { + + position.applyMatrix4( matrix ); + + position.needsUpdate = true; + + } + + const normal = this.attributes.normal; + + if ( normal !== undefined ) { + + const normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + normal.applyNormalMatrix( normalMatrix ); + + normal.needsUpdate = true; + + } + + const tangent = this.attributes.tangent; + + if ( tangent !== undefined ) { + + tangent.transformDirection( matrix ); + + tangent.needsUpdate = true; + + } + + if ( this.boundingBox !== null ) { + + this.computeBoundingBox(); + + } + + if ( this.boundingSphere !== null ) { + + this.computeBoundingSphere(); + + } + + return this; + + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateX( angle ) { + + // rotate geometry around world x-axis + + _m1.makeRotationX( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateY( angle ) { + + // rotate geometry around world y-axis + + _m1.makeRotationY( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateZ( angle ) { + + // rotate geometry around world z-axis + + _m1.makeRotationZ( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + translate( x, y, z ) { + + // translate geometry + + _m1.makeTranslation( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + scale( x, y, z ) { + + // scale geometry + + _m1.makeScale( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + lookAt( vector ) { + + _obj.lookAt( vector ); + + _obj.updateMatrix(); + + this.applyMatrix4( _obj.matrix ); + + return this; + + } + + center() { + + this.computeBoundingBox(); + + this.boundingBox.getCenter( _offset ).negate(); + + this.translate( _offset.x, _offset.y, _offset.z ); + + return this; + + } + + setFromPoints( points ) { + + const position = []; + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + const point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } + + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + return this; + + } + + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingBox.set( + new Vector3( - Infinity, - Infinity, - Infinity ), + new Vector3( + Infinity, + Infinity, + Infinity ) + ); + + return; + + } + + if ( position !== undefined ) { + + this.boundingBox.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _box$1.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( this.boundingBox.min, _box$1.min ); + this.boundingBox.expandByPoint( _vector$8 ); + + _vector$8.addVectors( this.boundingBox.max, _box$1.max ); + this.boundingBox.expandByPoint( _vector$8 ); + + } else { + + this.boundingBox.expandByPoint( _box$1.min ); + this.boundingBox.expandByPoint( _box$1.max ); + + } + + } + + } + + } else { + + this.boundingBox.makeEmpty(); + + } + + 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 ); + + } + + } + + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingSphere.set( new Vector3(), Infinity ); + + return; + + } + + if ( position ) { + + // first, find the center of the bounding sphere + + const center = this.boundingSphere.center; + + _box$1.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( _box$1.min, _boxMorphTargets.min ); + _box$1.expandByPoint( _vector$8 ); + + _vector$8.addVectors( _box$1.max, _boxMorphTargets.max ); + _box$1.expandByPoint( _vector$8 ); + + } else { + + _box$1.expandByPoint( _boxMorphTargets.min ); + _box$1.expandByPoint( _boxMorphTargets.max ); + + } + + } + + } + + _box$1.getCenter( center ); + + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + + let maxRadiusSq = 0; + + for ( let i = 0, il = position.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( position, i ); + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + const morphTargetsRelative = this.morphTargetsRelative; + + for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + + _vector$8.fromBufferAttribute( morphAttribute, j ); + + if ( morphTargetsRelative ) { + + _offset.fromBufferAttribute( position, j ); + _vector$8.add( _offset ); + + } + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + } + + } + + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + + if ( isNaN( this.boundingSphere.radius ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + } + + computeTangents() { + + const index = this.index; + const attributes = this.attributes; + + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) + + if ( index === null || + attributes.position === undefined || + attributes.normal === undefined || + attributes.uv === undefined ) { + + console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' ); + return; + + } + + const indices = index.array; + const positions = attributes.position.array; + const normals = attributes.normal.array; + const uvs = attributes.uv.array; + + const nVertices = positions.length / 3; + + if ( this.hasAttribute( 'tangent' ) === false ) { + + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + + } + + const tangents = this.getAttribute( 'tangent' ).array; + + const tan1 = [], tan2 = []; + + for ( let i = 0; i < nVertices; i ++ ) { + + tan1[ i ] = new Vector3(); + tan2[ i ] = new Vector3(); + + } + + const vA = new Vector3(), + vB = new Vector3(), + vC = new Vector3(), + + uvA = new Vector2(), + uvB = new Vector2(), + uvC = new Vector2(), + + sdir = new Vector3(), + tdir = new Vector3(); + + function handleTriangle( a, b, c ) { + + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); + + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); + + vB.sub( vA ); + vC.sub( vA ); + + uvB.sub( uvA ); + uvC.sub( uvA ); + + const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); + + // silently ignore degenerate uv triangles having coincident or colinear vertices + + if ( ! isFinite( r ) ) return; + + sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); + tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); + + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); + + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); + + } + + let groups = this.groups; + + if ( groups.length === 0 ) { + + groups = [ { + start: 0, + count: indices.length + } ]; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleTriangle( + indices[ j + 0 ], + indices[ j + 1 ], + indices[ j + 2 ] + ); + + } + + } + + const tmp = new Vector3(), tmp2 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + + function handleVertex( v ) { + + n.fromArray( normals, v * 3 ); + n2.copy( n ); + + const t = tan1[ v ]; + + // Gram-Schmidt orthogonalize + + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + + // Calculate handedness + + tmp2.crossVectors( n2, t ); + const test = tmp2.dot( tan2[ v ] ); + const w = ( test < 0.0 ) ? - 1.0 : 1.0; + + tangents[ v * 4 ] = tmp.x; + tangents[ v * 4 + 1 ] = tmp.y; + tangents[ v * 4 + 2 ] = tmp.z; + tangents[ v * 4 + 3 ] = w; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleVertex( indices[ j + 0 ] ); + handleVertex( indices[ j + 1 ] ); + handleVertex( indices[ j + 2 ] ); + + } + + } + + } + + computeVertexNormals() { + + const index = this.index; + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute !== undefined ) { + + let normalAttribute = this.getAttribute( 'normal' ); + + if ( normalAttribute === undefined ) { + + normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 ); + this.setAttribute( 'normal', normalAttribute ); + + } else { + + // reset existing normals to zero + + for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) { + + normalAttribute.setXYZ( i, 0, 0, 0 ); + + } + + } + + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + + // indexed elements + + if ( index ) { + + for ( let i = 0, il = index.count; i < il; i += 3 ) { + + const vA = index.getX( i + 0 ); + const vB = index.getX( i + 1 ); + const vC = index.getX( i + 2 ); + + pA.fromBufferAttribute( positionAttribute, vA ); + pB.fromBufferAttribute( positionAttribute, vB ); + pC.fromBufferAttribute( positionAttribute, vC ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + nA.fromBufferAttribute( normalAttribute, vA ); + nB.fromBufferAttribute( normalAttribute, vB ); + nC.fromBufferAttribute( normalAttribute, vC ); + + nA.add( cb ); + nB.add( cb ); + nC.add( cb ); + + normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z ); + normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z ); + normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z ); + + } + + } else { + + // non-indexed elements (unconnected triangle soup) + + for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) { + + pA.fromBufferAttribute( positionAttribute, i + 0 ); + pB.fromBufferAttribute( positionAttribute, i + 1 ); + pC.fromBufferAttribute( positionAttribute, i + 2 ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z ); + + } + + } + + this.normalizeNormals(); + + normalAttribute.needsUpdate = true; + + } + + } + + // @deprecated since r144 + + merge() { + + console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' ); + return this; + + } + + normalizeNormals() { + + const normals = this.attributes.normal; + + for ( let i = 0, il = normals.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( normals, i ); + + _vector$8.normalize(); + + normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + } + + toNonIndexed() { + + function convertBufferAttribute( attribute, indices ) { + + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array2 = new array.constructor( indices.length * itemSize ); + + let index = 0, index2 = 0; + + for ( let i = 0, l = indices.length; i < l; i ++ ) { + + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } + + for ( let j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + return new BufferAttribute( array2, itemSize, normalized ); + + } + + // + + if ( this.index === null ) { + + console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' ); + return this; + + } + + const geometry2 = new BufferGeometry(); + + const indices = this.index.array; + const attributes = this.attributes; + + // attributes + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + geometry2.setAttribute( name, newAttribute ); + + } + + // morph attributes + + const morphAttributes = this.morphAttributes; + + for ( const name in morphAttributes ) { + + const morphArray = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const attribute = morphAttribute[ i ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + morphArray.push( newAttribute ); + + } + + geometry2.morphAttributes[ name ] = morphArray; + + } + + geometry2.morphTargetsRelative = this.morphTargetsRelative; + + // groups + + const groups = this.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); + + } + + return geometry2; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; + + // standard BufferGeometry serialization + + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + if ( this.parameters !== undefined ) { + + const parameters = this.parameters; + + for ( const key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + + } + + return data; + + } + + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + + data.data = { attributes: {} }; + + const index = this.index; + + if ( index !== null ) { + + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; + + } + + const attributes = this.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + + data.data.attributes[ key ] = attribute.toJSON( data.data ); + + } + + const morphAttributes = {}; + let hasMorphAttributes = false; + + for ( const key in this.morphAttributes ) { + + const attributeArray = this.morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + + array.push( attribute.toJSON( data.data ) ); + + } + + if ( array.length > 0 ) { + + morphAttributes[ key ] = array; + + hasMorphAttributes = true; + + } + + } + + if ( hasMorphAttributes ) { + + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + + } + + const groups = this.groups; + + if ( groups.length > 0 ) { + + data.data.groups = JSON.parse( JSON.stringify( groups ) ); + + } + + const boundingSphere = this.boundingSphere; + + if ( boundingSphere !== null ) { + + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + // reset + + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + + // used for storing cloned, shared data + + const data = {}; + + // name + + this.name = source.name; + + // index + + const index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone( data ) ); + + } + + // attributes + + const attributes = source.attributes; + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone( data ) ); + + } + + // morph attributes + + const morphAttributes = source.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone( data ) ); + + } + + this.morphAttributes[ name ] = array; + + } + + this.morphTargetsRelative = source.morphTargetsRelative; + + // groups + + const groups = source.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); + + } + + // bounding box + + const boundingBox = source.boundingBox; + + if ( boundingBox !== null ) { + + this.boundingBox = boundingBox.clone(); + + } + + // bounding sphere + + const boundingSphere = source.boundingSphere; + + if ( boundingSphere !== null ) { + + this.boundingSphere = boundingSphere.clone(); + + } + + // draw range + + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + + // user data + + this.userData = source.userData; + + // geometry generator parameters + + if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); +const _sphere$3 = /*@__PURE__*/ new Sphere(); + +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); + +const _tempA = /*@__PURE__*/ new Vector3(); +const _morphA = /*@__PURE__*/ new Vector3(); + +const _uvA$1 = /*@__PURE__*/ new Vector2(); +const _uvB$1 = /*@__PURE__*/ new Vector2(); +const _uvC$1 = /*@__PURE__*/ new Vector2(); + +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); + +class Mesh extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { + + super(); + + this.isMesh = true; + + this.type = 'Mesh'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.morphTargetInfluences !== undefined ) { + + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + + } + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + getVertexPosition( index, target ) { + + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + + target.fromBufferAttribute( position, index ); + + const morphInfluences = this.morphTargetInfluences; + + if ( morphPosition && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + + for ( let i = 0, il = morphPosition.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morphAttribute = morphPosition[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morphAttribute, index ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( target ), influence ); + + } + + } + + target.add( _morphA ); + + } + + if ( this.isSkinnedMesh ) { + + this.boneTransform( index, target ); + + } + + return target; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + + // + + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + + // Check boundingBox before continuing + + if ( geometry.boundingBox !== null ) { + + if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return; + + } + + let intersection; + + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } else if ( position !== undefined ) { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = j; + const b = j + 1; + const c = j + 2; + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = i; + const b = i + 1; + const c = i + 2; + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } + + } + +} + +function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { + + let intersect; + + if ( material.side === BackSide ) { + + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + + } else { + + intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point ); + + } + + if ( intersect === null ) return null; + + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + + if ( distance < raycaster.near || distance > raycaster.far ) return null; + + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; + +} + +function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) { + + object.getVertexPosition( a, _vA$1 ); + object.getVertexPosition( b, _vB$1 ); + object.getVertexPosition( c, _vC$1 ); + + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); + + if ( intersection ) { + + if ( uv ) { + + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); + + intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + if ( uv2 ) { + + _uvA$1.fromBufferAttribute( uv2, a ); + _uvB$1.fromBufferAttribute( uv2, b ); + _uvC$1.fromBufferAttribute( uv2, c ); + + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + const face = { + a: a, + b: b, + c: c, + normal: new Vector3(), + materialIndex: 0 + }; + + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); + + intersection.face = face; + + } + + return intersection; + +} + +class BoxGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + this.type = 'BoxGeometry'; + + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; + + const scope = this; + + // segments + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let numberOfVertices = 0; + let groupStart = 0; + + // 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 + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + let vertexCounter = 0; + let groupCount = 0; + + const vector = new Vector3(); + + // generate vertices, normals and uvs + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segmentHeight - heightHalf; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segmentWidth - widthHalf; + + // set values to correct vector component + + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; + + // now apply vector to vertex buffer + + vertices.push( vector.x, vector.y, vector.z ); + + // set values to correct vector component + + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; + + // now apply vector to normal buffer + + normals.push( vector.x, vector.y, vector.z ); + + // uvs + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + // counters + + vertexCounter += 1; + + } + + } + + // indices + + // 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 + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // increase counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, materialIndex ); + + // calculate new start value for groups + + groupStart += groupCount; + + // update total number of vertices + + numberOfVertices += vertexCounter; + + } + + } + + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + +} + +/** + * Uniform Utilities + */ + +function cloneUniforms( src ) { + + const dst = {}; + + for ( const u in src ) { + + dst[ u ] = {}; + + for ( const p in src[ u ] ) { + + const property = src[ u ][ p ]; + + if ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ) { + + dst[ u ][ p ] = property.clone(); + + } else if ( Array.isArray( property ) ) { + + dst[ u ][ p ] = property.slice(); + + } else { + + dst[ u ][ p ] = property; + + } + + } + + } + + return dst; + +} + +function mergeUniforms( uniforms ) { + + const merged = {}; + + for ( let u = 0; u < uniforms.length; u ++ ) { + + const tmp = cloneUniforms( uniforms[ u ] ); + + for ( const p in tmp ) { + + merged[ p ] = tmp[ p ]; + + } + + } + + return merged; + +} + +function cloneUniformsGroups( src ) { + + const dst = []; + + for ( let u = 0; u < src.length; u ++ ) { + + dst.push( src[ u ].clone() ); + + } + + return dst; + +} + +function getUnlitUniformColorSpace( renderer ) { + + if ( renderer.getRenderTarget() === null ) { + + // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398 + return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; + + } + + return LinearSRGBColorSpace; + +} + +// Legacy + +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + +class ShaderMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShaderMaterial = true; + + this.type = 'ShaderMaterial'; + + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + + this.linewidth = 1; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + 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 + + 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 + }; + + // 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; + this.uniformsNeedUpdate = false; + + this.glslVersion = null; + + if ( parameters !== undefined ) { + + this.setValues( parameters ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); + + this.defines = Object.assign( {}, source.defines ); + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + + this.extensions = Object.assign( {}, source.extensions ); + + this.glslVersion = source.glslVersion; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.glslVersion = this.glslVersion; + data.uniforms = {}; + + for ( const name in this.uniforms ) { + + const uniform = this.uniforms[ name ]; + const value = uniform.value; + + if ( value && value.isTexture ) { + + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; + + } else if ( value && value.isColor ) { + + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; + + } else if ( value && value.isVector2 ) { + + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; + + } else if ( value && value.isVector3 ) { + + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; + + } else if ( value && value.isVector4 ) { + + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; + + } else if ( value && value.isMatrix3 ) { + + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; + + } else if ( value && value.isMatrix4 ) { + + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; + + } else { + + data.uniforms[ name ] = { + value: value + }; + + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + + } + + } + + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + const extensions = {}; + + for ( const key in this.extensions ) { + + if ( this.extensions[ key ] === true ) extensions[ key ] = true; + + } + + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + + return data; + + } + +} + +class Camera extends Object3D { + + constructor() { + + super(); + + this.isCamera = true; + + this.type = 'Camera'; + + this.matrixWorldInverse = new Matrix4(); + + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); + + return this; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + super.updateWorldMatrix( updateParents, updateChildren ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class PerspectiveCamera extends Camera { + + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + this.fov = fov; + this.zoom = 1; + + this.near = near; + this.far = far; + this.focus = 10; + + this.aspect = aspect; + this.view = null; + + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + 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( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * 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 + * + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( 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( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const near = this.near; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = - 0.5 * width; + const view = this.view; + + if ( this.view !== null && this.view.enabled ) { + + const fullWidth = view.fullWidth, + fullHeight = view.fullHeight; + + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + + } + + const skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.fov = this.fov; + data.object.zoom = this.zoom; + + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + + data.object.aspect = this.aspect; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + + return data; + + } + +} + +const fov = - 90; // negative fov is not an error +const aspect = 1; + +class CubeCamera extends Object3D { + + constructor( near, far, renderTarget ) { + + super(); + + this.type = 'CubeCamera'; + + this.renderTarget = renderTarget; + + const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + cameraPX.up.set( 0, 1, 0 ); + cameraPX.lookAt( 1, 0, 0 ); + this.add( cameraPX ); + + const cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + cameraNX.up.set( 0, 1, 0 ); + cameraNX.lookAt( - 1, 0, 0 ); + this.add( cameraNX ); + + const cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + cameraPY.up.set( 0, 0, - 1 ); + cameraPY.lookAt( 0, 1, 0 ); + this.add( cameraPY ); + + const cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + cameraNY.up.set( 0, 0, 1 ); + cameraNY.lookAt( 0, - 1, 0 ); + this.add( cameraNY ); + + const cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + cameraPZ.up.set( 0, 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + this.add( cameraPZ ); + + const cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + cameraNZ.up.set( 0, 1, 0 ); + cameraNZ.lookAt( 0, 0, - 1 ); + this.add( cameraNZ ); + + } + + update( renderer, scene ) { + + if ( this.parent === null ) this.updateMatrixWorld(); + + const renderTarget = this.renderTarget; + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; + + const currentRenderTarget = renderer.getRenderTarget(); + + const currentToneMapping = renderer.toneMapping; + const currentXrEnabled = renderer.xr.enabled; + + renderer.toneMapping = NoToneMapping; + renderer.xr.enabled = false; + + const generateMipmaps = renderTarget.texture.generateMipmaps; + + renderTarget.texture.generateMipmaps = false; + + renderer.setRenderTarget( renderTarget, 0 ); + renderer.render( scene, cameraPX ); + + renderer.setRenderTarget( renderTarget, 1 ); + renderer.render( scene, cameraNX ); + + renderer.setRenderTarget( renderTarget, 2 ); + renderer.render( scene, cameraPY ); + + renderer.setRenderTarget( renderTarget, 3 ); + renderer.render( scene, cameraNY ); + + renderer.setRenderTarget( renderTarget, 4 ); + renderer.render( scene, cameraPZ ); + + renderTarget.texture.generateMipmaps = generateMipmaps; + + renderer.setRenderTarget( renderTarget, 5 ); + renderer.render( scene, cameraNZ ); + + renderer.setRenderTarget( currentRenderTarget ); + + renderer.toneMapping = currentToneMapping; + renderer.xr.enabled = currentXrEnabled; + + renderTarget.texture.needsPMREMUpdate = true; + + } + +} + +class CubeTexture extends Texture { + + constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + + super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCubeTexture = true; + + this.flipY = false; + + } + + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + + constructor( size = 1, options = {} ) { + + super( size, size, options ); + + this.isWebGLCubeRenderTarget = true; + + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. + + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). + + this.texture.isRenderTargetTexture = true; + + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + } + + fromEquirectangularTexture( renderer, texture ) { + + this.texture.type = texture.type; + this.texture.encoding = texture.encoding; + + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + + const shader = { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: /* glsl */` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + + fragmentShader: /* glsl */` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + + const geometry = new BoxGeometry( 5, 5, 5 ); + + const material = new ShaderMaterial( { + + name: 'CubemapFromEquirect', + + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + + } ); + + material.uniforms.tEquirect.value = texture; + + const mesh = new Mesh( geometry, material ); + + const currentMinFilter = texture.minFilter; + + // Avoid blurred poles + if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter; + + const camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, mesh ); + + texture.minFilter = currentMinFilter; + + mesh.geometry.dispose(); + mesh.material.dispose(); + + return this; + + } + + clear( renderer, color, depth, stencil ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + for ( let i = 0; i < 6; i ++ ) { + + renderer.setRenderTarget( this, i ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( currentRenderTarget ); + + } + +} + +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); + +class Plane { + + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + + this.isPlane = true; + + // normal is assumed to be normalized + + this.normal = normal; + this.constant = constant; + + } + + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; + + } + + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; + + return this; + + } + + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + negate() { + + this.constant *= - 1; + this.normal.negate(); + + return this; + + } + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + projectPoint( point, target ) { + + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + + } + + intersectLine( line, target ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( t < 0 || t > 1 ) { + + return null; + + } + + return target.copy( direction ).multiplyScalar( t ).add( line.start ); + + } + + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _sphere$2 = /*@__PURE__*/ new Sphere(); +const _vector$7 = /*@__PURE__*/ new Vector3(); + +class Frustum { + + constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { + + this.planes = [ p0, p1, p2, p3, p4, p5 ]; + + } + + set( p0, p1, p2, p3, p4, p5 ) { + + const 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 ); + + return this; + + } + + copy( frustum ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + planes[ i ].copy( frustum.planes[ i ] ); + + } + + return this; + + } + + setFromProjectionMatrix( m ) { + + const planes = this.planes; + const me = m.elements; + const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + + 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(); + + return this; + + } + + intersectsObject( object ) { + + const geometry = object.geometry; + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSprite( sprite ) { + + _sphere$2.center.set( 0, 0, 0 ); + _sphere$2.radius = 0.7071067811865476; + _sphere$2.applyMatrix4( sprite.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSphere( sphere ) { + + const planes = this.planes; + const center = sphere.center; + const negRadius = - sphere.radius; + + for ( let i = 0; i < 6; i ++ ) { + + const distance = planes[ i ].distanceToPoint( center ); + + if ( distance < negRadius ) { + + return false; + + } + + } + + return true; + + } + + intersectsBox( box ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + const plane = planes[ i ]; + + // corner at max distance + + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; + + if ( plane.distanceToPoint( _vector$7 ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + containsPoint( point ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +function WebGLAnimation() { + + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + + function onAnimationFrame( time, frame ) { + + animationLoop( time, frame ); + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + } + + return { + + start: function () { + + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + isAnimating = true; + + }, + + stop: function () { + + context.cancelAnimationFrame( requestId ); + + isAnimating = false; + + }, + + setAnimationLoop: function ( callback ) { + + animationLoop = callback; + + }, + + setContext: function ( value ) { + + context = value; + + } + + }; + +} + +function WebGLAttributes( gl, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + const buffers = new WeakMap(); + + function createBuffer( attribute, bufferType ) { + + const array = attribute.array; + const usage = attribute.usage; + + const buffer = gl.createBuffer(); + + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); + + attribute.onUploadCallback(); + + let type; + + if ( array instanceof Float32Array ) { + + type = gl.FLOAT; + + } else if ( array instanceof Uint16Array ) { + + if ( attribute.isFloat16BufferAttribute ) { + + if ( isWebGL2 ) { + + type = gl.HALF_FLOAT; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); + + } + + } else { + + type = gl.UNSIGNED_SHORT; + + } + + } else if ( array instanceof Int16Array ) { + + type = gl.SHORT; + + } else if ( array instanceof Uint32Array ) { + + type = gl.UNSIGNED_INT; + + } else if ( array instanceof Int32Array ) { + + type = gl.INT; + + } else if ( array instanceof Int8Array ) { + + type = gl.BYTE; + + } else if ( array instanceof Uint8Array ) { + + type = gl.UNSIGNED_BYTE; + + } else if ( array instanceof Uint8ClampedArray ) { + + type = gl.UNSIGNED_BYTE; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + + } + + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; + + } + + function updateBuffer( buffer, attribute, bufferType ) { + + const array = attribute.array; + const updateRange = attribute.updateRange; + + gl.bindBuffer( bufferType, buffer ); + + if ( updateRange.count === - 1 ) { + + // Not using update ranges + + gl.bufferSubData( bufferType, 0, array ); + + } else { + + if ( isWebGL2 ) { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array, updateRange.offset, updateRange.count ); + + } else { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); + + } + + updateRange.count = - 1; // reset range + + } + + attribute.onUploadCallback(); + + } + + // + + function get( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + return buffers.get( attribute ); + + } + + function remove( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data ) { + + gl.deleteBuffer( data.buffer ); + + buffers.delete( attribute ); + + } + + } + + function update( attribute, bufferType ) { + + if ( attribute.isGLBufferAttribute ) { + + const cached = buffers.get( attribute ); + + if ( ! cached || cached.version < attribute.version ) { + + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); + + } + + return; + + } + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data === undefined ) { + + buffers.set( attribute, createBuffer( attribute, bufferType ) ); + + } else if ( data.version < attribute.version ) { + + updateBuffer( data.buffer, attribute, bufferType ); + + data.version = attribute.version; + + } + + } + + return { + + get: get, + remove: remove, + update: update + + }; + +} + +class PlaneGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { + + super(); + + this.type = 'PlaneGeometry'; + + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + + const width_half = width / 2; + const height_half = height / 2; + + const gridX = Math.floor( widthSegments ); + const gridY = Math.floor( heightSegments ); + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + const segment_width = width / gridX; + const segment_height = height / gridY; + + // + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segment_height - height_half; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segment_width - width_half; + + vertices.push( x, - y, 0 ); + + normals.push( 0, 0, 1 ); + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + } + + } + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = ix + gridX1 * iy; + const b = ix + gridX1 * ( iy + 1 ); + const c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = ( ix + 1 ) + gridX1 * iy; + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + +} + +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; + +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + +var begin_vertex = "vec3 transformed = vec3( position );"; + +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; + +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; + +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; + +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + +var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + +var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}"; + +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + +var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; + +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; + +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + +var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + +var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + +var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + +var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; + +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; + +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + +var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; + +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; + +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; + +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + +var skinbase_vertex = "#ifdef USE_SKINNING\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#endif"; + +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; + +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + +var skinnormal_vertex = "#ifdef USE_SKINNING\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\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; + +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; + +var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; + +var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; + +var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; + +var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + +var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; + +var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; + +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + +const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + +const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; + +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}"; + +const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}"; + +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$6 = "#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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}"; + +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + 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_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + 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_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + 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, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + output_fragment: output_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + 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, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_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, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; + +/** + * Uniforms library for shared webgl shaders + */ + +const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + + }, + + envmap: { + + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 } + + }, + + emissivemap: { + + emissiveMap: { value: null } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + roughnessmap: { + + roughnessMap: { value: null } + + }, + + metalnessmap: { + + metalnessMap: { value: null } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + } + +}; + +const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distanceRGBA: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + +}; + +ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatNormalMap: { value: null }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + +}; + +const _rgb = { r: 0, b: 0, g: 0 }; + +function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function render( renderList, scene ) { + + let forceClear = false; + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background ); + + } + + // Ignore background in AR + // TODO: Reconsider this. + + const xr = renderer.xr; + const session = xr.getSession && xr.getSession(); + + if ( session && session.environmentBlendMode === 'additive' ) { + + background = null; + + } + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + if ( renderer.autoClear || forceClear ) { + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render + + }; + +} + +function WebGLBindingStates( gl, extensions, attributes, capabilities ) { + + const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + + const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' ); + const vaoAvailable = capabilities.isWebGL2 || extension !== null; + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + if ( vaoAvailable ) { + + const state = getBindingState( geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + } else { + + const wireframe = ( material.wireframe === true ); + + if ( currentState.geometry !== geometry.id || + currentState.program !== program.id || + currentState.wireframe !== wireframe ) { + + currentState.geometry = geometry.id; + currentState.program = program.id; + currentState.wireframe = wireframe; + + updateBuffers = true; + + } + + } + + if ( index !== null ) { + + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + if ( capabilities.isWebGL2 ) return gl.createVertexArray(); + + return extension.createVertexArrayOES(); + + } + + function bindVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao ); + + return extension.bindVertexArrayOES( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao ); + + return extension.deleteVertexArrayOES( vao ); + + } + + function getBindingState( geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let programMap = bindingStates[ geometry.id ]; + + if ( programMap === undefined ) { + + programMap = {}; + bindingStates[ geometry.id ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + + extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset ) { + + if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { + + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return; + + } + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const programMap = bindingStates[ geometry.id ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + +} + +function WebGLBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawArraysInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawArraysInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLCapabilities( gl, extensions, parameters ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext; + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + + const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + + const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + + const vertexTextures = maxVertexTextures > 0; + const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' ); + const floatVertexTextures = vertexTextures && floatFragmentTextures; + + const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0; + + return { + + isWebGL2: isWebGL2, + + drawBuffers: drawBuffers, + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures, + + maxSamples: maxSamples + + }; + +} + +function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const 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; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + +} + +function WebGLCubeMaps( renderer ) { + + let cubemaps = new WeakMap(); + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function get( texture ) { + + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubemaps.has( texture ) ) { + + const cubemap = cubemaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubemaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemap = cubemaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubemaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function dispose() { + + cubemaps = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class OrthographicCamera extends Camera { + + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + + super(); + + this.isOrthographicCamera = true; + + this.type = 'OrthographicCamera'; + + this.zoom = 1; + this.view = null; + + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + + this.near = near; + this.far = far; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + return this; + + } + + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + 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 ); + + return data; + + } + +} + +const LOD_MIN = 4; + +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; + +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; + +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; + +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ + +class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._compileMaterial( this._blurMaterial ); + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + + _oldTarget = this._renderer.getRenderTarget(); + + this._setSize( 256 ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + + this._lodPlanes[ i ].dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + encoding: LinearEncoding, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); + + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); + + let useSolidColor = false; + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { + + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); + + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); + + } + + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); + + } + + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; + + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; + + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + + if ( samples > MAX_SAMPLES ) { + + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + + } + + const weights = []; + let sum = 0; + + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); + + if ( i === 0 ) { + + sum += weight; + + } else if ( i < samples ) { + + sum += 2 * weight; + + } + + } + + for ( let i = 0; i < weights.length; i ++ ) { + + weights[ i ] = weights[ i ] / sum; + + } + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + + if ( poleAxis ) { + + blurUniforms[ 'poleAxis' ].value = poleAxis; + + } + + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + + + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + +} + +function WebGLCubeUVMaps( renderer ) { + + let cubeUVmaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { + + texture.needsPMREMUpdate = false; + + let renderTarget = cubeUVmaps.get( texture ); + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( cubeUVmaps.has( texture ) ) { + + return cubeUVmaps.get( texture ).texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemapUV = cubeUVmaps.get( texture ); + + if ( cubemapUV !== undefined ) { + + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); + + } + + } + + function dispose() { + + cubeUVmaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + +} + +function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + let 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; + + 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; + + default: + extension = gl.getExtension( name ); + + } + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function ( capabilities ) { + + if ( capabilities.isWebGL2 ) { + + getExtension( 'EXT_color_buffer_float' ); + + } else { + + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); + + } + + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + +} + +function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + + } + + // morph targets + + const morphAttributes = geometry.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = morphAttributes[ name ]; + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + attributes.update( array[ i ], gl.ARRAY_BUFFER ); + + } + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } + + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + +} + +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawElementsInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; + + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; + + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; + + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + + case gl.POINTS: + render.points += instanceCount * count; + break; + + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + +} + +function numericalSort( a, b ) { + + return a[ 0 ] - b[ 0 ]; + +} + +function absNumericalSort( a, b ) { + + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + +} + +function WebGLMorphtargets( gl, capabilities, textures ) { + + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + const workInfluences = []; + + for ( let i = 0; i < 8; i ++ ) { + + workInfluences[ i ] = [ i, 0 ]; + + } + + function update( object, geometry, material, program ) { + + const objectInfluences = object.morphTargetInfluences; + + if ( capabilities.isWebGL2 === true ) { + + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + + } else { + + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + + const length = objectInfluences === undefined ? 0 : objectInfluences.length; + + let influences = influencesList[ geometry.id ]; + + if ( influences === undefined || influences.length !== length ) { + + // initialise list + + influences = []; + + for ( let i = 0; i < length; i ++ ) { + + influences[ i ] = [ i, 0 ]; + + } + + influencesList[ geometry.id ] = influences; + + } + + // Collect influences + + for ( let i = 0; i < length; i ++ ) { + + const influence = influences[ i ]; + + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; + + } + + influences.sort( absNumericalSort ); + + for ( let i = 0; i < 8; i ++ ) { + + if ( i < length && influences[ i ][ 1 ] ) { + + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + + } else { + + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; + + } + + } + + workInfluences.sort( numericalSort ); + + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < 8; i ++ ) { + + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; + + if ( index !== Number.MAX_SAFE_INTEGER && value ) { + + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + + } + + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + + } + + morphInfluences[ i ] = value; + morphInfluencesSum += value; + + } else { + + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + + geometry.deleteAttribute( 'morphTarget' + i ); + + } + + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + + geometry.deleteAttribute( 'morphNormal' + i ); + + } + + morphInfluences[ i ] = 0; + + } + + } + + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + + } + + } + + return { + + update: update + + }; + +} + +function WebGLObjects( gl, geometries, attributes, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, gl.ARRAY_BUFFER ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + +} + +/** + * 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 )'. + * + * + * 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, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + +// --- Utilities --- + +// Array Caches (provide typed arrays for temporary by size) + +const arrayCacheF32 = []; +const arrayCacheI32 = []; + +// Float32Array caches used for uploading Matrix uniforms + +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); + +// Flattening for arrays of vectors and matrices + +function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + +} + +function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + +} + +function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + +} + +// Texture unit allocation + +function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + +} + +// --- Setters --- + +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. + +// Single scalar + +function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single float vector (from flat array or THREE.VectorN) + +function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single matrix (from flat array or THREE.MatrixN) + +function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + +} + +// Single integer / boolean + +function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single integer / boolean vector (from flat array or THREE.VectorN) + +function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single unsigned integer + +function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single unsigned integer vector (from flat array or THREE.VectorN) + +function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + + +// Single texture (2D / Cube) + +function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2D( v || emptyTexture, unit ); + +} + +function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + +} + +function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + +} + +function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + +} + +// Helper to pick the right setter for the singular case + +function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + +} + + +// Array of scalars + +function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + +} + +// Array of vectors (from flat array or array of THREE.VectorN) + +function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + +} + +function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + +} + +function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + +} + +// Array of matrices (from flat array or array of THREE.MatrixN) + +function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + +} + +function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + +} + +function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + +} + +// Array of integer / boolean + +function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + +} + +// Array of integer / boolean vectors (from flat array) + +function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + +} + +function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + +} + +function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + +} + +// Array of unsigned integer + +function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + +} + +// Array of unsigned integer vectors (from flat array) + +function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + +} + +function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + +} + +function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + +} + + +// Array of textures (2D / 3D / Cube / 2DArray) + +function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + + } + +} + +function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + +} + +function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + +} + +function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + +} + + +// Helper to pick the right setter for a pure (bottom-level) array + +function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + +} + +// --- Uniform Classes --- + +class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + +} + +// --- Top-level --- + +// Parser - builds up the property tree from the path strings + +const RePathPart = /(\w+)(\])?(\[|\.)?/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. + +function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + +} + +function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + +} + +// Root Container + +class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + +} + +function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + +} + +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + +} + +function getEncodingComponents( encoding ) { + + switch ( encoding ) { + + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); + return [ 'Linear', '( value )' ]; + + } + +} + +function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS ); + const errors = gl.getShaderInfoLog( shader ).trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + +} + +function getTexelEncodingFunction( functionName, encoding ) { + + const components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + +} + +function getToneMappingFunction( functionName, toneMapping ) { + + let toneMappingName; + + switch ( toneMapping ) { + + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + +} + +function generateExtensions( parameters ) { + + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + +} + +function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2; + if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3; + if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +function includeReplacer( match, include ) { + + const string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + 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 && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( 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.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + + runnable = false; + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const isWebGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const vertexTextures = capabilities.vertexTextures; + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const useAlphaTest = material.alphaTest > 0; + const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; + + const parameters = { + + isWebGL2: isWebGL2, + + shaderID: shaderID, + shaderName: material.type, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: object.isInstancedMesh === true, + instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ), + map: !! material.map, + matcap: !! material.matcap, + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + + decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ), + + clearcoat: useClearcoat, + clearcoatMap: useClearcoat && !! material.clearcoatMap, + clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, + clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + specularIntensityMap: !! material.specularIntensityMap, + specularColorMap: !! material.specularColorMap, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: !! material.alphaMap, + alphaTest: useAlphaTest, + + gradientMap: !! material.gradientMap, + + sheen: material.sheen > 0, + sheenColorMap: !! material.sheenColorMap, + sheenRoughnessMap: !! material.sheenRoughnessMap, + + transmission: material.transmission > 0, + transmissionMap: !! material.transmissionMap, + thicknessMap: !! material.thicknessMap, + + combine: material.combine, + + vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: !! material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + + rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputEncoding ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputEncoding ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.combine ); + array.push( parameters.vertexUvs ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.map ) + _programLayers.enable( 4 ); + if ( parameters.matcap ) + _programLayers.enable( 5 ); + if ( parameters.envMap ) + _programLayers.enable( 6 ); + if ( parameters.lightMap ) + _programLayers.enable( 7 ); + if ( parameters.aoMap ) + _programLayers.enable( 8 ); + if ( parameters.emissiveMap ) + _programLayers.enable( 9 ); + if ( parameters.bumpMap ) + _programLayers.enable( 10 ); + if ( parameters.normalMap ) + _programLayers.enable( 11 ); + if ( parameters.objectSpaceNormalMap ) + _programLayers.enable( 12 ); + if ( parameters.tangentSpaceNormalMap ) + _programLayers.enable( 13 ); + if ( parameters.clearcoat ) + _programLayers.enable( 14 ); + if ( parameters.clearcoatMap ) + _programLayers.enable( 15 ); + if ( parameters.clearcoatRoughnessMap ) + _programLayers.enable( 16 ); + if ( parameters.clearcoatNormalMap ) + _programLayers.enable( 17 ); + if ( parameters.iridescence ) + _programLayers.enable( 18 ); + if ( parameters.iridescenceMap ) + _programLayers.enable( 19 ); + if ( parameters.iridescenceThicknessMap ) + _programLayers.enable( 20 ); + if ( parameters.displacementMap ) + _programLayers.enable( 21 ); + if ( parameters.specularMap ) + _programLayers.enable( 22 ); + if ( parameters.roughnessMap ) + _programLayers.enable( 23 ); + if ( parameters.metalnessMap ) + _programLayers.enable( 24 ); + if ( parameters.gradientMap ) + _programLayers.enable( 25 ); + if ( parameters.alphaMap ) + _programLayers.enable( 26 ); + if ( parameters.alphaTest ) + _programLayers.enable( 27 ); + if ( parameters.vertexColors ) + _programLayers.enable( 28 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 29 ); + if ( parameters.vertexUvs ) + _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.physicallyCorrectLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.specularIntensityMap ) + _programLayers.enable( 15 ); + if ( parameters.specularColorMap ) + _programLayers.enable( 16 ); + if ( parameters.transmission ) + _programLayers.enable( 17 ); + if ( parameters.transmissionMap ) + _programLayers.enable( 18 ); + if ( parameters.thicknessMap ) + _programLayers.enable( 19 ); + if ( parameters.sheen ) + _programLayers.enable( 20 ); + if ( parameters.sheenColorMap ) + _programLayers.enable( 21 ); + if ( parameters.sheenRoughnessMap ) + _programLayers.enable( 22 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 23 ); + if ( parameters.opaque ) + _programLayers.enable( 24 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + +function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + + + +let nextVersion = 0; + +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + +} + +function WebGLLights( extensions, capabilities ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + directionalLength: - 1, + pointLength: - 1, + spotLength: - 1, + rectAreaLength: - 1, + hemiLength: - 1, + + numDirectionalShadows: - 1, + numPointShadows: - 1, + numSpotShadows: - 1, + numSpotMaps: - 1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights, physicallyCorrectLights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + + if ( light.isAmbientLight ) { + + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( capabilities.isWebGL2 ) { + + // WebGL 2 + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + // WebGL 1 + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } else { + + console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' ); + + } + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { + + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + +} + +function WebGLRenderState( extensions, capabilities ) { + + const lights = new WebGLLights( extensions, capabilities ); + + const lightsArray = []; + const shadowsArray = []; + + function init() { + + lightsArray.length = 0; + shadowsArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function setupLights( physicallyCorrectLights ) { + + lights.setup( lightsArray, physicallyCorrectLights ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + + lights: lights + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow + }; + +} + +function WebGLRenderStates( extensions, capabilities ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class MeshDepthMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDepthMaterial = true; + + this.type = 'MeshDepthMaterial'; + + this.depthPacking = BasicDepthPacking; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.depthPacking = source.depthPacking; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + return this; + + } + +} + +class MeshDistanceMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDistanceMaterial = true; + + this.type = 'MeshDistanceMaterial'; + + this.referencePosition = new Vector3(); + this.nearDistance = 1; + this.farDistance = 1000; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.referencePosition.copy( source.referencePosition ); + this.nearDistance = source.nearDistance; + this.farDistance = source.farDistance; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + return this; + + } + +} + +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + +function WebGLShadowMap( _renderer, _objects, _capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = _capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide, [ TwoPassDoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + const currentRenderTarget = _renderer.getRenderTarget(); + const activeCubeFace = _renderer.getActiveCubeFace(); + const activeMipmapLevel = _renderer.getActiveMipmapLevel(); + + const _state = _renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + if ( shadow.map === null ) { + + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + '.shadowMap'; + + shadow.camera.updateProjectionMatrix(); + + } + + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + + const viewportCount = shadow.getViewportCount(); + + for ( let vp = 0; vp < viewportCount; vp ++ ) { + + const viewport = shadow.getViewport( vp ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + shadow.updateMatrices( light, vp ); + + _frustum = shadow.getFrustum(); + + renderObject( scene, camera, shadow.camera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + scope.needsUpdate = false; + + _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = _objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // vertical pass + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.mapPass ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + result.referencePosition.setFromMatrixPosition( light.matrixWorld ); + result.nearDistance = shadowCameraNear; + result.farDistance = shadowCameraFar; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = _objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + +} + +function WebGLState( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( gl.NEVER ); + break; + + case AlwaysDepth: + + gl.depthFunc( gl.ALWAYS ); + break; + + case LessDepth: + + gl.depthFunc( gl.LESS ); + break; + + case LessEqualDepth: + + gl.depthFunc( gl.LEQUAL ); + break; + + case EqualDepth: + + gl.depthFunc( gl.EQUAL ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( gl.GEQUAL ); + break; + + case GreaterDepth: + + gl.depthFunc( gl.GREATER ); + break; + + case NotEqualDepth: + + gl.depthFunc( gl.NOTEQUAL ); + break; + + default: + + gl.depthFunc( gl.LEQUAL ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + gl.clearDepth( depth ); + currentDepthClear = depth; + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( gl.STENCIL_TEST ); + + } else { + + disable( gl.STENCIL_TEST ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( gl.SCISSOR_BOX ); + const viewportParam = gl.getParameter( gl.VIEWPORT ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const 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 ); + + for ( let i = 0; i < count; i ++ ) { + + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } + + return texture; + + } + + const 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 ); + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + + if ( target === gl.DRAW_FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer; + + } + + if ( target === gl.FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; + + needsUpdate = true; + + } + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.BACK ) { + + drawBuffers[ 0 ] = gl.BACK; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + if ( capabilities.isWebGL2 ) { + + gl.drawBuffers( drawBuffers ); + + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } + + } + + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: gl.FUNC_ADD, + [ SubtractEquation ]: gl.FUNC_SUBTRACT, + [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT + }; + + if ( isWebGL2 ) { + + equationToGL[ MinEquation ] = gl.MIN; + equationToGL[ MaxEquation ] = gl.MAX; + + } else { + + const extension = extensions.get( 'EXT_blend_minmax' ); + + if ( extension !== null ) { + + equationToGL[ MinEquation ] = extension.MIN_EXT; + equationToGL[ MaxEquation ] = extension.MAX_EXT; + + } + + } + + const factorToGL = { + [ ZeroFactor ]: gl.ZERO, + [ OneFactor ]: gl.ONE, + [ SrcColorFactor ]: gl.SRC_COLOR, + [ SrcAlphaFactor ]: gl.SRC_ALPHA, + [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE, + [ DstColorFactor ]: gl.DST_COLOR, + [ DstAlphaFactor ]: gl.DST_ALPHA, + [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR, + [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA, + [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR, + [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( gl.BLEND ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( gl.BLEND ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( gl.FUNC_ADD ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( gl.CULL_FACE ) + : enable( gl.CULL_FACE ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE ) + : disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( gl.CW ); + + } else { + + gl.frontFace( gl.CCW ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( gl.CULL_FACE ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( gl.BACK ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( gl.FRONT ); + + } else { + + gl.cullFace( gl.FRONT_AND_BACK ); + + } + + } + + } else { + + disable( gl.CULL_FACE ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( gl.POLYGON_OFFSET_FILL ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + gl.polygonOffset( factor, units ); + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + } + + } else { + + disable( gl.POLYGON_OFFSET_FILL ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( gl.SCISSOR_TEST ); + + } else { + + disable( gl.SCISSOR_TEST ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = gl.TEXTURE0 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( gl.BLEND ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.POLYGON_OFFSET_FILL ); + gl.disable( gl.SCISSOR_TEST ); + gl.disable( gl.STENCIL_TEST ); + gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ONE, gl.ZERO ); + gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( gl.LESS ); + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff ); + gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP ); + gl.clearStencil( 0 ); + + gl.cullFace( gl.BACK ); + gl.frontFace( gl.CCW ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( gl.TEXTURE0 ); + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + + if ( isWebGL2 === true ) { + + gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); + + } + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + // reset internals + + enabledCapabilities = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + +} + +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _videoTextures = new WeakMap(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { + + let scale = 1; + + // handle case if texture exceeds max size + + if ( image.width > maxSize || image.height > maxSize ) { + + scale = maxSize / Math.max( image.width, image.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 || needsPowerOfTwo === true ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; + + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function isPowerOfTwo$1( image ) { + + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + + } + + function textureNeedsPowerOfTwo( texture ) { + + if ( isWebGL2 ) return false; + + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + + } + + function textureNeedsGenerateMipmaps( texture, supportsMips ) { + + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) { + + if ( isWebGL2 === false ) return glFormat; + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let internalFormat = glFormat; + + if ( glFormat === _gl.RED ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; + + } + + if ( glFormat === _gl.RG ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8; + + } + + if ( glFormat === _gl.RGBA ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4; + if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1; + + } + + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || + internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getMipLevels( texture, image, supportsMips ) { + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // Fallback filters for non-power-of-2 textures + + function filterFallback( f ) { + + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + + return _gl.NEAREST; + + } + + return _gl.LINEAR; + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; + + } + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + for ( let i = 0, il = texture.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( texture[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( texture[ i ] ); + + } + + } + + properties.remove( texture ); + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= maxTextures ) { + + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.encoding ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } + + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: _gl.REPEAT, + [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, + [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT + }; + + const filterToGL = { + [ NearestFilter ]: _gl.NEAREST, + [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, + [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, + + [ LinearFilter ]: _gl.LINEAR, + [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, + [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR + }; + + function setTextureParameters( textureType, texture, supportsMips ) { + + if ( supportsMips ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); + + } else { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _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.' ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + + 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.' ); + + } + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + + 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; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create Source <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = _gl.TEXTURE_2D; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY; + if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _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 ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ); + + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture ); + + setTextureParameters( textureType, texture, supportsMips ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); + + if ( texture.isDepthTexture ) { + + // populate depth texture with dummy data + + glInternalFormat = _gl.DEPTH_COMPONENT; + + if ( isWebGL2 ) { + + if ( texture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( texture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( texture.type === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } else { + + glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D + + } + + } else { + + if ( texture.type === FloatType ) { + + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + + } + + } + + // validation checks for WebGL 1 + + if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); + + } + + } + + if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = _gl.DEPTH_STENCIL; + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); + + } + + } + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( 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 + + if ( mipmaps.length > 0 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } else { + + state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else { + + // regular Texture (image, video, canvas) + + // 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 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _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 ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); + + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) { + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const renderTargetProperties = properties.get( renderTarget ); + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) { + + state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753 + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + + let glInternalFormat = _gl.DEPTH_COMPONENT16; + + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { + + const depthTexture = renderTarget.depthTexture; + + if ( depthTexture && depthTexture.isDepthTexture ) { + + if ( depthTexture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( depthTexture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } + + } + + const samples = getRenderTargetSamples( renderTarget ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + + } + + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else { + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { + + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + + } + + // 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; + + } + + setTexture2D( renderTarget.depthTexture, 0 ); + + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'Unknown depthTexture format' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } + + } else { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + if ( isMultipleRenderTargets ) { + + if ( capabilities.drawBuffers ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); + + } + + } + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = isMultipleRenderTargets ? texture : [ texture ]; + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + for ( let i = 0; i < 6; i ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D ); + + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_2D ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + if ( isWebGL2 ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } else { + + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); + + } + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType ); + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); + + } + + } + + } + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i ); + + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; + if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] ); + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); + + if ( supportsInvalidateFramebuffer ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray ); + + } + + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const encoding = texture.encoding; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image; + + if ( encoding !== LinearEncoding ) { + + // sRGB + + if ( encoding === sRGBEncoding ) { + + if ( isWebGL2 === false ) { + + // in WebGL 1, try to use EXT_sRGB extension and unsized formats + + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { + + texture.format = _SRGBAFormat; + + // it's not possible to generate mips in WebGL 1 with this extension + + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; + + } else { + + // slow fallback (CPU decode) + + image = ImageUtils.sRGBToLinear( image ); + + } + + } else { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } + + } else { + + console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding ); + + } + + } + + return image; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + +} + +function WebGLUtils( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function convert( p, encoding = null ) { + + let extension; + + 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 === 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; + + if ( p === HalfFloatType ) { + + if ( isWebGL2 ) return gl.HALF_FLOAT; + + extension = extensions.get( 'OES_texture_half_float' ); + + if ( extension !== null ) { + + return extension.HALF_FLOAT_OES; + + } else { + + return null; + + } + + } + + if ( p === AlphaFormat ) return gl.ALPHA; + 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 === DepthStencilFormat ) return gl.DEPTH_STENCIL; + + // WebGL 1 sRGB fallback + + if ( p === _SRGBAFormat ) { + + extension = extensions.get( 'EXT_sRGB' ); + + if ( extension !== null ) { + + return extension.SRGB_ALPHA_EXT; + + } else { + + return null; + + } + + } + + // WebGL2 formats. + + if ( p === RedFormat ) return gl.RED; + if ( p === RedIntegerFormat ) return gl.RED_INTEGER; + if ( p === RGFormat ) return gl.RG; + if ( p === RGIntegerFormat ) return gl.RG_INTEGER; + if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( encoding === sRGBEncoding ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + 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; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + 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; + + } else { + + return null; + + } + + } + + // ETC1 + + if ( p === RGB_ETC1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + + if ( extension !== null ) { + + return extension.COMPRESSED_RGB_ETC1_WEBGL; + + } else { + + return null; + + } + + } + + // ETC2 + + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) { + + if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8; + + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { + + return extension.UNSIGNED_INT_24_8_WEBGL; + + } else { + + return null; + + } + + } + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + +} + +class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; + + } + +} + +class Group extends Object3D { + + constructor() { + + super(); + + this.isGroup = true; + + this.type = 'Group'; + + } + +} + +const _moveEvent = { type: 'move' }; + +class WebXRController { + + constructor() { + + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + + } + + return this._hand; + + } + + getTargetRaySpace() { + + if ( this._targetRay === null ) { + + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + + } + + return this._targetRay; + + } + + getGripSpace() { + + if ( this._grip === null ) { + + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + + } + + return this._grip; + + } + + dispatchEvent( event ) { + + if ( this._targetRay !== null ) { + + this._targetRay.dispatchEvent( event ); + + } + + if ( this._grip !== null ) { + + this._grip.dispatchEvent( event ); + + } + + if ( this._hand !== null ) { + + this._hand.dispatchEvent( event ); + + } + + return this; + + } + + connect( inputSource ) { + + if ( inputSource && inputSource.hand ) { + + const hand = this._hand; + + if ( hand ) { + + for ( const inputjoint of inputSource.hand.values() ) { + + // Initialize hand with joints when connected + this._getHandJoint( hand, inputjoint ); + + } + + } + + } + + this.dispatchEvent( { type: 'connected', data: inputSource } ); + + return this; + + } + + disconnect( inputSource ) { + + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + + if ( this._targetRay !== null ) { + + this._targetRay.visible = false; + + } + + if ( this._grip !== null ) { + + this._grip.visible = false; + + } + + if ( this._hand !== null ) { + + this._hand.visible = false; + + } + + return this; + + } + + update( inputSource, frame, referenceSpace ) { + + let inputPose = null; + let gripPose = null; + let handPose = null; + + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + + if ( hand && inputSource.hand ) { + + handPose = true; + + for ( const inputjoint of inputSource.hand.values() ) { + + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + + // The transform of this joint will be updated with the joint pose on each frame + const joint = this._getHandJoint( hand, inputjoint ); + + if ( jointPose !== null ) { + + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.jointRadius = jointPose.radius; + + } + + joint.visible = jointPose !== null; + + } + + // Custom events + + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); + + const distanceToPinch = 0.02; + const threshold = 0.005; + + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); + + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); + + } + + } else { + + if ( grip !== null && inputSource.gripSpace ) { + + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + + if ( gripPose !== null ) { + + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + + if ( gripPose.linearVelocity ) { + + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); + + } else { + + grip.hasLinearVelocity = false; + + } + + if ( gripPose.angularVelocity ) { + + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); + + } else { + + grip.hasAngularVelocity = false; + + } + + } + + } + + } + + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + + } + + if ( targetRay !== null ) { + + targetRay.visible = ( inputPose !== null ); + + } + + if ( grip !== null ) { + + grip.visible = ( gripPose !== null ); + + } + + if ( hand !== null ) { + + hand.visible = ( handPose !== null ); + + } + + return this; + + } + + // private method + + _getHandJoint( hand, inputjoint ) { + + if ( hand.joints[ inputjoint.jointName ] === undefined ) { + + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + + hand.add( joint ); + + } + + return hand.joints[ inputjoint.jointName ]; + + } + +} + +class DepthTexture extends Texture { + + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + + format = format !== undefined ? format : DepthFormat; + + if ( format !== DepthFormat && format !== DepthStencilFormat ) { + + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + + } + + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isDepthTexture = true; + + this.image = { width: width, height: height }; + + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + + this.flipY = false; + this.generateMipmaps = false; + + } + + +} + +class WebXRManager extends EventDispatcher { + + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + const planes = new Set(); + const planesLastChangedTimes = new Map(); + + // + + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + this.cameraAutoUpdate = true; + this.enabled = false; + + this.isPresenting = false; + + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + this.getBinding = function () { + + return glBinding; + + }; + + this.getFrame = function () { + + return xrFrame; + + }; + + this.getSession = function () { + + return session; + + }; + + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { + + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + encoding: renderer.outputEncoding, + stencilBuffer: attributes.stencil + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = new XRWebGLBinding( session, gl ); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + encoding: renderer.outputEncoding, + samples: attributes.antialias ? 4 : 0 + } ); + + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + // Set foveation to maximum. + this.setFoveation( 1.0 ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; + + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); + + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; + + } + + const parent = camera.parent; + const cameras = cameraVR.cameras; + + updateCamera( cameraVR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale ); + + // update user camera and its children + + camera.matrix.copy( cameraVR.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + + const children = camera.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].updateMatrixWorld( true ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraVR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + }; + + this.getCamera = function () { + + return cameraVR; + + }; + + this.getFoveation = function () { + + if ( glProjLayer !== null ) { + + return glProjLayer.fixedFoveation; + + } + + if ( glBaseLayer !== null ) { + + return glBaseLayer.fixedFoveation; + + } + + return undefined; + + }; + + this.setFoveation = function ( foveation ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = foveation; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = foveation; + + } + + }; + + this.getPlanes = function () { + + return planes; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraVRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraVR's camera list + + if ( views.length !== cameraVR.cameras.length ) { + + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraVR.matrix.copy( camera.matrix ); + + } + + if ( cameraVRNeedsUpdate === true ) { + + cameraVR.cameras.push( camera ); + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } ); + + let planesToRemove = null; + + for ( const plane of planes ) { + + if ( ! frame.detectedPlanes.has( plane ) ) { + + if ( planesToRemove === null ) { + + planesToRemove = []; + + } + + planesToRemove.push( plane ); + + } + + } + + if ( planesToRemove !== null ) { + + for ( const plane of planesToRemove ) { + + planes.delete( plane ); + planesLastChangedTimes.delete( plane ); + scope.dispatchEvent( { type: 'planeremoved', data: plane } ); + + } + + } + + for ( const plane of frame.detectedPlanes ) { + + if ( ! planes.has( plane ) ) { + + planes.add( plane ); + planesLastChangedTimes.set( plane, frame.lastChangedTime ); + scope.dispatchEvent( { type: 'planeadded', data: plane } ); + + } else { + + const lastKnownTime = planesLastChangedTimes.get( plane ); + + if ( plane.lastChangedTime > lastKnownTime ) { + + planesLastChangedTimes.set( plane, plane.lastChangedTime ); + scope.dispatchEvent( { type: 'planechanged', data: plane } ); + + } + + } + + } + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + +} + +function WebGLMaterials( renderer, properties ) { + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1; + + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. displacementMap map + // 4. normal map + // 5. bump map + // 6. roughnessMap map + // 7. metalnessMap map + // 8. alphaMap map + // 9. emissiveMap map + // 10. clearcoat map + // 11. clearcoat normal map + // 12. clearcoat roughnessMap map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.specularMap ) { + + uvScaleMap = material.specularMap; + + } else if ( material.displacementMap ) { + + uvScaleMap = material.displacementMap; + + } else if ( material.normalMap ) { + + uvScaleMap = material.normalMap; + + } else if ( material.bumpMap ) { + + uvScaleMap = material.bumpMap; + + } else if ( material.roughnessMap ) { + + uvScaleMap = material.roughnessMap; + + } else if ( material.metalnessMap ) { + + uvScaleMap = material.metalnessMap; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } else if ( material.emissiveMap ) { + + uvScaleMap = material.emissiveMap; + + } else if ( material.clearcoatMap ) { + + uvScaleMap = material.clearcoatMap; + + } else if ( material.clearcoatNormalMap ) { + + uvScaleMap = material.clearcoatNormalMap; + + } else if ( material.clearcoatRoughnessMap ) { + + uvScaleMap = material.clearcoatRoughnessMap; + + } else if ( material.iridescenceMap ) { + + uvScaleMap = material.iridescenceMap; + + } else if ( material.iridescenceThicknessMap ) { + + uvScaleMap = material.iridescenceThicknessMap; + + } else if ( material.specularIntensityMap ) { + + uvScaleMap = material.specularIntensityMap; + + } else if ( material.specularColorMap ) { + + uvScaleMap = material.specularColorMap; + + } else if ( material.transmissionMap ) { + + uvScaleMap = material.transmissionMap; + + } else if ( material.thicknessMap ) { + + uvScaleMap = material.thicknessMap; + + } else if ( material.sheenColorMap ) { + + uvScaleMap = material.sheenColorMap; + + } else if ( material.sheenRoughnessMap ) { + + uvScaleMap = material.sheenRoughnessMap; + + } + + if ( uvScaleMap !== undefined ) { + + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { + + uvScaleMap = uvScaleMap.texture; + + } + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map + + let uv2ScaleMap; + + if ( material.aoMap ) { + + uv2ScaleMap = material.aoMap; + + } else if ( material.lightMap ) { + + uv2ScaleMap = material.lightMap; + + } + + if ( uv2ScaleMap !== undefined ) { + + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { + + uv2ScaleMap = uv2ScaleMap.texture; + + } + + if ( uv2ScaleMap.matrixAutoUpdate === true ) { + + uv2ScaleMap.updateMatrix(); + + } + + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + } + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + } + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + +} + +function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + gl.bufferData( gl.UNIFORM_BUFFER, size, usage ); + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniform = uniforms[ i ]; + + // partly update the buffer if necessary + + if ( hasUniformChanged( uniform, i, cache ) === true ) { + + const offset = uniform.__offset; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + let arrayOffset = 0; + + for ( let i = 0; i < values.length; i ++ ) { + + const value = values[ i ]; + + const info = getUniformSize( value ); + + if ( typeof value === 'number' ) { + + uniform.__data[ 0 ] = value; + gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data ); + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + uniform.__data[ 0 ] = value.elements[ 0 ]; + uniform.__data[ 1 ] = value.elements[ 1 ]; + uniform.__data[ 2 ] = value.elements[ 2 ]; + uniform.__data[ 3 ] = value.elements[ 0 ]; + uniform.__data[ 4 ] = value.elements[ 3 ]; + uniform.__data[ 5 ] = value.elements[ 4 ]; + uniform.__data[ 6 ] = value.elements[ 5 ]; + uniform.__data[ 7 ] = value.elements[ 0 ]; + uniform.__data[ 8 ] = value.elements[ 6 ]; + uniform.__data[ 9 ] = value.elements[ 7 ]; + uniform.__data[ 10 ] = value.elements[ 8 ]; + uniform.__data[ 11 ] = value.elements[ 0 ]; + + } else { + + value.toArray( uniform.__data, arrayOffset ); + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data ); + + } + + } + + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + + } + + function hasUniformChanged( uniform, index, cache ) { + + const value = uniform.value; + + if ( cache[ index ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' ) { + + cache[ index ] = value; + + } else { + + const values = Array.isArray( value ) ? value : [ value ]; + + const tempValues = []; + + for ( let i = 0; i < values.length; i ++ ) { + + tempValues.push( values[ i ].clone() ); + + } + + cache[ index ] = tempValues; + + } + + return true; + + } else { + + // compare current value with cached entry + + if ( typeof value === 'number' ) { + + if ( cache[ index ] !== value ) { + + cache[ index ] = value; + return true; + + } + + } else { + + const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ]; + const values = Array.isArray( value ) ? value : [ value ]; + + for ( let i = 0; i < cachedObjects.length; i ++ ) { + + const cachedObject = cachedObjects[ i ]; + + if ( cachedObject.equals( values[ i ] ) === false ) { + + cachedObject.copy( values[ i ] ); + return true; + + } + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniform = uniforms[ i ]; + + const infos = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let j = 0, jl = values.length; j < jl; j ++ ) { + + const value = values[ j ]; + + const info = getUniformSize( value ); + + infos.boundary += info.boundary; + infos.storage += info.storage; + + } + + // the following two properties will be used for partial buffer updates + + uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // + + if ( i > 0 ) { + + chunkOffset = offset % chunkSize; + + const remainingSizeInChunk = chunkSize - chunkOffset; + + // check for chunk overflow + + if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) { + + // add padding and adjust offset + + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; + + } + + } + + offset += infos.storage; + + } + + // ensure correct final padding + + chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' ) { + + // float/int + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + +} + +function createCanvasElement() { + + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; + +} + +function WebGLRenderer( parameters = {} ) { + + this.isWebGLRenderer = true; + + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), + _context = parameters.context !== undefined ? parameters.context : null, + + _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, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + + let _alpha; + + if ( _context !== null ) { + + _alpha = _context.getContextAttributes().alpha; + + } else { + + _alpha = parameters.alpha !== undefined ? parameters.alpha : false; + + } + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // public properties + + this.domElement = _canvas; + + // Debug configuration container + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; + + // clearing + + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + + // scene graph + + this.sortObjects = true; + + // user-defined clipping + + this.clippingPlanes = []; + this.localClippingEnabled = false; + + // physically based shading + + this.outputEncoding = LinearEncoding; + + // physical lights + + this.physicallyCorrectLights = false; + + // tone mapping + + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + + // internal state cache + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + // + + let _width = _canvas.width; + let _height = _canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // transmission + + let _transmissionRenderTarget = null; + + // camera matrices cache + + const _projScreenMatrix = new Matrix4(); + + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = _context; + + function getContext( contextNames, contextAttributes ) { + + for ( let i = 0; i < contextNames.length; i ++ ) { + + const contextName = contextNames[ i ]; + const context = _canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; + + } + + return null; + + } + + try { + + const contextAttributes = { + alpha: true, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + + if ( _this.isWebGL1Renderer === true ) { + + contextNames.shift(); + + } + + _gl = getContext( contextNames, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextNames ) ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'Error creating WebGL context.' ); + + } + + } + + } + + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + + }; + + } + + } catch ( error ) { + + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + + extensions.init( capabilities ); + + utils = new WebGLUtils( _gl, extensions, capabilities ); + + state = new WebGLState( _gl, extensions, capabilities ); + + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + + info.programs = programCache.programs; + + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + + } + + initGLContext(); + + // xr + + const xr = new WebXRManager( _this, _gl ); + + this.xr = xr; + + // API + + this.getContext = function () { + + return _gl; + + }; + + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + this.setSize = function ( width, height, updateStyle ) { + + if ( xr.isPresenting ) { + + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle !== false ) { + + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; + + } + + this.setViewport( 0, 0, width, height ); + + }; + + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissorTest = function () { + + return _scissorTest; + + }; + + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + this.setClearColor = function () { + + background.setClearColor.apply( background, arguments ); + + }; + + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + this.setClearAlpha = function () { + + background.setClearAlpha.apply( background, arguments ); + + }; + + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + + _gl.clear( bits ); + + }; + + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + // + + this.dispose = function () { + + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + if ( _transmissionRenderTarget ) { + + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; + + } + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + console.log( 'THREE.WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + console.log( 'THREE.WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); + + } else { + + renderer.setMode( _gl.TRIANGLES ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( _gl.LINES ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( _gl.LINE_LOOP ); + + } else { + + renderer.setMode( _gl.LINE_STRIP ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( _gl.POINTS ); + + } else if ( object.isSprite ) { + + renderer.setMode( _gl.TRIANGLES ); + + } + + if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + this.compile = function ( scene, camera ) { + + function prepare( material, scene, object ) { + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = TwoPassDoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + scene.traverse( function ( object ) { + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepare( material2, scene, object ); + + } + + } else { + + prepare( material, scene, object ); + + } + + } + + } ); + + renderStateStack.pop(); + currentRenderState = null; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + // + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + if ( this.info.autoReset === true ) this.info.reset(); + + // + + background.render( currentRenderList, scene ); + + // render scene + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + renderScene( currentRenderList, scene, camera ); + + } + + // + + if ( _currentRenderTarget !== null ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( object.isSkinnedMesh ) { + + // update skeleton only once in a frame + + if ( object.skeleton.frame !== info.render.frame ) { + + object.skeleton.update(); + object.skeleton.frame = info.render.frame; + + } + + } + + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, scene, camera ) { + + const isWebGL2 = capabilities.isWebGL2; + + if ( _transmissionRenderTarget === null ) { + + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 + } ); + + } + + _this.getDrawingBufferSize( _vector2 ); + + if ( isWebGL2 ) { + + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); + + } else { + + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); + + } + + // + + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + _this.clear(); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + renderObjects( opaqueObjects, scene, camera ); + + _this.toneMapping = currentToneMapping; + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + _this.setRenderTarget( currentRenderTarget ); + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = TwoPassDoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + material.onBuild( object, parameters, _this ); + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputEncoding = parameters.outputEncoding; + materialProperties.instancing = parameters.instancing; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent; + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const 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, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputEncoding !== encoding ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // 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: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( capabilities.floatVertexTextures ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + + } else { + + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); + + } + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { + + morphtargets.update( object, geometry, material, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { + + m_uniforms.envMap.value = envMap; + + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // 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 + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + if ( capabilities.isWebGL2 ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); + + } + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; + + if ( renderTargetProperties.__hasExternalTextures ) { + + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { + + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; + + } + + } + + } + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + useDefaultFramebuffer = false; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + isCube = true; + + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + framebuffer = __webglFramebuffer; + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + + } + + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings + + }; + + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + try { + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + } + + } + + }; + + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + + textures.setTexture2D( dstTexture, 0 ); + + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + + } else { + + if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + + } else { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image ); + + } + + } + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + + if ( _this.isWebGL1Renderer ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; + + } + + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_3D; + + } else if ( dstTexture.isDataArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D_ARRAY; + + } else { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; + + } + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH ); + const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT ); + const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS ); + const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES ); + + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z ); + + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); + + } else { + + if ( srcTexture.isCompressedArrayTexture ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); + + } + + } + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + + state.unbindTexture(); + + }; + + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + +} + +class WebGL1Renderer extends WebGLRenderer {} + +WebGL1Renderer.prototype.isWebGL1Renderer = true; + +class FogExp2 { + + constructor( color, density = 0.00025 ) { + + this.isFogExp2 = true; + + this.name = ''; + + this.color = new Color( color ); + this.density = density; + + } + + clone() { + + return new FogExp2( this.color, this.density ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; + + } + +} + +class Fog { + + constructor( color, near = 1, far = 1000 ) { + + this.isFog = true; + + this.name = ''; + + this.color = new Color( color ); + + this.near = near; + this.far = far; + + } + + clone() { + + return new Fog( this.color, this.near, this.far ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; + + } + +} + +class Scene extends Object3D { + + constructor() { + + super(); + + this.isScene = true; + + this.type = 'Scene'; + + this.background = null; + this.environment = null; + this.fog = null; + + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + + this.overrideMaterial = null; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; + if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + + return data; + + } + + // @deprecated + + get autoUpdate() { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + return this.matrixWorldAutoUpdate; + + } + + set autoUpdate( value ) { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + this.matrixWorldAutoUpdate = value; + + } + +} + +class InterleavedBuffer { + + constructor( array, stride ) { + + this.isInterleavedBuffer = true; + + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + this.uuid = generateUUID(); + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.stride; + index2 *= attribute.stride; + + for ( let i = 0, l = this.stride; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + set( value, offset = 0 ) { + + this.array.set( value, offset ); + + return this; + + } + + clone( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + + } + + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); + + return ib; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + toJSON( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + // generate UUID for array buffer if necessary + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); + + } + + // + + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + + } + +} + +const _vector$6 = /*@__PURE__*/ new Vector3(); + +class InterleavedBufferAttribute { + + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + + this.isInterleavedBufferAttribute = true; + + this.name = ''; + + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + + this.normalized = normalized; + + } + + get count() { + + return this.data.count; + + } + + get array() { + + return this.data.array; + + } + + set needsUpdate( value ) { + + this.data.needsUpdate = value; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.data.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyMatrix4( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.transformDirection( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.data.array[ index * this.data.stride + this.offset ] = x; + + return this; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + + return this; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + + return this; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + + return this; + + } + + getX( index ) { + + let x = this.data.array[ index * this.data.stride + this.offset ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + getY( index ) { + + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + getZ( index ) { + + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + getW( index ) { + + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setXY( index, x, y ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; + + return this; + + } + + clone( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + + } else { + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + + } + + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + + } + + } + + toJSON( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + // de-interleave data and save it as an ordinary buffer attribute for now + + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; + + } else { + + // save as true interleaved attribute + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + + } + + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + + } + + } + +} + +class SpriteMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isSpriteMaterial = true; + + this.type = 'SpriteMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.rotation = 0; + + this.sizeAttenuation = true; + + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.rotation = source.rotation; + + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +let _geometry; + +const _intersectPoint = /*@__PURE__*/ new Vector3(); +const _worldScale = /*@__PURE__*/ new Vector3(); +const _mvPosition = /*@__PURE__*/ new Vector3(); + +const _alignedPosition = /*@__PURE__*/ new Vector2(); +const _rotatedPosition = /*@__PURE__*/ new Vector2(); +const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _vA = /*@__PURE__*/ new Vector3(); +const _vB = /*@__PURE__*/ new Vector3(); +const _vC = /*@__PURE__*/ new Vector3(); + +const _uvA = /*@__PURE__*/ new Vector2(); +const _uvB = /*@__PURE__*/ new Vector2(); +const _uvC = /*@__PURE__*/ new Vector2(); + +class Sprite extends Object3D { + + constructor( material ) { + + super(); + + this.isSprite = true; + + this.type = 'Sprite'; + + if ( _geometry === undefined ) { + + _geometry = new BufferGeometry(); + + const float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); + + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + + } + + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + + this.center = new Vector2( 0.5, 0.5 ); + + } + + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + + } + + _worldScale.setFromMatrixScale( this.matrixWorld ); + + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + + _worldScale.multiplyScalar( - _mvPosition.z ); + + } + + const rotation = this.material.rotation; + let sin, cos; + + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); + + } + + const center = this.center; + + transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); + + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint ); + + if ( intersect === null ) { + + // check second triangle + transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 1 ); + + intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint ); + if ( intersect === null ) { + + return; + + } + + } + + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.center !== undefined ) this.center.copy( source.center ); + + this.material = source.material; + + return this; + + } + +} + +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + + // to check if rotation is not zero + if ( sin !== undefined ) { + + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + + } else { + + _rotatedPosition.copy( _alignedPosition ); + + } + + + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); + +} + +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); + +class LOD extends Object3D { + + constructor() { + + super(); + + this._currentLevel = 0; + + this.type = 'LOD'; + + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true, + } + } ); + + this.autoUpdate = true; + + } + + copy( source ) { + + super.copy( source, false ); + + const levels = source.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + this.addLevel( level.object.clone(), level.distance, level.hysteresis ); + + } + + this.autoUpdate = source.autoUpdate; + + return this; + + } + + addLevel( object, distance = 0, hysteresis = 0 ) { + + distance = Math.abs( distance ); + + const levels = this.levels; + + let l; + + for ( l = 0; l < levels.length; l ++ ) { + + if ( distance < levels[ l ].distance ) { + + break; + + } + + } + + levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } ); + + this.add( object ); + + return this; + + } + + getCurrentLevel() { + + return this._currentLevel; + + } + + + + getObjectForDistance( distance ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance < levelDistance ) { + + break; + + } + + } + + return levels[ i - 1 ].object; + + } + + return null; + + } + + raycast( raycaster, intersects ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + _v1$2.setFromMatrixPosition( this.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); + + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + + } + + } + + update( camera ) { + + const levels = this.levels; + + if ( levels.length > 1 ) { + + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); + + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; + + levels[ 0 ].object.visible = true; + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance >= levelDistance ) { + + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; + + } else { + + break; + + } + + } + + this._currentLevel = i - 1; + + for ( ; i < l; i ++ ) { + + levels[ i ].object.visible = false; + + } + + } + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.autoUpdate === false ) data.object.autoUpdate = false; + + data.object.levels = []; + + const levels = this.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + } ); + + } + + return data; + + } + +} + +const _basePosition = /*@__PURE__*/ new Vector3(); + +const _skinIndex = /*@__PURE__*/ new Vector4(); +const _skinWeight = /*@__PURE__*/ new Vector4(); + +const _vector$5 = /*@__PURE__*/ new Vector3(); +const _matrix = /*@__PURE__*/ new Matrix4(); + +class SkinnedMesh extends Mesh { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isSkinnedMesh = true; + + this.type = 'SkinnedMesh'; + + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); + + this.skeleton = source.skeleton; + + return this; + + } + + bind( skeleton, bindMatrix ) { + + this.skeleton = skeleton; + + if ( bindMatrix === undefined ) { + + this.updateMatrixWorld( true ); + + this.skeleton.calculateInverses(); + + bindMatrix = this.matrixWorld; + + } + + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); + + } + + pose() { + + this.skeleton.pose(); + + } + + normalizeSkinWeights() { + + const vector = new Vector4(); + + const skinWeight = this.geometry.attributes.skinWeight; + + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + + vector.fromBufferAttribute( skinWeight, i ); + + const scale = 1.0 / vector.manhattanLength(); + + if ( scale !== Infinity ) { + + vector.multiplyScalar( scale ); + + } else { + + vector.set( 1, 0, 0, 0 ); // do something reasonable + + } + + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + + } + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.bindMode === 'attached' ) { + + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + + } else if ( this.bindMode === 'detached' ) { + + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + + } else { + + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + + } + + } + + boneTransform( index, target ) { + + const skeleton = this.skeleton; + const geometry = this.geometry; + + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + + _basePosition.copy( target ).applyMatrix4( this.bindMatrix ); + + target.set( 0, 0, 0 ); + + for ( let i = 0; i < 4; i ++ ) { + + const weight = _skinWeight.getComponent( i ); + + if ( weight !== 0 ) { + + const boneIndex = _skinIndex.getComponent( i ); + + _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + + target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight ); + + } + + } + + return target.applyMatrix4( this.bindMatrixInverse ); + + } + +} + +class Bone extends Object3D { + + constructor() { + + super(); + + this.isBone = true; + + this.type = 'Bone'; + + } + +} + +class DataTexture extends Texture { + + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isDataTexture = true; + + this.image = { data: data, width: width, height: height }; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +const _offsetMatrix = /*@__PURE__*/ new Matrix4(); +const _identityMatrix = /*@__PURE__*/ new Matrix4(); + +class Skeleton { + + constructor( bones = [], boneInverses = [] ) { + + this.uuid = generateUUID(); + + this.bones = bones.slice( 0 ); + this.boneInverses = boneInverses; + this.boneMatrices = null; + + this.boneTexture = null; + this.boneTextureSize = 0; + + this.frame = - 1; + + this.init(); + + } + + init() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + + this.boneMatrices = new Float32Array( bones.length * 16 ); + + // calculate inverse bone matrices if necessary + + if ( boneInverses.length === 0 ) { + + this.calculateInverses(); + + } else { + + // handle special case + + if ( bones.length !== boneInverses.length ) { + + console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + + this.boneInverses = []; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + this.boneInverses.push( new Matrix4() ); + + } + + } + + } + + } + + calculateInverses() { + + this.boneInverses.length = 0; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const inverse = new Matrix4(); + + if ( this.bones[ i ] ) { + + inverse.copy( this.bones[ i ].matrixWorld ).invert(); + + } + + this.boneInverses.push( inverse ); + + } + + } + + pose() { + + // recover the bind-time world matrices + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + + } + + } + + // compute the local matrices, positions, rotations and scales + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + if ( bone.parent && bone.parent.isBone ) { + + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); + + } else { + + bone.matrix.copy( bone.matrixWorld ); + + } + + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + + } + + } + + } + + update() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + + // flatten bone matrices to array + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + // compute the offset between the current and the original transform + + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); + + } + + if ( boneTexture !== null ) { + + boneTexture.needsUpdate = true; + + } + + } + + clone() { + + return new Skeleton( this.bones, this.boneInverses ); + + } + + computeBoneTexture() { + + // 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) + + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); + + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values + + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; + + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + this.boneTextureSize = size; + + return this; + + } + + getBoneByName( name ) { + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone.name === name ) { + + return bone; + + } + + } + + return undefined; + + } + + dispose( ) { + + if ( this.boneTexture !== null ) { + + this.boneTexture.dispose(); + + this.boneTexture = null; + + } + + } + + fromJSON( json, bones ) { + + this.uuid = json.uuid; + + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; + + if ( bone === undefined ) { + + console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); + + } + + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + + } + + this.init(); + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; + + data.uuid = this.uuid; + + const bones = this.bones; + const boneInverses = this.boneInverses; + + for ( let i = 0, l = bones.length; i < l; i ++ ) { + + const bone = bones[ i ]; + data.bones.push( bone.uuid ); + + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); + + } + + return data; + + } + +} + +class InstancedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { + + super( array, itemSize, normalized ); + + this.isInstancedBufferAttribute = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.meshPerAttribute = this.meshPerAttribute; + + data.isInstancedBufferAttribute = true; + + return data; + + } + +} + +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _instanceIntersects = []; + +const _identity = /*@__PURE__*/ new Matrix4(); +const _mesh = /*@__PURE__*/ new Mesh(); + +class InstancedMesh extends Mesh { + + constructor( geometry, material, count ) { + + super( geometry, material ); + + this.isInstancedMesh = true; + + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; + + this.count = count; + + this.frustumCulled = false; + + for ( let i = 0; i < count; i ++ ) { + + this.setMatrixAt( i, _identity ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.instanceMatrix.copy( source.instanceMatrix ); + + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + + this.count = source.count; + + return this; + + } + + getColorAt( index, color ) { + + color.fromArray( this.instanceColor.array, index * 3 ); + + } + + getMatrixAt( index, matrix ) { + + matrix.fromArray( this.instanceMatrix.array, index * 16 ); + + } + + raycast( raycaster, intersects ) { + + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + + _mesh.geometry = this.geometry; + _mesh.material = this.material; + + if ( _mesh.material === undefined ) return; + + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + + // calculate the world matrix for each instance + + this.getMatrixAt( instanceId, _instanceLocalMatrix ); + + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + + // the mesh represents this single instance + + _mesh.matrixWorld = _instanceWorldMatrix; + + _mesh.raycast( raycaster, _instanceIntersects ); + + // process the result of raycast + + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); + + } + + _instanceIntersects.length = 0; + + } + + } + + setColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); + + } + + color.toArray( this.instanceColor.array, index * 3 ); + + } + + setMatrixAt( index, matrix ) { + + matrix.toArray( this.instanceMatrix.array, index * 16 ); + + } + + updateMorphTargets() { + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class LineBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isLineBasicMaterial = true; + + this.type = 'LineBasicMaterial'; + + this.color = new Color( 0xffffff ); + + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _start$1 = /*@__PURE__*/ new Vector3(); +const _end$1 = /*@__PURE__*/ new Vector3(); +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$1 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); + +class Line extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + + super(); + + this.isLine = true; + + this.type = 'Line'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; + + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; + + // + + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); + +class LineSegments extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineSegments = true; + + this.type = 'LineSegments'; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); + + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + +} + +class LineLoop extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineLoop = true; + + this.type = 'LineLoop'; + + } + +} + +class PointsMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isPointsMaterial = true; + + this.type = 'PointsMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.size = 1; + this.sizeAttenuation = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix = /*@__PURE__*/ new Matrix4(); +const _ray = /*@__PURE__*/ new Ray(); +const _sphere = /*@__PURE__*/ new Sphere(); +const _position$2 = /*@__PURE__*/ new Vector3(); + +class Points extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + + super(); + + this.isPoints = true; + + this.type = 'Points'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i ++ ) { + + const a = index.getX( i ); + + _position$2.fromBufferAttribute( positionAttribute, a ); + + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end; i < l; i ++ ) { + + _position$2.fromBufferAttribute( positionAttribute, i ); + + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); + + if ( rayPointDistanceSq < localThresholdSq ) { + + const intersectPoint = new Vector3(); + + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object + + } ); + + } + +} + +class VideoTexture extends Texture { + + constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isVideoTexture = true; + + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + + this.generateMipmaps = false; + + const scope = this; + + function updateVideo() { + + scope.needsUpdate = true; + video.requestVideoFrameCallback( updateVideo ); + + } + + if ( 'requestVideoFrameCallback' in video ) { + + video.requestVideoFrameCallback( updateVideo ); + + } + + } + + clone() { + + return new this.constructor( this.image ).copy( this ); + + } + + update() { + + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; + + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + + this.needsUpdate = true; + + } + + } + +} + +class FramebufferTexture extends Texture { + + constructor( width, height, format ) { + + super( { width, height } ); + + this.isFramebufferTexture = true; + + this.format = format; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.generateMipmaps = false; + + this.needsUpdate = true; + + } + +} + +class CompressedTexture extends Texture { + + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCompressedTexture = true; + + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; + + // 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; + + } + +} + +class CompressedArrayTexture extends CompressedTexture { + + constructor( mipmaps, width, height, depth, format, type ) { + + super( mipmaps, width, height, format, type ); + + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + + } + +} + +class CanvasTexture extends Texture { + + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isCanvasTexture = true; + + this.needsUpdate = true; + + } + +} + +/** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ + +class Curve { + + constructor() { + + this.type = 'Curve'; + + this.arcLengthDivisions = 200; + + } + + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + + getPoint( /* t, optionalTarget */ ) { + + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; + + } + + // Get point at relative position in curve according to arc length + // - u [0 .. 1] + + getPointAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); + + } + + // Get sequence of points using getPoint( t ) + + getPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPoint( d / divisions ) ); + + } + + return points; + + } + + // Get sequence of points using getPointAt( u ) + + getSpacedPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); + + } + + return points; + + } + + // Get total curve arc length + + getLength() { + + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; + + } + + // Get list of cumulative segment lengths + + getLengths( divisions = this.arcLengthDivisions ) { + + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; + + } + + this.needsUpdate = false; + + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; + + cache.push( 0 ); + + for ( let 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() { + + this.needsUpdate = true; + this.getLengths(); + + } + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + getUtoTmapping( u, distance ) { + + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if ( distance ) { + + targetArcLength = distance; + + } else { + + targetArcLength = u * arcLengths[ il - 1 ]; + + } + + // binary search for the index with largest value smaller than target u distance + + let 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; + + if ( arcLengths[ i ] === targetArcLength ) { + + return i / ( il - 1 ); + + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + + // add that fractional amount to t + + const 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( t, optionalTarget ) { + + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + + // Capping in case of danger + + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); + + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); + + return tangent; + + } + + getTangentAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); + + } + + computeFrenetFrames( segments, closed ) { + + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + + const normal = new Vector3(); + + const tangents = []; + const normals = []; + const binormals = []; + + const vec = new Vector3(); + const mat = new Matrix4(); + + // compute the tangent vectors for each segment on the curve + + for ( let i = 0; i <= segments; i ++ ) { + + const u = i / segments; + + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + + } + + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component + + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); + + if ( tx <= min ) { + + min = tx; + normal.set( 1, 0, 0 ); + + } + + if ( ty <= min ) { + + min = ty; + normal.set( 0, 1, 0 ); + + } + + if ( tz <= min ) { + + normal.set( 0, 0, 1 ); + + } + + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + + + // compute the slowly-varying normal and binormal vectors for each segment on the curve + + for ( let i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( let i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + } + + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; + + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + + return data; + + } + + fromJSON( json ) { + + this.arcLengthDivisions = json.arcLengthDivisions; + + return this; + + } + +} + +class EllipseCurve extends Curve { + + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + + super(); + + this.isEllipseCurve = true; + + this.type = 'EllipseCurve'; + + this.aX = aX; + this.aY = aY; + + this.xRadius = xRadius; + this.yRadius = yRadius; + + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + + this.aClockwise = aClockwise; + + this.aRotation = aRotation; + + } + + getPoint( t, optionalTarget ) { + + const point = optionalTarget || new Vector2(); + + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + + if ( deltaAngle < Number.EPSILON ) { + + if ( samePoints ) { + + deltaAngle = 0; + + } else { + + deltaAngle = twoPi; + + } + + } + + if ( this.aClockwise === true && ! samePoints ) { + + if ( deltaAngle === twoPi ) { + + deltaAngle = - twoPi; + + } else { + + deltaAngle = deltaAngle - twoPi; + + } + + } + + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); + + if ( this.aRotation !== 0 ) { + + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); + + const tx = x - this.aX; + const 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 point.set( x, y ); + + } + + copy( source ) { + + super.copy( source ); + + this.aX = source.aX; + this.aY = source.aY; + + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + + this.aClockwise = source.aClockwise; + + this.aRotation = source.aRotation; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.aX = this.aX; + data.aY = this.aY; + + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + + data.aClockwise = this.aClockwise; + + data.aRotation = this.aRotation; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.aX = json.aX; + this.aY = json.aY; + + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + + this.aClockwise = json.aClockwise; + + this.aRotation = json.aRotation; + + return this; + + } + +} + +class ArcCurve extends EllipseCurve { + + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + this.isArcCurve = true; + + this.type = 'ArcCurve'; + + } + +} + +/** + * 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 + */ + + +/* +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. +*/ + +function CubicPoly() { + + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * 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. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + + } + + return { + + initCatmullRom: function ( x0, x1, x2, x3, tension ) { + + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + + }, + + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; + + init( x1, x2, t1, t2 ); + + }, + + calc: function ( t ) { + + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + + } + + }; + +} + +// + +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); + +class CatmullRomCurve3 extends Curve { + + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + + super(); + + this.isCatmullRomCurve3 = true; + + this.type = 'CatmullRomCurve3'; + + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const points = this.points; + const l = points.length; + + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; + + if ( this.closed ) { + + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + + } else if ( weight === 0 && intPoint === l - 1 ) { + + intPoint = l - 2; + weight = 1; + + } + + let p0, p3; // 4 points (p1 & p2 defined below) + + if ( this.closed || intPoint > 0 ) { + + p0 = points[ ( intPoint - 1 ) % l ]; + + } else { + + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; + + } + + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; + + if ( this.closed || intPoint + 2 < l ) { + + p3 = points[ ( intPoint + 2 ) % l ]; + + } else { + + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; + + } + + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; + + 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.curveType === 'catmullrom' ) { + + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + + } + + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); + + } + + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + + return this; + + } + +} + +/** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ + +function CatmullRom( t, p0, p1, p2, p3 ) { + + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + +} + +// + +function QuadraticBezierP0( t, p ) { + + const k = 1 - t; + return k * k * p; + +} + +function QuadraticBezierP1( t, p ) { + + return 2 * ( 1 - t ) * t * p; + +} + +function QuadraticBezierP2( t, p ) { + + return t * t * p; + +} + +function QuadraticBezier( t, p0, p1, p2 ) { + + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); + +} + +// + +function CubicBezierP0( t, p ) { + + const k = 1 - t; + return k * k * k * p; + +} + +function CubicBezierP1( t, p ) { + + const k = 1 - t; + return 3 * k * k * t * p; + +} + +function CubicBezierP2( t, p ) { + + return 3 * ( 1 - t ) * t * t * p; + +} + +function CubicBezierP3( t, p ) { + + return t * t * t * p; + +} + +function CubicBezier( t, p0, p1, p2, p3 ) { + + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); + +} + +class CubicBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + + super(); + + this.isCubicBezierCurve = true; + + this.type = 'CubicBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class CubicBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + + super(); + + this.isCubicBezierCurve3 = true; + + this.type = 'CubicBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class LineCurve extends Curve { + + constructor( v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isLineCurve = true; + + this.type = 'LineCurve'; + + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget ) { + + const tangent = optionalTarget || new Vector2(); + + tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + + return tangent; + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class LineCurve3 extends Curve { + + constructor( v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isLineCurve3 = true; + + this.type = 'LineCurve3'; + + this.v1 = v1; + this.v2 = v2; + + } + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isQuadraticBezierCurve = true; + + this.type = 'QuadraticBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isQuadraticBezierCurve3 = true; + + this.type = 'QuadraticBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class SplineCurve extends Curve { + + constructor( points = [] ) { + + super(); + + this.isSplineCurve = true; + + this.type = 'SplineCurve'; + + this.points = points; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const points = this.points; + const p = ( points.length - 1 ) * t; + + const intPoint = Math.floor( p ); + const weight = p - intPoint; + + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); + + } + + return this; + + } + +} + +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); + +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ + +class CurvePath extends Curve { + + constructor() { + + super(); + + this.type = 'CurvePath'; + + this.curves = []; + this.autoClose = false; // Automatically closes the path + + } + + add( curve ) { + + this.curves.push( curve ); + + } + + closePath() { + + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + + if ( ! startPoint.equals( endPoint ) ) { + + this.curves.push( new LineCurve( endPoint, startPoint ) ); + + } + + } + + // 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( t, optionalTarget ) { + + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + + // To think about boundaries points. + + while ( i < curveLengths.length ) { + + if ( curveLengths[ i ] >= d ) { + + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; + + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt( u, optionalTarget ); + + } + + 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; + + } + + copy( source ) { + + super.copy( source ); + + this.curves = []; + + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + + const curve = source.curves[ i ]; + + this.curves.push( curve.clone() ); + + } + + this.autoClose = source.autoClose; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.autoClose = this.autoClose; + data.curves = []; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.autoClose = json.autoClose; + this.curves = []; + + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + + } + + return this; + + } + +} + +class Path extends CurvePath { + + constructor( points ) { + + super(); + + this.type = 'Path'; + + this.currentPoint = new Vector2(); + + if ( points ) { + + this.setFromPoints( points ); + + } + + } + + setFromPoints( points ) { + + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } + + return this; + + } + + moveTo( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + return this; + + } + + lineTo( x, y ) { + + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + const 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 ); + + return this; + + } + + splineThru( pts /*Array of Vector*/ ) { + + const npts = [ this.currentPoint.clone() ].concat( pts ); + + const curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + return this; + + } + + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + return this; + + } + + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const 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 + const firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; + + } + + copy( source ) { + + super.copy( source ); + + this.currentPoint.copy( source.currentPoint ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; + + } + +} + +class LatheGeometry extends BufferGeometry { + + constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + + super(); + + this.type = 'LatheGeometry'; + + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + segments = Math.floor( segments ); + + // clamp phiLength so it's in range of [ 0, 2PI ] + + phiLength = clamp( phiLength, 0, Math.PI * 2 ); + + // buffers + + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + + // helper variables + + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + + // pre-compute normals for initial "meridian" + + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + + switch ( j ) { + + case 0: // special handling for 1st vertex on path + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + prevNormal.copy( normal ); + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + break; + + case ( points.length - 1 ): // special handling for last Vertex on path + + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); + + break; + + default: // default handling for all vertices in between + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + curNormal.copy( normal ); + + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + prevNormal.copy( curNormal ); + + } + + } + + // generate vertices, uvs and normals + + for ( let i = 0; i <= segments; i ++ ) { + + const phi = phiStart + i * inverseSegments * phiLength; + + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); + + for ( let 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.push( vertex.x, vertex.y, vertex.z ); + + // uv + + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + + uvs.push( uv.x, uv.y ); + + // normal + + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; + + normals.push( x, y, z ); + + } + + } + + // indices + + for ( let i = 0; i < segments; i ++ ) { + + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + + const base = j + i * points.length; + + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + + // faces + + indices.push( a, b, d ); + indices.push( c, d, b ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + + } + + static fromJSON( data ) { + + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); + + } + +} + +class CapsuleGeometry extends LatheGeometry { + + constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { + + const path = new Path(); + path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); + path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); + + super( path.getPoints( capSegments ), radialSegments ); + + this.type = 'CapsuleGeometry'; + + this.parameters = { + radius: radius, + height: length, + capSegments: capSegments, + radialSegments: radialSegments, + }; + + } + + static fromJSON( data ) { + + return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments ); + + } + +} + +class CircleGeometry extends BufferGeometry { + + constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CircleGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + segments = Math.max( 3, segments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + const segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( let i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); + + } + +} + +class CylinderGeometry extends BufferGeometry { + + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CylinderGeometry'; + + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + const scope = this; + + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + + // generate geometry + + generateTorso(); + + if ( openEnded === false ) { + + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generateTorso() { + + const normal = new Vector3(); + const vertex = new Vector3(); + + let groupCount = 0; + + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; + + // generate vertices, normals and uvs + + for ( let y = 0; y <= heightSegments; y ++ ) { + + const indexRow = []; + + const v = y / heightSegments; + + // calculate the radius of the current row + + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + + const theta = u * thetaLength + thetaStart; + + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, 1 - v ); + + // save index of vertex in respective row + + indexRow.push( index ++ ); + + } + + // now save vertices of the row in our index array + + indexArray.push( indexRow ); + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + for ( let y = 0; y < heightSegments; y ++ ) { + + // we use the index array to access the correct indices + + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // update group counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, 0 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + function generateCap( top ) { + + // save the index of the first center vertex + const centerIndexStart = index; + + const uv = new Vector2(); + const vertex = new Vector3(); + + let groupCount = 0; + + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : - 1; + + // 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 + + for ( let x = 1; x <= radialSegments; x ++ ) { + + // vertex + + vertices.push( 0, halfHeight * sign, 0 ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uvs.push( 0.5, 0.5 ); + + // increase index + + index ++; + + } + + // save the index of the last center vertex + const centerIndexEnd = index; + + // now we generate the surrounding vertices, normals and uvs + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); + + // increase index + + index ++; + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + + if ( top === true ) { + + // face top + + indices.push( i, i + 1, c ); + + } else { + + // face bottom + + indices.push( i + 1, i, c ); + + } + + groupCount += 3; + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + } + + static fromJSON( data ) { + + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +class ConeGeometry extends CylinderGeometry { + + constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super( 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 + }; + + } + + static fromJSON( data ) { + + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +class PolyhedronGeometry extends BufferGeometry { + + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { + + super(); + + this.type = 'PolyhedronGeometry'; + + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; + + // default buffer data + + const vertexBuffer = []; + const uvBuffer = []; + + // the subdivision creates the vertex buffer data + + subdivide( detail ); + + // all vertices should lie on a conceptual sphere with a given radius + + applyRadius( radius ); + + // finally, create the uv data + + generateUVs(); + + // build non-indexed geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + + if ( detail === 0 ) { + + this.computeVertexNormals(); // flat normals + + } else { + + this.normalizeNormals(); // smooth normals + + } + + // helper functions + + function subdivide( detail ) { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + // iterate over all faces and apply a subdivision with the given detail value + + for ( let i = 0; i < indices.length; i += 3 ) { + + // get the vertices of the face + + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); + + // perform subdivision + + subdivideFace( a, b, c, detail ); + + } + + } + + function subdivideFace( a, b, c, detail ) { + + const cols = detail + 1; + + // we use this multidimensional array as a data structure for creating the subdivision + + const v = []; + + // construct all of the vertices for this subdivision + + for ( let i = 0; i <= cols; i ++ ) { + + v[ i ] = []; + + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); + + const rows = cols - i; + + for ( let j = 0; j <= rows; j ++ ) { + + if ( j === 0 && i === cols ) { + + v[ i ][ j ] = aj; + + } else { + + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + + } + + } + + } + + // construct all of the faces + + for ( let i = 0; i < cols; i ++ ) { + + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + + const k = Math.floor( j / 2 ); + + if ( j % 2 === 0 ) { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); + + } else { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + + } + + } + + } + + } + + function applyRadius( radius ) { + + const vertex = new Vector3(); + + // iterate over the entire buffer and apply the radius to each vertex + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + vertex.normalize().multiplyScalar( radius ); + + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; + + } + + } + + function generateUVs() { + + const vertex = new Vector3(); + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); + + } + + correctUVs(); + + correctSeam(); + + } + + function correctSeam() { + + // handle case when face straddles the seam, see #3269 + + for ( let i = 0; i < uvBuffer.length; i += 6 ) { + + // uv data of a single face + + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; + + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); + + // 0.9 is somewhat arbitrary + + if ( max > 0.9 && min < 0.1 ) { + + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + + } + + } + + } + + function pushVertex( vertex ) { + + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + + } + + function getVertexByIndex( index, vertex ) { + + const stride = index * 3; + + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; + + } + + function correctUVs() { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + const centroid = new Vector3(); + + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { + + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + + const azi = azimuth( centroid ); + + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); + + } + + } + + function correctUV( uv, stride, vector, azimuth ) { + + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + + uvBuffer[ stride ] = uv.x - 1; + + } + + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + + } + + } + + // Angle around the Y axis, counter-clockwise when looking from above. + + function azimuth( vector ) { + + return Math.atan2( vector.z, - vector.x ); + + } + + + // Angle above the XZ plane. + + function inclination( vector ) { + + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + + } + + } + + static fromJSON( data ) { + + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details ); + + } + +} + +class DodecahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'DodecahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new DodecahedronGeometry( data.radius, data.detail ); + + } + +} + +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); + +class EdgesGeometry extends BufferGeometry { + + constructor( geometry = null, thresholdAngle = 1 ) { + + super(); + + this.type = 'EdgesGeometry'; + + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; + + if ( geometry !== null ) { + + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); + + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); + + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { + + if ( indexAttr ) { + + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); + + } else { + + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; + + } + + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); + + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + + continue; + + } + + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { + + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; + + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); + + } + + edgeData[ reverseHash ] = null; + + } else if ( ! ( hash in edgeData ) ) { + + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { + + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), + + }; + + } + + } + + } + + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { + + if ( edgeData[ key ] ) { + + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); + + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); + + } + + } + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + +} + +class Shape extends Path { + + constructor( points ) { + + super( points ); + + this.uuid = generateUUID(); + + this.type = 'Shape'; + + this.holes = []; + + } + + getPointsHoles( divisions ) { + + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + + } + + return holesPts; + + } + + // get points of shape and holes (keypoints based on segments parameter) + + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; + + } + + copy( source ) { + + super.copy( source ); + + this.holes = []; + + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + + const hole = source.holes[ i ]; + + this.holes.push( hole.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.uuid = this.uuid; + data.holes = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.uuid = json.uuid; + this.holes = []; + + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); + + } + + return this; + + } + +} + +/** + * Port from https://github.com/mapbox/earcut (v2.2.4) + */ + +const Earcut = { + + triangulate: function ( data, holeIndices, dim = 2 ) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 32767 / invSize : 0; + + } + + earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 ); + + return triangles; + + } + +}; + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { + + let i, last; + + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } else { + + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } + + if ( last && equals( last, last.next ) ) { + + removeNode( last ); + last = last.next; + + } + + return last; + +} + +// eliminate colinear or duplicate points +function filterPoints( start, end ) { + + if ( ! start ) return start; + if ( ! end ) end = start; + + let p = start, + again; + do { + + again = false; + + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; + + } else { + + p = p.next; + + } + + } while ( again || p !== end ); + + return end; + +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + + if ( ! ear ) return; + + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + + let stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { + + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim | 0 ); + triangles.push( ear.i / dim | 0 ); + triangles.push( next.i / dim | 0 ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { + + // try filtering points and slicing again + if ( ! pass ) { + + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); + + // if this didn't work, try curing all small self-intersections locally + + } else if ( pass === 1 ) { + + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); + + // as a last resort, try splitting the remaining polygon into two + + } else if ( pass === 2 ) { + + splitEarcut( ear, triangles, dim, minX, minY, invSize ); + + } + + break; + + } + + } + +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + let p = c.next; + while ( p !== a ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; + + } + + return true; + +} + +function isEarHashed( ear, minX, minY, invSize ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + // z-order range for the current triangle bbox; + const minZ = zOrder( x0, y0, minX, minY, invSize ), + maxZ = zOrder( x1, y1, minX, minY, invSize ); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + } + + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + return true; + +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { + + let p = start; + do { + + const a = p.prev, + b = p.next.next; + + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + + triangles.push( a.i / dim | 0 ); + triangles.push( p.i / dim | 0 ); + triangles.push( b.i / dim | 0 ); + + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); + + p = start = b; + + } + + p = p.next; + + } while ( p !== start ); + + return filterPoints( p ); + +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + + let b = a.next.next; + while ( b !== a.prev ) { + + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); + + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); + + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize, 0 ); + earcutLinked( c, triangles, dim, minX, minY, invSize, 0 ); + return; + + } + + b = b.next; + + } + + a = a.next; + + } while ( a !== start ); + +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { + + const queue = []; + let i, len, start, end, list; + + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); + + } + + queue.sort( compareX ); + + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { + + outerNode = eliminateHole( queue[ i ], outerNode ); + + } + + return outerNode; + +} + +function compareX( a, b ) { + + return a.x - b.x; + +} + +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole( hole, outerNode ) { + + const bridge = findHoleBridge( hole, outerNode ); + if ( ! bridge ) { + + return outerNode; + + } + + const bridgeReverse = splitPolygon( bridge, hole ); + + // filter collinear points around the cuts + filterPoints( bridgeReverse, bridgeReverse.next ); + return filterPoints( bridge, bridge.next ); + +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { + + let p = outerNode, + qx = - Infinity, + m; + + const hx = hole.x, hy = hole.y; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { + + qx = x; + m = p.x < p.next.x ? p : p.next; + if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint + + } + + } + + p = p.next; + + } while ( p !== outerNode ); + + if ( ! m ) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; + + p = m; + + do { + + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + + m = p; + tanMin = tan; + + } + + } + + p = p.next; + + } while ( p !== stop ); + + return m; + +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { + + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + +} + +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { + + let p = start; + do { + + if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + + } while ( p !== start ); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked( p ); + +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { + + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + + p = list; + list = null; + tail = null; + numMerges = 0; + + while ( p ) { + + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { + + pSize ++; + q = q.nextZ; + if ( ! q ) break; + + } + + qSize = inSize; + + while ( pSize > 0 || ( qSize > 0 && q ) ) { + + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + + e = p; + p = p.nextZ; + pSize --; + + } else { + + e = q; + q = q.nextZ; + qSize --; + + } + + if ( tail ) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + + } + + p = q; + + } + + tail.nextZ = null; + inSize *= 2; + + } while ( numMerges > 1 ); + + return list; + +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { + + // coords are transformed into non-negative 15-bit integer range + x = ( x - minX ) * invSize | 0; + y = ( y - minY ) * invSize | 0; + + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; + + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; + + return x | ( y << 1 ); + +} + +// find the leftmost node of a polygon ring +function getLeftmost( start ) { + + let p = start, + leftmost = start; + do { + + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; + + } while ( p !== start ); + + return leftmost; + +} + +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + + return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) && + ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) && + ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py ); + +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { + + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + +} + +// signed area of a triangle +function area( p, q, r ) { + + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + +} + +// check if two points are equal +function equals( p1, p2 ) { + + return p1.x === p2.x && p1.y === p2.y; + +} + +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { + + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); + + if ( o1 !== o2 && o3 !== o4 ) return true; // general case + + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { + + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + +} + +function sign( num ) { + + return num > 0 ? 1 : num < 0 ? - 1 : 0; + +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { + + let p = a; + do { + + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; + + } while ( p !== a ); + + return false; + +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { + + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { + + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { + + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; + + } while ( p !== a ); + + return inside; + +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { + + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { + + const p = new Node( i, x, y ); + + if ( ! last ) { + + p.prev = p; + p.next = p; + + } else { + + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + + } + + return p; + +} + +function removeNode( p ) { + + p.next.prev = p.prev; + p.prev.next = p.next; + + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + +} + +function Node( i, x, y ) { + + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + +} + +function signedArea( data, start, end, dim ) { + + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { + + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; + + } + + return sum; + +} + +class ShapeUtils { + + // calculate area of the contour polygon + + static area( contour ) { + + const n = contour.length; + let a = 0.0; + + for ( let 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; + + } + + static isClockWise( pts ) { + + return ShapeUtils.area( pts ) < 0; + + } + + static triangulateShape( contour, holes ) { + + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + + removeDupEndPts( contour ); + addContour( vertices, contour ); + + // + + let holeIndex = contour.length; + + holes.forEach( removeDupEndPts ); + + for ( let i = 0; i < holes.length; i ++ ) { + + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); + + } + + // + + const triangles = Earcut.triangulate( vertices, holeIndices ); + + // + + for ( let i = 0; i < triangles.length; i += 3 ) { + + faces.push( triangles.slice( i, i + 3 ) ); + + } + + return faces; + + } + +} + +function removeDupEndPts( points ) { + + const l = points.length; + + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + + points.pop(); + + } + +} + +function addContour( vertices, contour ) { + + for ( let i = 0; i < contour.length; i ++ ) { + + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); + + } + +} + +/** + * 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 + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ + +class ExtrudeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { + + super(); + + this.type = 'ExtrudeGeometry'; + + this.parameters = { + shapes: shapes, + options: options + }; + + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + + const scope = this; + + const verticesArray = []; + const uvArray = []; + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + addShape( shape ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + this.computeVertexNormals(); + + // functions + + function addShape( shape ) { + + const placeholder = []; + + // options + + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + + const extrudePath = options.extrudePath; + + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + + // + + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + + if ( extrudePath ) { + + extrudePts = extrudePath.getSpacedPoints( steps ); + + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion + + // SETUP TNB variables + + // TODO1 - have a .isClosed in spline? + + splineTube = extrudePath.computeFrenetFrames( steps, false ); + + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } + + // Safeguards if bevels are not enabled + + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + + } + + // Variables initialization + + const shapePoints = shape.extractPoints( curveSegments ); + + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + + const reverse = ! ShapeUtils.isClockWise( vertices ); + + if ( reverse ) { + + vertices = vertices.reverse(); + + // Maybe we should also check if holes are in the opposite direction, just to be safe ... + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + if ( ShapeUtils.isClockWise( ahole ) ) { + + holes[ h ] = ahole.reverse(); + + } + + } + + } + + + const faces = ShapeUtils.triangulateShape( vertices, holes ); + + /* Vertices */ + + const contour = vertices; // vertices has all points but contour has only points of circumference + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + vertices = vertices.concat( ahole ); + + } + + + function scalePt2( pt, vec, size ) { + + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + + return vec.clone().multiplyScalar( size ).add( pt ); + + } + + const vlen = vertices.length, flen = faces.length; + + + // Find directions for point movement + + + 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. + + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html + + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; + + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + + // not collinear + + // length of vectors for normalizing + + const v_prev_len = Math.sqrt( v_prev_lensq ); + const 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 + + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + const 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 ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } + + } else { + + // handle special case of collinear edges + + let direction_eq = false; // assumes: opposite + + if ( v_prev_x > Number.EPSILON ) { + + if ( v_next_x > Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( v_prev_x < - Number.EPSILON ) { + + if ( v_next_x < - Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + + direction_eq = true; + + } + + } + + } + + 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 ); + + } 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 ); + + } + + } + + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + + } + + + const contourMovements = []; + + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) + + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + + } + + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + oneHoleMovements = []; + + for ( let 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; + + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + + } + + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); + + } + + + // Loop bevelSegments, 1 for the front, 1 for the back + + for ( let b = 0; b < bevelSegments; b ++ ) { + + //for ( b = bevelSegments; b > 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + } + + } + + const bs = bevelSize + bevelOffset; + + // Back facing vertices + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, 0 ); + + } else { + + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + // Add stepped vertices... + // Including front facing vertices + + for ( let s = 1; s <= steps; s ++ ) { + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth / steps * s ); + + } else { + + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + } + + + // Add bevel segments planes + + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } + + } + + /* Faces */ + + // Top and bottom faces + + buildLidFaces(); + + // Sides faces + + buildSideFaces(); + + + ///// Internal functions + + function buildLidFaces() { + + const start = verticesArray.length / 3; + + if ( bevelEnabled ) { + + let layer = 0; // steps + 1 + let offset = vlen * layer; + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + + } + + layer = steps + bevelSegments * 2; + offset = vlen * layer; + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + + } + + } else { + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + + } + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + + } + + } + + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; + + } + + + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + + + } + + function sidewalls( contour, layeroffset ) { + + let i = contour.length; + + while ( -- i >= 0 ) { + + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; + + //console.log('b', i,j, i-1, k,vertices.length); + + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); + + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } + + } + + } + + function v( x, y, z ) { + + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); + + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + + } + + function f4( a, b, c, d ) { + + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + const options = this.parameters.options; + + return toJSON$1( shapes, options, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + const extrudePath = data.options.extrudePath; + + if ( extrudePath !== undefined ) { + + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + + } + + return new ExtrudeGeometry( geometryShapes, data.options ); + + } + +} + +const WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + + }, + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { + + 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 ) + ]; + + } else { + + 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 ) + ]; + + } + + } + +}; + +function toJSON$1( shapes, options, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + data.options = Object.assign( {}, options ); + + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + + return data; + +} + +class IcosahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'IcosahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new IcosahedronGeometry( data.radius, data.detail ); + + } + +} + +class OctahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'OctahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new OctahedronGeometry( data.radius, data.detail ); + + } + +} + +class RingGeometry extends BufferGeometry { + + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'RingGeometry'; + + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // some helper variables + + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= phiSegments; j ++ ) { + + for ( let i = 0; i <= thetaSegments; i ++ ) { + + // values are generate from the inside of the ring to the outside + + const segment = thetaStart + i / thetaSegments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uv + + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // increase the radius for next row of vertices + + radius += radiusStep; + + } + + // indices + + for ( let j = 0; j < phiSegments; j ++ ) { + + const thetaSegmentLevel = j * ( thetaSegments + 1 ); + + for ( let i = 0; i < thetaSegments; i ++ ) { + + const segment = i + thetaSegmentLevel; + + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); + + } + +} + +class ShapeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) { + + super(); + + this.type = 'ShapeGeometry'; + + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let groupStart = 0; + let groupCount = 0; + + // allow single and array values for "shapes" parameter + + if ( Array.isArray( shapes ) === false ) { + + addShape( shapes ); + + } else { + + for ( let i = 0; i < shapes.length; i ++ ) { + + addShape( shapes[ i ] ); + + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + + groupStart += groupCount; + groupCount = 0; + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + + // helper functions + + function addShape( shape ) { + + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); + + let shapeVertices = points.shape; + const shapeHoles = points.holes; + + // check direction of vertices + + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + + shapeVertices = shapeVertices.reverse(); + + } + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + + shapeHoles[ i ] = shapeHole.reverse(); + + } + + } + + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + + // join vertices of inner and outer paths to a single array + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); + + } + + // vertices, normals, uvs + + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + + const vertex = shapeVertices[ i ]; + + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs + + } + + // indices + + for ( let i = 0, l = faces.length; i < l; i ++ ) { + + const face = faces[ i ]; + + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; + + indices.push( a, b, c ); + groupCount += 3; + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + return new ShapeGeometry( geometryShapes, data.curveSegments ); + + } + +} + +function toJSON( shapes, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + return data; + +} + +class SphereGeometry extends BufferGeometry { + + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + + super(); + + this.type = 'SphereGeometry'; + + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + + let index = 0; + const grid = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // generate vertices, normals and uvs + + for ( let iy = 0; iy <= heightSegments; iy ++ ) { + + const verticesRow = []; + + const v = iy / heightSegments; + + // special case for the poles + + let uOffset = 0; + + if ( iy == 0 && thetaStart == 0 ) { + + uOffset = 0.5 / widthSegments; + + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + + uOffset = - 0.5 / widthSegments; + + } + + for ( let ix = 0; ix <= widthSegments; ix ++ ) { + + const u = ix / widthSegments; + + // vertex + + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, 1 - v ); + + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); + + } + + // indices + + for ( let iy = 0; iy < heightSegments; iy ++ ) { + + for ( let ix = 0; ix < widthSegments; ix ++ ) { + + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); + + } + +} + +class TetrahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; + + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'TetrahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new TetrahedronGeometry( data.radius, data.detail ); + + } + +} + +class TorusGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) { + + super(); + + this.type = 'TorusGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; + + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= radialSegments; j ++ ) { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + + // 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= radialSegments; j ++ ) { + + for ( let i = 1; i <= tubularSegments; i ++ ) { + + // indices + + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); + + } + +} + +class TorusKnotGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + + super(); + + this.type = 'TorusKnotGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; + + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + + const P1 = new Vector3(); + const P2 = new Vector3(); + + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); + + // generate vertices, normals and uvs + + for ( let i = 0; i <= tubularSegments; ++ i ) { + + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment + + const u = i / tubularSegments * p * Math.PI * 2; + + // 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 ); + + // calculate orthonormal basis + + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); + + // normalize B, N. T can be ignored, we don't use it + + B.normalize(); + N.normalize(); + + for ( let j = 0; j <= radialSegments; ++ j ) { + + // 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. + + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); + + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve + + 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // 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.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + // indices + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // this function calculates the current position on the torus curve + + function calculatePositionOnCurve( u, p, q, radius, position ) { + + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const 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; + + } + + } + + static fromJSON( data ) { + + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); + + } + +} + +class TubeGeometry extends BufferGeometry { + + constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + + super(); + + this.type = 'TubeGeometry'; + + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; + + const frames = path.computeFrenetFrames( tubularSegments, closed ); + + // expose internals + + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + + // buffer + + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + + // create buffer data + + generateBufferData(); + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // functions + + function generateBufferData() { + + for ( let i = 0; i < tubularSegments; i ++ ) { + + generateSegment( i ); + + } + + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + + generateSegment( ( closed === false ) ? tubularSegments : 0 ); + + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries + + generateUVs(); + + // finally create faces + + generateIndices(); + + } + + function generateSegment( i ) { + + // we use getPointAt to sample evenly distributed points from the given path + + P = path.getPointAt( i / tubularSegments, P ); + + // retrieve corresponding normal and binormal + + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; + + // generate normals and vertices for the current segment + + for ( let j = 0; j <= radialSegments; j ++ ) { + + const v = j / radialSegments * Math.PI * 2; + + const sin = Math.sin( v ); + const cos = - Math.cos( v ); + + // normal + + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // vertex + + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + } + + } + + function generateIndices() { + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + } + + function generateUVs() { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + for ( let j = 0; j <= radialSegments; j ++ ) { + + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + + uvs.push( uv.x, uv.y ); + + } + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + data.path = this.parameters.path.toJSON(); + + return data; + + } + + static fromJSON( data ) { + + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + + } + +} + +class WireframeGeometry extends BufferGeometry { + + constructor( geometry = null ) { + + super(); + + this.type = 'WireframeGeometry'; + + this.parameters = { + geometry: geometry + }; + + if ( geometry !== null ) { + + // buffer + + const vertices = []; + const edges = new Set(); + + // helper variables + + const start = new Vector3(); + const end = new Vector3(); + + if ( geometry.index !== null ) { + + // indexed BufferGeometry + + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + + if ( groups.length === 0 ) { + + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + + } + + // create a data structure that contains all edges without duplicates + + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + + const group = groups[ o ]; + + const groupStart = group.start; + const groupCount = group.count; + + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { + + for ( let j = 0; j < 3; j ++ ) { + + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + } else { + + // non-indexed BufferGeometry + + const position = geometry.attributes.position; + + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + + for ( let j = 0; j < 3; j ++ ) { + + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + +} + +function isUniqueEdge( start, end, edges ) { + + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge + + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { + + return false; + + } else { + + edges.add( hash1 ); + edges.add( hash2 ); + return true; + + } + +} + +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry +}); + +class ShadowMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShadowMaterial = true; + + this.type = 'ShadowMaterial'; + + this.color = new Color( 0x000000 ); + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.fog = source.fog; + + return this; + + } + +} + +class RawShaderMaterial extends ShaderMaterial { + + constructor( parameters ) { + + super( parameters ); + + this.isRawShaderMaterial = true; + + this.type = 'RawShaderMaterial'; + + } + +} + +class MeshStandardMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshStandardMaterial = true; + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 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.0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + 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; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + + constructor( parameters ) { + + super(); + + this.isMeshPhysicalMaterial = true; + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.type = 'MeshPhysicalMaterial'; + + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; + + this.ior = 1.5; + + Object.defineProperty( this, 'reflectivity', { + get: function () { + + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); + + }, + set: function ( reflectivity ) { + + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); + + } + } ); + + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; + + this.transmissionMap = null; + + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color( 1, 1, 1 ); + + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; + + this._sheen = 0.0; + this._clearcoat = 0; + this._iridescence = 0; + this._transmission = 0; + + this.setValues( parameters ); + + } + + get sheen() { + + return this._sheen; + + } + + set sheen( value ) { + + if ( this._sheen > 0 !== value > 0 ) { + + this.version ++; + + } + + this._sheen = value; + + } + + get clearcoat() { + + return this._clearcoat; + + } + + set clearcoat( value ) { + + if ( this._clearcoat > 0 !== value > 0 ) { + + this.version ++; + + } + + this._clearcoat = value; + + } + + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + + get transmission() { + + return this._transmission; + + } + + set transmission( value ) { + + if ( this._transmission > 0 !== value > 0 ) { + + this.version ++; + + } + + this._transmission = value; + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.ior = source.ior; + + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); + + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; + + return this; + + } + +} + +class MeshPhongMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshPhongMaterial = true; + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshToonMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshToonMaterial = true; + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + this.gradientMap = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + this.gradientMap = source.gradientMap; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshNormalMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshNormalMaterial = true; + + this.type = 'MeshNormalMaterial'; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.flatShading = false; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + return this; + + } + +} + +class MeshLambertMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshLambertMaterial = true; + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshMatcapMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshMatcapMaterial = true; + + this.defines = { 'MATCAP': '' }; + + this.type = 'MeshMatcapMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.matcap = null; + + this.map = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.defines = { 'MATCAP': '' }; + + this.color.copy( source.color ); + + this.matcap = source.matcap; + + this.map = source.map; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class LineDashedMaterial extends LineBasicMaterial { + + constructor( parameters ) { + + super(); + + this.isLineDashedMaterial = true; + + this.type = 'LineDashedMaterial'; + + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + } + +} + +// same as Array.prototype.slice, but also works on typed arrays +function arraySlice( array, from, to ) { + + if ( isTypedArray( array ) ) { + + // in ios9 array.subarray(from, undefined) will return empty array + // but array.subarray(from) or array.subarray(from, len) is correct + return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + + } + + return array.slice( from, to ); + +} + +// converts an array to a specific type +function convertArray( array, type, forceClone ) { + + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; + + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + + return new type( array ); // create typed array + + } + + return Array.prototype.slice.call( array ); // create Array + +} + +function isTypedArray( object ) { + + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); + +} + +// returns an array by which times and values can be sorted +function getKeyframeOrder( times ) { + + function compareTime( i, j ) { + + return times[ i ] - times[ j ]; + + } + + const n = times.length; + const result = new Array( n ); + for ( let i = 0; i !== n; ++ i ) result[ i ] = i; + + result.sort( compareTime ); + + return result; + +} + +// uses the array previously returned by 'getKeyframeOrder' to sort data +function sortedArray( values, stride, order ) { + + const nValues = values.length; + const result = new values.constructor( nValues ); + + for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + + const srcOffset = order[ i ] * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + result[ dstOffset ++ ] = values[ srcOffset + j ]; + + } + + } + + return result; + +} + +// function for parsing AOS keyframe formats +function flattenJSON( jsonKeys, times, values, valuePropertyName ) { + + let i = 1, key = jsonKeys[ 0 ]; + + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + + key = jsonKeys[ i ++ ]; + + } + + if ( key === undefined ) return; // no data + + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data + + if ( Array.isArray( value ) ) { + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push.apply( values, value ); // push all elements + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else if ( value.toArray !== undefined ) { + + // ...assume THREE.Math-ish + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + value.toArray( values, values.length ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else { + + // otherwise push as-is + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push( value ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } + +} + +function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { + + const clip = sourceClip.clone(); + + clip.name = name; + + const tracks = []; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); + + const times = []; + const values = []; + + for ( let j = 0; j < track.times.length; ++ j ) { + + const frame = track.times[ j ] * fps; + + if ( frame < startFrame || frame >= endFrame ) continue; + + times.push( track.times[ j ] ); + + for ( let k = 0; k < valueSize; ++ k ) { + + values.push( track.values[ j * valueSize + k ] ); + + } + + } + + if ( times.length === 0 ) continue; + + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); + + } + + clip.tracks = tracks; + + // find minimum .times value across all tracks in the trimmed clip + + let minStartTime = Infinity; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + + minStartTime = clip.tracks[ i ].times[ 0 ]; + + } + + } + + // shift all tracks such that clip begins at t=0 + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + clip.tracks[ i ].shift( - 1 * minStartTime ); + + } + + clip.resetDuration(); + + return clip; + +} + +function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + + if ( fps <= 0 ) fps = 30; + + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { + + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; + + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { + + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; + + } ); + + if ( targetTrack === undefined ) continue; + + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + referenceOffset = referenceValueSize / 3; + + } + + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + targetOffset = targetValueSize / 3; + + } + + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { + + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else { + + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex ); + + } + + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { + + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); + + } + + // Subtract the reference value from all of the track values + + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { + + const valueStart = j * targetValueSize + targetOffset; + + if ( referenceTrackType === 'quaternion' ) { + + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + + } else { + + const valueEnd = targetValueSize - targetOffset * 2; + + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { + + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + + } + + } + + } + + } + + targetClip.blendMode = AdditiveAnimationBlendMode; + + return targetClip; + +} + +var AnimationUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arraySlice: arraySlice, + convertArray: convertArray, + flattenJSON: flattenJSON, + getKeyframeOrder: getKeyframeOrder, + isTypedArray: isTypedArray, + makeClipAdditive: makeClipAdditive, + sortedArray: sortedArray, + subclip: subclip +}); + +/** + * 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 + * + */ + +class Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + + this.settings = null; + this.DefaultSettings_ = {}; + + } + + evaluate( t ) { + + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; + + validate_interval: { + + seek: { + + let right; + + linear_scan: { + + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { + + for ( let giveUpAt = i1 + 2; ; ) { + + if ( t1 === undefined ) { + + if ( t < t0 ) break forward_scan; + + // after end + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t0 = t1; + t1 = pp[ ++ i1 ]; + + if ( t < t1 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // 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? + + const t1global = pp[ 1 ]; + + if ( t < t1global ) { + + i1 = 2; // + 1, using the scan for the details + t0 = t1global; + + } + + // linear reverse scan + + for ( let giveUpAt = i1 - 2; ; ) { + + if ( t0 === undefined ) { + + // before start + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t1 = t0; + t0 = pp[ -- i1 - 1 ]; + + if ( t >= t0 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; + + } + + // the interval is valid + + break validate_interval; + + } // linear scan + + // binary search + + while ( i1 < right ) { + + const mid = ( i1 + right ) >>> 1; + + if ( t < pp[ mid ] ) { + + right = mid; + + } else { + + i1 = mid + 1; + + } + + } + + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; + + // check boundary cases, again + + if ( t0 === undefined ) { + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( t1 === undefined ) { + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + } // seek + + this._cachedIndex = i1; + + this.intervalChanged_( i1, t0, t1 ); + + } // validate_interval + + return this.interpolate_( i1, t0, t, t1 ); + + } + + getSettings_() { + + return this.settings || this.DefaultSettings_; + + } + + copySampleValue_( index ) { + + // copies a sample value to the result buffer + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = values[ offset + i ]; + + } + + return result; + + } + + // Template methods for derived classes: + + interpolate_( /* i1, t0, t, t1 */ ) { + + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer + + } + + intervalChanged_( /* i1, t0, t1 */ ) { + + // empty + + } + +} + +/** + * 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. + */ + +class CubicInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; + + this.DefaultSettings_ = { + + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + + }; + + } + + intervalChanged_( i1, t0, t1 ) { + + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, + + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; + + if ( tPrev === undefined ) { + + switch ( this.getSettings_().endingStart ) { + + case ZeroSlopeEnding: + + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; + + } + + } + + if ( tNext === undefined ) { + + switch ( this.getSettings_().endingEnd ) { + + case ZeroSlopeEnding: + + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; + + } + + } + + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; + + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + + } + + interpolate_( i1, t0, t, t1 ) { + + const 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; + + // evaluate polynomials + + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + + // combine data linearly + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; + + } + + return result; + + } + +} + +class LinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + offset1 = i1 * stride, + offset0 = offset1 - stride, + + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; + + } + + return result; + + } + +} + +/** + * + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + */ + +class DiscreteInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1 /*, t0, t, t1 */ ) { + + return this.copySampleValue_( i1 - 1 ); + + } + +} + +class KeyframeTrack { + + constructor( name, times, values, interpolation ) { + + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + + this.name = name; + + this.times = convertArray( times, this.TimeBufferType ); + this.values = convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + } + + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): + + static toJSON( track ) { + + const trackType = track.constructor; + + let json; + + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { + + json = trackType.toJSON( track ); + + } else { + + // by default, we assume the data can be serialized as-is + json = { + + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) + + }; + + const interpolation = track.getInterpolation(); + + if ( interpolation !== track.DefaultInterpolation ) { + + json.interpolation = interpolation; + + } + + } + + json.type = track.ValueTypeName; // mandatory + + return json; + + } + + InterpolantFactoryMethodDiscrete( result ) { + + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodLinear( result ) { + + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + setInterpolation( interpolation ) { + + let factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + } + + if ( factoryMethod === undefined ) { + + const 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( 'THREE.KeyframeTrack:', message ); + return this; + + } + + this.createInterpolant = factoryMethod; + + return this; + + } + + getInterpolation() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + } + + } + + getValueSize() { + + return this.values.length / this.times.length; + + } + + // move all keyframes either forwards or backwards in time + shift( timeOffset ) { + + if ( timeOffset !== 0.0 ) { + + const times = this.times; + + for ( let 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( timeScale ) { + + if ( timeScale !== 1.0 ) { + + const times = this.times; + + for ( let 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( startTime, endTime ) { + + const times = this.times, + nKeys = times.length; + + let 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; + + } + + const stride = this.getValueSize(); + this.times = arraySlice( times, from, to ); + this.values = 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() { + + let valid = true; + + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; + + } + + const times = this.times, + values = this.values, + + nKeys = times.length; + + if ( nKeys === 0 ) { + + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; + + } + + let prevTime = null; + + for ( let i = 0; i !== nKeys; i ++ ) { + + const currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; + + } + + if ( prevTime !== null && prevTime > currTime ) { + + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( isTypedArray( values ) ) { + + for ( let i = 0, n = values.length; i !== n; ++ i ) { + + const value = values[ i ]; + + if ( isNaN( value ) ) { + + console.error( 'THREE.KeyframeTrack: 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() { + + // times or values may be shared with other tracks, so overwriting is unsafe + const times = arraySlice( this.times ), + values = arraySlice( this.values ), + stride = this.getValueSize(), + + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + + lastIndex = times.length - 1; + + let writeIndex = 1; + + for ( let i = 1; i < lastIndex; ++ i ) { + + let keep = false; + + const time = times[ i ]; + const timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + + if ( ! smoothInterpolation ) { + + // remove unnecessary keyframes same as their neighbors + + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( let j = 0; j !== stride; ++ j ) { + + const value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } else { + + keep = true; + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + const readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + } + + ++ writeIndex; + + } + + } + + // flush last keyframe (compaction looks ahead) + + if ( lastIndex > 0 ) { + + times[ writeIndex ] = times[ lastIndex ]; + + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + ++ writeIndex; + + } + + if ( writeIndex !== times.length ) { + + this.times = arraySlice( times, 0, writeIndex ); + this.values = arraySlice( values, 0, writeIndex * stride ); + + } else { + + this.times = times; + this.values = values; + + } + + return this; + + } + + clone() { + + const times = arraySlice( this.times, 0 ); + const values = arraySlice( this.values, 0 ); + + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); + + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; + + return track; + + } + +} + +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +/** + * A Track of Boolean keyframe values. + */ +class BooleanKeyframeTrack extends KeyframeTrack {} + +BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track of keyframe values that represent color. + */ +class ColorKeyframeTrack extends KeyframeTrack {} + +ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + +/** + * A Track of numeric keyframe values. + */ +class NumberKeyframeTrack extends KeyframeTrack {} + +NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + +/** + * Spherical linear unit quaternion interpolant. + */ + +class QuaternionLinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + alpha = ( t - t0 ) / ( t1 - t0 ); + + let offset = i1 * stride; + + for ( let end = offset + stride; offset !== end; offset += 4 ) { + + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); + + } + + return result; + + } + +} + +/** + * A Track of quaternion keyframe values. + */ +class QuaternionKeyframeTrack extends KeyframeTrack { + + InterpolantFactoryMethodLinear( result ) { + + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + +} + +QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; +// ValueBufferType is inherited +QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track that interpolates Strings + */ +class StringKeyframeTrack extends KeyframeTrack {} + +StringKeyframeTrack.prototype.ValueTypeName = 'string'; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track of vectored keyframe values. + */ +class VectorKeyframeTrack extends KeyframeTrack {} + +VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + +class AnimationClip { + + constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { + + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + + this.uuid = generateUUID(); + + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { + + this.resetDuration(); + + } + + } + + + static parse( json ) { + + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); + + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + + } + + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; + + return clip; + + } + + static toJSON( clip ) { + + const tracks = [], + clipTracks = clip.tracks; + + const json = { + + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode + + }; + + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + + } + + return json; + + } + + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + + for ( let i = 0; i < numMorphTargets; i ++ ) { + + let times = []; + let values = []; + + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); + + values.push( 0, 1, 0 ); + + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); + + // 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 ] ); + + } + + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + + } + + return new this( name, - 1, tracks ); + + } + + static findByName( objectOrClipArray, name ) { + + let clipArray = objectOrClipArray; + + if ( ! Array.isArray( objectOrClipArray ) ) { + + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + + } + + for ( let i = 0; i < clipArray.length; i ++ ) { + + if ( clipArray[ i ].name === name ) { + + return clipArray[ i ]; + + } + + } + + return null; + + } + + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + + const animationToMorphTargets = {}; + + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; + + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); + + if ( parts && parts.length > 1 ) { + + const name = parts[ 1 ]; + + let animationMorphTargets = animationToMorphTargets[ name ]; + + if ( ! animationMorphTargets ) { + + animationToMorphTargets[ name ] = animationMorphTargets = []; + + } + + animationMorphTargets.push( morphTarget ); + + } + + } + + const clips = []; + + for ( const name in animationToMorphTargets ) { + + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + + } + + return clips; + + } + + // parse the animation.hierarchy format + static parseAnimation( animation, bones ) { + + if ( ! animation ) { + + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; + + } + + const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { + + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { + + const times = []; + const values = []; + + flattenJSON( animationKeys, times, values, propertyName ); + + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { + + destTracks.push( new trackType( trackName, times, values ) ); + + } + + } + + }; + + const tracks = []; + + const clipName = animation.name || 'default'; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + + // automatic length determination in AnimationClip. + let duration = animation.length || - 1; + + const hierarchyTracks = animation.hierarchy || []; + + for ( let h = 0; h < hierarchyTracks.length; h ++ ) { + + const animationKeys = hierarchyTracks[ h ].keys; + + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; + + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { + + // figure out all morph targets used in this track + const morphTargetNames = {}; + + let k; + + for ( k = 0; k < animationKeys.length; k ++ ) { + + if ( animationKeys[ k ].morphTargets ) { + + for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + + } + + } + + } + + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( const morphTargetName in morphTargetNames ) { + + const times = []; + const values = []; + + for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { + + const animationKey = animationKeys[ k ]; + + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + + } + + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + + } + + duration = morphTargetNames.length * fps; + + } else { + + // ...assume skeletal animation + + const boneName = '.bones[' + bones[ h ].name + ']'; + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); + + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); + + } + + } + + if ( tracks.length === 0 ) { + + return null; + + } + + const clip = new this( clipName, duration, tracks, blendMode ); + + return clip; + + } + + resetDuration() { + + const tracks = this.tracks; + let duration = 0; + + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { + + const track = this.tracks[ i ]; + + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + + } + + this.duration = duration; + + return this; + + } + + trim() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].trim( 0, this.duration ); + + } + + return this; + + } + + validate() { + + let valid = true; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + valid = valid && this.tracks[ i ].validate(); + + } + + return valid; + + } + + optimize() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].optimize(); + + } + + return this; + + } + + clone() { + + const tracks = []; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + tracks.push( this.tracks[ i ].clone() ); + + } + + return new this.constructor( this.name, this.duration, tracks, this.blendMode ); + + } + + toJSON() { + + return this.constructor.toJSON( this ); + + } + +} + +function getTrackTypeForValueTypeName( typeName ) { + + switch ( typeName.toLowerCase() ) { + + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': + + return NumberKeyframeTrack; + + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': + + return VectorKeyframeTrack; + + case 'color': + + return ColorKeyframeTrack; + + case 'quaternion': + + return QuaternionKeyframeTrack; + + case 'bool': + case 'boolean': + + return BooleanKeyframeTrack; + + case 'string': + + return StringKeyframeTrack; + + } + + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); + +} + +function parseKeyframeTrack( json ) { + + if ( json.type === undefined ) { + + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + + } + + const trackType = getTrackTypeForValueTypeName( json.type ); + + if ( json.times === undefined ) { + + const times = [], values = []; + + 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 { + + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); + + } + +} + +const Cache = { + + enabled: false, + + files: {}, + + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + get: function ( key ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + clear: function () { + + this.files = {}; + + } + +}; + +class LoadingManager { + + constructor( onLoad, onProgress, onError ) { + + const scope = this; + + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor + + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } + + } + + isLoading = true; + + }; + + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); + + } + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + + } + + }; + + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + + } + + }; + + this.resolveURL = function ( url ) { + + if ( urlModifier ) { + + return urlModifier( url ); + + } + + return url; + + }; + + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + + return this; + + }; + + this.addHandler = function ( regex, loader ) { + + handlers.push( regex, loader ); + + return this; + + }; + + this.removeHandler = function ( regex ) { + + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); + + } + + return this; + + }; + + this.getHandler = function ( file ) { + + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; + + if ( regex.global ) regex.lastIndex = 0; // see #17920 + + if ( regex.test( file ) ) { + + return loader; + + } + + } + + return null; + + }; + + } + +} + +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +class Loader { + + constructor( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; + + } + + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.load( url, resolve, onProgress, reject ); + + } ); + + } + + parse( /* data */ ) {} + + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + setWithCredentials( value ) { + + this.withCredentials = value; + return this; + + } + + setPath( path ) { + + this.path = path; + return this; + + } + + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + setRequestHeader( requestHeader ) { + + this.requestHeader = requestHeader; + return this; + + } + +} + +const loading = {}; + +class HttpError extends Error { + + constructor( message, response ) { + + super( message ); + this.response = response; + + } + +} + +class FileLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + this.manager.itemStart( url ); + + setTimeout( () => { + + if ( onLoad ) onLoad( cached ); + + this.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + // Check if request is duplicate + + if ( loading[ url ] !== undefined ) { + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + return; + + } + + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, + } ); + + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + // An abort controller could be added within a future PR + } ); + + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; + + // start the fetch + fetch( req ) + .then( response => { + + if ( response.status === 200 || response.status === 0 ) { + + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. + + if ( response.status === 0 ) { + + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); + + } + + // Workaround: Checking if response.body === undefined for Alipay browser #23548 + + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { + + return response; + + } + + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + + // Nginx needs X-File-Size check + // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content + const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { + + readData(); + + function readData() { + + reader.read().then( ( { done, value } ) => { + + if ( done ) { + + controller.close(); + + } else { + + loaded += value.byteLength; + + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); + + } + + controller.enqueue( value ); + readData(); + + } + + } ); + + } + + } + + } ); + + return new Response( stream ); + + } else { + + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); + + } + + } ) + .then( response => { + + switch ( responseType ) { + + case 'arraybuffer': + + return response.arrayBuffer(); + + case 'blob': + + return response.blob(); + + case 'document': + + return response.text() + .then( text => { + + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); + + } ); + + case 'json': + + return response.json(); + + default: + + if ( mimeType === undefined ) { + + return response.text(); + + } else { + + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); + + } + + } + + } ) + .then( data => { + + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, data ); + + const callbacks = loading[ url ]; + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); + + } + + } ) + .catch( err => { + + // Abort errors and other errors are handled the same + + const callbacks = loading[ url ]; + + if ( callbacks === undefined ) { + + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; + + } + + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); + + } + + this.manager.itemError( url ); + + } ) + .finally( () => { + + this.manager.itemEnd( url ); + + } ); + + this.manager.itemStart( url ); + + } + + setResponseType( value ) { + + this.responseType = value; + return this; + + } + + setMimeType( value ) { + + this.mimeType = value; + return this; + + } + +} + +class AnimationLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const animations = []; + + for ( let i = 0; i < json.length; i ++ ) { + + const clip = AnimationClip.parse( json[ i ] ); + + animations.push( clip ); + + } + + return animations; + + } + +} + +/** + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + +class CompressedTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const images = []; + + const texture = new CompressedTexture(); + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( url[ i ], function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + + loaded += 1; + + if ( loaded === 6 ) { + + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; + + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, onProgress, onError ); + + } + + if ( Array.isArray( url ) ) { + + for ( let i = 0, il = url.length; i < il; ++ i ) { + + loadTexture( i ); + + } + + } else { + + // compressed cubemap texture stored in a single DDS file + + loader.load( url, function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + if ( texDatas.isCubemap ) { + + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + + for ( let f = 0; f < faces; f ++ ) { + + images[ f ] = { mipmaps: [] }; + + for ( let 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; + + } + + } + + texture.image = images; + + } else { + + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + + } + + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + }, onProgress, onError ); + + } + + return texture; + + } + +} + +class ImageLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const image = createElementNS( 'img' ); + + function onImageLoad() { + + removeEventListeners(); + + Cache.add( url, this ); + + if ( onLoad ) onLoad( this ); + + scope.manager.itemEnd( url ); + + } + + function onImageError( event ) { + + removeEventListeners(); + + if ( onError ) onError( event ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } + + function removeEventListeners() { + + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); + + } + + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); + + if ( url.slice( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + + } + + scope.manager.itemStart( url ); + + image.src = url; + + return image; + + } + +} + +class CubeTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( urls, onLoad, onProgress, onError ) { + + const texture = new CubeTexture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( urls[ i ], function ( image ) { + + texture.images[ i ] = image; + + loaded ++; + + if ( loaded === 6 ) { + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, undefined, onError ); + + } + + for ( let i = 0; i < urls.length; ++ i ) { + + loadTexture( i ); + + } + + return texture; + + } + +} + +/** + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + +class DataTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const texture = new DataTexture(); + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { + + const texData = scope.parse( buffer ); + + if ( ! texData ) return; + + if ( texData.image !== undefined ) { + + texture.image = texData.image; + + } else if ( texData.data !== undefined ) { + + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + + } + + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + + if ( texData.encoding !== undefined ) { + + texture.encoding = texData.encoding; + + } + + if ( texData.flipY !== undefined ) { + + texture.flipY = texData.flipY; + + } + + if ( texData.format !== undefined ) { + + texture.format = texData.format; + + } + + if ( texData.type !== undefined ) { + + texture.type = texData.type; + + } + + if ( texData.mipmaps !== undefined ) { + + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... + + } + + if ( texData.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + if ( texData.generateMipmaps !== undefined ) { + + texture.generateMipmaps = texData.generateMipmaps; + + } + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture, texData ); + + }, onProgress, onError ); + + + return texture; + + } + +} + +class TextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const texture = new Texture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + loader.load( url, function ( image ) { + + texture.image = image; + texture.needsUpdate = true; + + if ( onLoad !== undefined ) { + + onLoad( texture ); + + } + + }, onProgress, onError ); + + return texture; + + } + +} + +class Light extends Object3D { + + constructor( color, intensity = 1 ) { + + super(); + + this.isLight = true; + + this.type = 'Light'; + + this.color = new Color( color ); + this.intensity = intensity; + + } + + dispose() { + + // Empty here in base class; some subclasses override. + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.color.copy( source.color ); + this.intensity = source.intensity; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + + 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; + + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +class HemisphereLight extends Light { + + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.groundColor = new Color( groundColor ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; + + } + +} + +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); +const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + +class LightShadow { + + constructor( camera ) { + + this.camera = camera; + + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + + this.mapSize = new Vector2( 512, 512 ); + + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + + this.autoUpdate = true; + this.needsUpdate = false; + + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); + + this._viewportCount = 1; + + this._viewports = [ + + new Vector4( 0, 0, 1, 1 ) + + ]; + + } + + getViewportCount() { + + return this._viewportCount; + + } + + getFrustum() { + + return this._frustum; + + } + + updateMatrices( light ) { + + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); + + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); + + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + + 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( _projScreenMatrix$1 ); + + } + + getViewport( viewportIndex ) { + + return this._viewports[ viewportIndex ]; + + } + + getFrameExtents() { + + return this._frameExtents; + + } + + dispose() { + + if ( this.map ) { + + this.map.dispose(); + + } + + if ( this.mapPass ) { + + this.mapPass.dispose(); + + } + + } + + copy( source ) { + + this.camera = source.camera.clone(); + + this.bias = source.bias; + this.radius = source.radius; + + this.mapSize.copy( source.mapSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + toJSON() { + + const object = {}; + + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; + + return object; + + } + +} + +class SpotLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + + this.isSpotLightShadow = true; + + this.focus = 1; + + } + + updateMatrices( light ) { + + const camera = this.camera; + + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); + + } + + super.updateMatrices( light ); + + } + + copy( source ) { + + super.copy( source ); + + this.focus = source.focus; + + return this; + + } + +} + +class SpotLight extends Light { + + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) { + + super( color, intensity ); + + this.isSpotLight = true; + + this.type = 'SpotLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + + this.map = null; + + this.shadow = new SpotLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + + this.target = source.target.clone(); + + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +class PointLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + + this.isPointLightShadow = true; + + this._frameExtents = new Vector2( 4, 2 ); + + this._viewportCount = 6; + + this._viewports = [ + // 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 + + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; + + this._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 ) + ]; + + this._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 ) + ]; + + } + + updateMatrices( light, viewportIndex = 0 ) { + + const camera = this.camera; + const shadowMatrix = this.matrix; + + const far = light.distance || camera.far; + + if ( far !== camera.far ) { + + camera.far = far; + camera.updateProjectionMatrix(); + + } + + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); + + _lookTarget.copy( camera.position ); + _lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); + + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix ); + + } + +} + +class PointLight extends Light { + + constructor( color, intensity, distance = 0, decay = 2 ) { + + super( color, intensity ); + + this.isPointLight = true; + + this.type = 'PointLight'; + + this.distance = distance; + this.decay = decay; + + this.shadow = new PointLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.decay = source.decay; + + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +class DirectionalLightShadow extends LightShadow { + + constructor() { + + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + + this.isDirectionalLightShadow = true; + + } + +} + +class DirectionalLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isDirectionalLight = true; + + this.type = 'DirectionalLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.shadow = new DirectionalLightShadow(); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +class AmbientLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isAmbientLight = true; + + this.type = 'AmbientLight'; + + } + +} + +class RectAreaLight extends Light { + + constructor( color, intensity, width = 10, height = 10 ) { + + super( color, intensity ); + + this.isRectAreaLight = true; + + this.type = 'RectAreaLight'; + + this.width = width; + this.height = height; + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); + + } + + copy( source ) { + + super.copy( source ); + + this.width = source.width; + this.height = source.height; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.width = this.width; + data.object.height = this.height; + + return data; + + } + +} + +/** + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ + +// 3-band SH defined by 9 coefficients + +class SphericalHarmonics3 { + + constructor() { + + this.isSphericalHarmonics3 = true; + + this.coefficients = []; + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients.push( new Vector3() ); + + } + + } + + set( coefficients ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].copy( coefficients[ i ] ); + + } + + return this; + + } + + zero() { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].set( 0, 0, 0 ); + + } + + return this; + + } + + // get the radiance in the direction of the normal + // target is a Vector3 + getAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; + + } + + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + + return target; + + } + + add( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].add( sh.coefficients[ i ] ); + + } + + return this; + + } + + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + + } + + return this; + + } + + scale( s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; + + } + + lerp( sh, alpha ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + + } + + return this; + + } + + equals( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { + + return false; + + } + + } + + return true; + + } + + copy( sh ) { + + return this.set( sh.coefficients ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + fromArray( array, offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); + + } + + return array; + + } + + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt( normal, shBasis ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + // band 0 + shBasis[ 0 ] = 0.282095; + + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; + + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); + + } + +} + +class LightProbe extends Light { + + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + + super( undefined, intensity ); + + this.isLightProbe = true; + + this.sh = sh; + + } + + copy( source ) { + + super.copy( source ); + + this.sh.copy( source.sh ); + + return this; + + } + + fromJSON( json ) { + + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.sh = this.sh.toArray(); + + return data; + + } + +} + +class MaterialLoader extends Loader { + + constructor( manager ) { + + super( manager ); + this.textures = {}; + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const textures = this.textures; + + function getTexture( name ) { + + if ( textures[ name ] === undefined ) { + + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + + } + + return textures[ name ]; + + } + + const material = MaterialLoader.createMaterialFromType( json.type ); + + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = json.sheen; + if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) material.transmission = json.transmission; + if ( json.thickness !== undefined ) material.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor ); + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide; + 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.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; + + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + + if ( json.rotation !== undefined ) material.rotation = json.rotation; + + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; + + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; + + if ( json.dithering !== undefined ) material.dithering = json.dithering; + + if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha; + + if ( json.visible !== undefined ) material.visible = json.visible; + + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; + + if ( json.userData !== undefined ) material.userData = json.userData; + + if ( json.vertexColors !== undefined ) { + + if ( typeof json.vertexColors === 'number' ) { + + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; + + } else { + + material.vertexColors = json.vertexColors; + + } + + } + + // Shader Material + + if ( json.uniforms !== undefined ) { + + for ( const name in json.uniforms ) { + + const uniform = json.uniforms[ name ]; + + material.uniforms[ name ] = {}; + + switch ( uniform.type ) { + + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; + + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; + + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; + + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; + + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; + + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; + + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; + + default: + material.uniforms[ name ].value = uniform.value; + + } + + } + + } + + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; + + if ( json.extensions !== undefined ) { + + for ( const key in json.extensions ) { + + material.extensions[ key ] = json.extensions[ key ]; + + } + + } + + // 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 = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); + + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); + + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { + + let normalScale = json.normalScale; + + if ( Array.isArray( normalScale ) === false ) { + + // Blender exporter used to export a scalar. See #7459 + + normalScale = [ normalScale, normalScale ]; + + } + + material.normalScale = new Vector2().fromArray( normalScale ); + + } + + if ( json.displacementMap !== undefined ) material.displacementMap = 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 = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap ); + if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); + + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; + + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; + + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); + + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); + + if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap ); + if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap ); + + return material; + + } + + setTextures( value ) { + + this.textures = value; + return this; + + } + + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + + return new materialLib[ type ](); + + } + +} + +class LoaderUtils { + + static decodeText( array ) { + + if ( typeof TextDecoder !== 'undefined' ) { + + return new TextDecoder().decode( array ); + + } + + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. + + let s = ''; + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); + + } + + try { + + // merges multi-byte utf-8 characters. + + return decodeURIComponent( escape( s ) ); + + } catch ( e ) { // see #16358 + + return s; + + } + + } + + static extractUrlBase( url ) { + + const index = url.lastIndexOf( '/' ); + + if ( index === - 1 ) return './'; + + return url.slice( 0, index + 1 ); + + } + + static resolveURL( url, path ) { + + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; + + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); + + } + + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; + + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; + + } + +} + +class InstancedBufferGeometry extends BufferGeometry { + + constructor() { + + super(); + + this.isInstancedBufferGeometry = true; + + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; + + } + + copy( source ) { + + super.copy( source ); + + this.instanceCount = source.instanceCount; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.instanceCount = this.instanceCount; + + data.isInstancedBufferGeometry = true; + + return data; + + } + +} + +class BufferGeometryLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + + function getInterleavedBuffer( json, uuid ) { + + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; + + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; + + interleavedBufferMap[ uuid ] = ib; + + return ib; + + } + + function getArrayBuffer( json, uuid ) { + + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; + + const ab = new Uint32Array( arrayBuffer ).buffer; + + arrayBufferMap[ uuid ] = ab; + + return ab; + + } + + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + + const index = json.data.index; + + if ( index !== undefined ) { + + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + + } + + const attributes = json.data.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); + + if ( attribute.updateRange !== undefined ) { + + bufferAttribute.updateRange.offset = attribute.updateRange.offset; + bufferAttribute.updateRange.count = attribute.updateRange.count; + + } + + geometry.setAttribute( key, bufferAttribute ); + + } + + const morphAttributes = json.data.morphAttributes; + + if ( morphAttributes ) { + + for ( const key in morphAttributes ) { + + const attributeArray = morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); + + } + + geometry.morphAttributes[ key ] = array; + + } + + } + + const morphTargetsRelative = json.data.morphTargetsRelative; + + if ( morphTargetsRelative ) { + + geometry.morphTargetsRelative = true; + + } + + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + + if ( groups !== undefined ) { + + for ( let i = 0, n = groups.length; i !== n; ++ i ) { + + const group = groups[ i ]; + + geometry.addGroup( group.start, group.count, group.materialIndex ); + + } + + } + + const boundingSphere = json.data.boundingSphere; + + if ( boundingSphere !== undefined ) { + + const center = new Vector3(); + + if ( boundingSphere.center !== undefined ) { + + center.fromArray( boundingSphere.center ); + + } + + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + + } + + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; + + return geometry; + + } + +} + +class ObjectLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + let json = null; + + try { + + json = JSON.parse( text ); + + } catch ( error ) { + + if ( onError !== undefined ) onError( error ); + + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + + return; + + } + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) ); + + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; + + } + + scope.parse( json, onLoad ); + + }, onProgress, onError ); + + } + + async loadAsync( url, onProgress ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + + const text = await loader.loadAsync( url, onProgress ); + + const json = JSON.parse( text ); + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); + + } + + return await scope.parseAsync( json ); + + } + + parse( json, onLoad ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = this.parseImages( json.images, function () { + + if ( onLoad !== undefined ) onLoad( object ); + + } ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + // + + if ( onLoad !== undefined ) { + + let hasImages = false; + + for ( const uuid in images ) { + + if ( images[ uuid ].data instanceof HTMLImageElement ) { + + hasImages = true; + break; + + } + + } + + if ( hasImages === false ) onLoad( object ); + + } + + return object; + + } + + async parseAsync( json ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = await this.parseImagesAsync( json.images ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + return object; + + } + + parseShapes( json ) { + + const shapes = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const shape = new Shape().fromJSON( json[ i ] ); + + shapes[ shape.uuid ] = shape; + + } + + } + + return shapes; + + } + + parseSkeletons( json, object ) { + + const skeletons = {}; + const bones = {}; + + // generate bone lookup table + + object.traverse( function ( child ) { + + if ( child.isBone ) bones[ child.uuid ] = child; + + } ); + + // create skeletons + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + + skeletons[ skeleton.uuid ] = skeleton; + + } + + } + + return skeletons; + + } + + parseGeometries( json, shapes ) { + + const geometries = {}; + + if ( json !== undefined ) { + + const bufferGeometryLoader = new BufferGeometryLoader(); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + let geometry; + const data = json[ i ]; + + switch ( data.type ) { + + case 'BufferGeometry': + case 'InstancedBufferGeometry': + + geometry = bufferGeometryLoader.parse( data ); + break; + + default: + + if ( data.type in Geometries ) { + + geometry = Geometries[ data.type ].fromJSON( data, shapes ); + + } else { + + console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` ); + + } + + } + + geometry.uuid = data.uuid; + + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; + + geometries[ data.uuid ] = geometry; + + } + + } + + return geometries; + + } + + parseMaterials( json, textures ) { + + const cache = {}; // MultiMaterial + const materials = {}; + + if ( json !== undefined ) { + + const loader = new MaterialLoader(); + loader.setTextures( textures ); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( cache[ data.uuid ] === undefined ) { + + cache[ data.uuid ] = loader.parse( data ); + + } + + materials[ data.uuid ] = cache[ data.uuid ]; + + } + + } + + return materials; + + } + + parseAnimations( json ) { + + const animations = {}; + + if ( json !== undefined ) { + + for ( let i = 0; i < json.length; i ++ ) { + + const data = json[ i ]; + + const clip = AnimationClip.parse( data ); + + animations[ clip.uuid ] = clip; + + } + + } + + return animations; + + } + + parseImages( json, onLoad ) { + + const scope = this; + const images = {}; + + let loader; + + function loadImage( url ) { + + scope.manager.itemStart( url ); + + return loader.load( url, function () { + + scope.manager.itemEnd( url ); + + }, undefined, function () { + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + } + + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return loadImage( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + const manager = new LoadingManager( onLoad ); + + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + + } + + } + + } + + return images; + + } + + async parseImagesAsync( json ) { + + const scope = this; + const images = {}; + + let loader; + + async function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return await loader.loadAsync( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = await deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + } + + } + + } + + return images; + + } + + parseTextures( json, images ) { + + function parseConstant( value, type ) { + + if ( typeof value === 'number' ) return value; + + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; + + } + + const textures = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( data.image === undefined ) { + + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + + } + + if ( images[ data.image ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + + } + + const source = images[ data.image ]; + const image = source.data; + + let texture; + + if ( Array.isArray( image ) ) { + + texture = new CubeTexture(); + + if ( image.length === 6 ) texture.needsUpdate = true; + + } else { + + if ( image && image.data ) { + + texture = new DataTexture(); + + } else { + + texture = new Texture(); + + } + + if ( image ) texture.needsUpdate = true; // textures can have undefined image data + + } + + texture.source = source; + + texture.uuid = data.uuid; + + if ( data.name !== undefined ) texture.name = data.name; + + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; + + if ( data.wrap !== undefined ) { + + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + + } + + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; + + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + + if ( data.flipY !== undefined ) texture.flipY = data.flipY; + + if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps; + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + + if ( data.userData !== undefined ) texture.userData = data.userData; + + textures[ data.uuid ] = texture; + + } + + } + + return textures; + + } + + parseObject( data, geometries, materials, textures, animations ) { + + let object; + + function getGeometry( name ) { + + if ( geometries[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + + } + + return geometries[ name ]; + + } + + function getMaterial( name ) { + + if ( name === undefined ) return undefined; + + if ( Array.isArray( name ) ) { + + const array = []; + + for ( let i = 0, l = name.length; i < l; i ++ ) { + + const uuid = name[ i ]; + + if ( materials[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + + } + + array.push( materials[ uuid ] ); + + } + + return array; + + } + + if ( materials[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', name ); + + } + + return materials[ name ]; + + } + + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined texture', uuid ); + + } + + return textures[ uuid ]; + + } + + let geometry, material; + + switch ( data.type ) { + + case 'Scene': + + object = new Scene(); + + if ( data.background !== undefined ) { + + if ( Number.isInteger( data.background ) ) { + + object.background = new Color( data.background ); + + } else { + + object.background = getTexture( data.background ); + + } + + } + + if ( data.environment !== undefined ) { + + object.environment = getTexture( data.environment ); + + } + + if ( data.fog !== undefined ) { + + if ( data.fog.type === 'Fog' ) { + + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + + } else if ( data.fog.type === 'FogExp2' ) { + + object.fog = new FogExp2( data.fog.color, data.fog.density ); + + } + + } + + if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; + if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + + break; + + case 'PerspectiveCamera': + + 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 ); + + break; + + case 'OrthographicCamera': + + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + + break; + + case 'AmbientLight': + + object = new AmbientLight( data.color, data.intensity ); + + break; + + case 'DirectionalLight': + + object = new DirectionalLight( data.color, data.intensity ); + + break; + + case 'PointLight': + + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + + break; + + case 'RectAreaLight': + + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + + break; + + case 'SpotLight': + + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + + break; + + case 'HemisphereLight': + + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + + break; + + case 'LightProbe': + + object = new LightProbe().fromJSON( data ); + + break; + + case 'SkinnedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new SkinnedMesh( geometry, material ); + + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + + break; + + case 'Mesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new Mesh( geometry, material ); + + break; + + case 'InstancedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); + + break; + + case 'LOD': + + object = new LOD(); + + break; + + case 'Line': + + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineLoop': + + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineSegments': + + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'PointCloud': + case 'Points': + + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'Sprite': + + object = new Sprite( getMaterial( data.material ) ); + + break; + + case 'Group': + + object = new Group(); + + break; + + case 'Bone': + + object = new Bone(); + + break; + + default: + + object = new Object3D(); + + } + + object.uuid = data.uuid; + + if ( data.name !== undefined ) object.name = data.name; + + if ( data.matrix !== undefined ) { + + object.matrix.fromArray( data.matrix ); + + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.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.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + 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; + + if ( data.shadow ) { + + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + + } + + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; + + if ( data.children !== undefined ) { + + const children = data.children; + + for ( let i = 0; i < children.length; i ++ ) { + + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); + + } + + } + + if ( data.animations !== undefined ) { + + const objectAnimations = data.animations; + + for ( let i = 0; i < objectAnimations.length; i ++ ) { + + const uuid = objectAnimations[ i ]; + + object.animations.push( animations[ uuid ] ); + + } + + } + + if ( data.type === 'LOD' ) { + + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + + const levels = data.levels; + + for ( let l = 0; l < levels.length; l ++ ) { + + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); + + if ( child !== undefined ) { + + object.addLevel( child, level.distance, level.hysteresis ); + + } + + } + + } + + return object; + + } + + bindSkeletons( object, skeletons ) { + + if ( Object.keys( skeletons ).length === 0 ) return; + + object.traverse( function ( child ) { + + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + + const skeleton = skeletons[ child.skeleton ]; + + if ( skeleton === undefined ) { + + console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); + + } else { + + child.bind( skeleton, child.bindMatrix ); + + } + + } + + } ); + + } + +} + +const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping +}; + +const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; + +const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; + +class ImageBitmapLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + this.isImageBitmapLoader = true; + + if ( typeof createImageBitmap === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + + } + + if ( typeof fetch === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + + } + + this.options = { premultiplyAlpha: 'none' }; + + } + + setOptions( options ) { + + this.options = options; + + return this; + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; + + fetch( url, fetchOptions ).then( function ( res ) { + + return res.blob(); + + } ).then( function ( blob ) { + + return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); + + } ).then( function ( imageBitmap ) { + + Cache.add( url, imageBitmap ); + + if ( onLoad ) onLoad( imageBitmap ); + + scope.manager.itemEnd( url ); + + } ).catch( function ( e ) { + + if ( onError ) onError( e ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + scope.manager.itemStart( url ); + + } + +} + +let _context; + +class AudioContext { + + static getContext() { + + if ( _context === undefined ) { + + _context = new ( window.AudioContext || window.webkitAudioContext )(); + + } + + return _context; + + } + + static setContext( value ) { + + _context = value; + + } + +} + +class AudioLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { + + try { + + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); + + const context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { + + onLoad( audioBuffer ); + + } ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + +} + +class HemisphereLightProbe extends LightProbe { + + constructor( skyColor, groundColor, intensity = 1 ) { + + super( undefined, intensity ); + + this.isHemisphereLightProbe = true; + + const color1 = new Color().set( skyColor ); + const color2 = new Color().set( groundColor ); + + const sky = new Vector3( color1.r, color1.g, color1.b ); + const ground = new Vector3( color2.r, color2.g, color2.b ); + + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + const c0 = Math.sqrt( Math.PI ); + const c1 = c0 * Math.sqrt( 0.75 ); + + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + + } + +} + +class AmbientLightProbe extends LightProbe { + + constructor( color, intensity = 1 ) { + + super( undefined, intensity ); + + this.isAmbientLightProbe = true; + + const color1 = new Color().set( color ); + + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + + } + +} + +const _eyeRight = /*@__PURE__*/ new Matrix4(); +const _eyeLeft = /*@__PURE__*/ new Matrix4(); +const _projectionMatrix = /*@__PURE__*/ new Matrix4(); + +class StereoCamera { + + constructor() { + + this.type = 'StereoCamera'; + + this.aspect = 1; + + this.eyeSep = 0.064; + + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; + + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; + + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + + } + + update( camera ) { + + const cache = this._cache; + + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + + if ( needsUpdate ) { + + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ + + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; + + // translate xOffset + + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; + + // for left eye + + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraL.projectionMatrix.copy( _projectionMatrix ); + + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + + } + +} + +class Clock { + + constructor( autoStart = true ) { + + this.autoStart = autoStart; + + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + + this.running = false; + + } + + start() { + + this.startTime = now(); + + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + + } + + stop() { + + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + + } + + getElapsedTime() { + + this.getDelta(); + return this.elapsedTime; + + } + + getDelta() { + + let diff = 0; + + if ( this.autoStart && ! this.running ) { + + this.start(); + return 0; + + } + + if ( this.running ) { + + const newTime = now(); + + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; + + this.elapsedTime += diff; + + } + + return diff; + + } + +} + +function now() { + + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + +} + +const _position$1 = /*@__PURE__*/ new Vector3(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); +const _scale$1 = /*@__PURE__*/ new Vector3(); +const _orientation$1 = /*@__PURE__*/ new Vector3(); + +class AudioListener extends Object3D { + + constructor() { + + super(); + + this.type = 'AudioListener'; + + this.context = AudioContext.getContext(); + + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); + + this.filter = null; + + this.timeDelta = 0; + + // private + + this._clock = new Clock(); + + } + + getInput() { + + return this.gain; + + } + + removeFilter() { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; + + } + + return this; + + } + + getFilter() { + + return this.filter; + + } + + setFilter( value ) { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + + } else { + + this.gain.disconnect( this.context.destination ); + + } + + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); + + return this; + + } + + getMasterVolume() { + + return this.gain.gain.value; + + } + + setMasterVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + const listener = this.context.listener; + const up = this.up; + + this.timeDelta = this._clock.getDelta(); + + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); + + _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 ); + + if ( listener.positionX ) { + + // code path for Chrome (see #14393) + + const endTime = this.context.currentTime + this.timeDelta; + + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); + + } else { + + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z ); + + } + + } + +} + +class Audio extends Object3D { + + constructor( listener ) { + + super(); + + this.type = 'Audio'; + + this.listener = listener; + this.context = listener.context; + + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); + + this.autoplay = false; + + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = 'empty'; + + this._startedAt = 0; + this._progress = 0; + this._connected = false; + + this.filters = []; + + } + + getOutput() { + + return this.gain; + + } + + setNodeSource( audioNode ) { + + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; + + } + + setMediaElementSource( mediaElement ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); + + return this; + + } + + setMediaStreamSource( mediaStream ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); + + return this; + + } + + setBuffer( audioBuffer ) { + + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; + + } + + play( delay = 0 ) { + + if ( this.isPlaying === true ) { + + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; + + } + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._startedAt = this.context.currentTime + delay; + + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); + + this.isPlaying = true; + + this.source = source; + + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); + + return this.connect(); + + } + + pause() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + if ( this.isPlaying === true ) { + + // update current progress + + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + + if ( this.loop === true ) { + + // ensure _progress does not exceed duration with looped audios + + this._progress = this._progress % ( this.duration || this.buffer.duration ); + + } + + this.source.stop(); + this.source.onended = null; + + this.isPlaying = false; + + } + + return this; + + } + + stop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._progress = 0; + + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + + return this; + + } + + connect() { + + if ( this.filters.length > 0 ) { + + this.source.connect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].connect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + + } else { + + this.source.connect( this.getOutput() ); + + } + + this._connected = true; + + return this; + + } + + disconnect() { + + if ( this.filters.length > 0 ) { + + this.source.disconnect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + + } else { + + this.source.disconnect( this.getOutput() ); + + } + + this._connected = false; + + return this; + + } + + getFilters() { + + return this.filters; + + } + + setFilters( value ) { + + if ( ! value ) value = []; + + if ( this._connected === true ) { + + this.disconnect(); + this.filters = value.slice(); + this.connect(); + + } else { + + this.filters = value.slice(); + + } + + return this; + + } + + setDetune( value ) { + + this.detune = value; + + if ( this.source.detune === undefined ) return; // only set detune when available + + if ( this.isPlaying === true ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getDetune() { + + return this.detune; + + } + + getFilter() { + + return this.getFilters()[ 0 ]; + + } + + setFilter( filter ) { + + return this.setFilters( filter ? [ filter ] : [] ); + + } + + setPlaybackRate( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.playbackRate = value; + + if ( this.isPlaying === true ) { + + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getPlaybackRate() { + + return this.playbackRate; + + } + + onEnded() { + + this.isPlaying = false; + + } + + getLoop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; + + } + + return this.loop; + + } + + setLoop( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.loop = value; + + if ( this.isPlaying === true ) { + + this.source.loop = this.loop; + + } + + return this; + + } + + setLoopStart( value ) { + + this.loopStart = value; + + return this; + + } + + setLoopEnd( value ) { + + this.loopEnd = value; + + return this; + + } + + getVolume() { + + return this.gain.gain.value; + + } + + setVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + +} + +const _position = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); +const _scale = /*@__PURE__*/ new Vector3(); +const _orientation = /*@__PURE__*/ new Vector3(); + +class PositionalAudio extends Audio { + + constructor( listener ) { + + super( listener ); + + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); + + } + + disconnect() { + + super.disconnect(); + + this.panner.disconnect( this.gain ); + + } + + getOutput() { + + return this.panner; + + } + + getRefDistance() { + + return this.panner.refDistance; + + } + + setRefDistance( value ) { + + this.panner.refDistance = value; + + return this; + + } + + getRolloffFactor() { + + return this.panner.rolloffFactor; + + } + + setRolloffFactor( value ) { + + this.panner.rolloffFactor = value; + + return this; + + } + + getDistanceModel() { + + return this.panner.distanceModel; + + } + + setDistanceModel( value ) { + + this.panner.distanceModel = value; + + return this; + + } + + getMaxDistance() { + + return this.panner.maxDistance; + + } + + setMaxDistance( value ) { + + this.panner.maxDistance = value; + + return this; + + } + + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + + this.matrixWorld.decompose( _position, _quaternion, _scale ); + + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); + + const panner = this.panner; + + if ( panner.positionX ) { + + // code path for Chrome and Firefox (see #14393) + + const endTime = this.context.currentTime + this.listener.timeDelta; + + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); + + } else { + + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); + + } + + } + +} + +class AudioAnalyser { + + constructor( audio, fftSize = 2048 ) { + + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); + + } + + + getFrequencyData() { + + this.analyser.getByteFrequencyData( this.data ); + + return this.data; + + } + + getAverageFrequency() { + + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; + + } + + return value / data.length; + + } + +} + +class PropertyMixer { + + constructor( binding, typeName, valueSize ) { + + this.binding = binding; + this.valueSize = valueSize; + + let mixFunction, + mixFunctionAdditive, + setIdentity; + + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // 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 + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results + + switch ( typeName ) { + + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; + + case 'string': + case 'bool': + mixFunction = this._select; + + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; + + setIdentity = this._setAdditiveIdentityOther; + + this.buffer = new Array( valueSize * 5 ); + break; + + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + + this.buffer = new Float64Array( valueSize * 5 ); + + } + + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + this.useCount = 0; + this.referenceCount = 0; + + } + + // accumulate data in the 'incoming' region into 'accu' + accumulate( 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 + + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; + + let currentWeight = this.cumulativeWeight; + + if ( currentWeight === 0 ) { + + // accuN := incoming * weight + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ offset + i ] = buffer[ i ]; + + } + + currentWeight = weight; + + } else { + + // accuN := accuN + incoming * weight + + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); + + } + + this.cumulativeWeight = currentWeight; + + } + + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive( weight ) { + + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; + + if ( this.cumulativeWeightAdditive === 0 ) { + + // add = identity + + this._setIdentity(); + + } + + // add := add + incoming * weight + + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; + + } + + // apply the state of 'accu' to the binding when accus differ + apply( accuIndex ) { + + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, + + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, + + binding = this.binding; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + if ( weight < 1 ) { + + // accuN := accuN + original * ( 1 - cumulativeWeight ) + + const originalValueOffset = stride * this._origIndex; + + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); + + } + + if ( weightAdditive > 0 ) { + + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + + } + + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + + if ( buffer[ i ] !== buffer[ i + stride ] ) { + + // value has changed -> update scene graph + + binding.setValue( buffer, offset ); + break; + + } + + } + + } + + // remember the state of the bound property and copy it to both accus + saveOriginalState() { + + const binding = this.binding; + + const buffer = this.buffer, + stride = this.valueSize, + + originalValueOffset = stride * this._origIndex; + + binding.getValue( buffer, originalValueOffset ); + + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + + } + + // Add to identity for additive + this._setIdentity(); + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + } + + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { + + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); + + } + + _setAdditiveIdentityNumeric() { + + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + + for ( let i = startIndex; i < endIndex; i ++ ) { + + this.buffer[ i ] = 0; + + } + + } + + _setAdditiveIdentityQuaternion() { + + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + + } + + _setAdditiveIdentityOther() { + + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + + for ( let i = 0; i < this.valueSize; i ++ ) { + + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + + } + + } + + + // mix functions + + _select( buffer, dstOffset, srcOffset, t, stride ) { + + if ( t >= 0.5 ) { + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } + + } + + } + + _slerp( buffer, dstOffset, srcOffset, t ) { + + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + + } + + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + const workOffset = this._workIndex * stride; + + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + + } + + _lerp( buffer, dstOffset, srcOffset, t, stride ) { + + const s = 1 - t; + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + + } + + } + + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + + } + + } + +} + +// Characters [].:/ are reserved for track binding syntax. +const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + +const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); + +const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; + +class Composite { + + constructor( targetGroup, path, optionalParsedPath ) { + + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); + + } + + getValue( array, offset ) { + + this.bind(); // bind all binding + + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); + + } + + setValue( array, offset ) { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].setValue( array, offset ); + + } + + } + + bind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].bind(); + + } + + } + + unbind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].unbind(); + + } + + } + +} + +// 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. +class PropertyBinding { + + constructor( rootNode, path, parsedPath ) { + + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + + this.rootNode = rootNode; + + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + + } + + + static create( root, path, parsedPath ) { + + if ( ! ( root && root.isAnimationObjectGroup ) ) { + + return new PropertyBinding( root, path, parsedPath ); + + } else { + + return new PropertyBinding.Composite( root, path, parsedPath ); + + } + + } + + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName( name ) { + + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + + } + + static parseTrackName( trackName ) { + + const matches = _trackRe.exec( trackName ); + + if ( matches === null ) { + + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + + } + + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; + + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + + if ( lastDot !== undefined && lastDot !== - 1 ) { + + const objectName = results.nodeName.substring( lastDot + 1 ); + + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; + + } + + } + + if ( results.propertyName === null || results.propertyName.length === 0 ) { + + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + + } + + return results; + + } + + static findNode( root, nodeName ) { + + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + + return root; + + } + + // search into skeleton bones. + if ( root.skeleton ) { + + const bone = root.skeleton.getBoneByName( nodeName ); + + if ( bone !== undefined ) { + + return bone; + + } + + } + + // search into node subtree. + if ( root.children ) { + + const searchNodeSubtree = function ( children ) { + + for ( let i = 0; i < children.length; i ++ ) { + + const childNode = children[ i ]; + + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + + return childNode; + + } + + const result = searchNodeSubtree( childNode.children ); + + if ( result ) return result; + + } + + return null; + + }; + + const subTreeNode = searchNodeSubtree( root.children ); + + if ( subTreeNode ) { + + return subTreeNode; + + } + + } + + return null; + + } + + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} + + // Getters + + _getValue_direct( buffer, offset ) { + + buffer[ offset ] = this.targetObject[ this.propertyName ]; + + } + + _getValue_array( buffer, offset ) { + + const source = this.resolvedProperty; + + for ( let i = 0, n = source.length; i !== n; ++ i ) { + + buffer[ offset ++ ] = source[ i ]; + + } + + } + + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + + } + + _getValue_toArray( buffer, offset ) { + + this.resolvedProperty.toArray( buffer, offset ); + + } + + // Direct + + _setValue_direct( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + + } + + _setValue_direct_setNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // EntireArray + + _setValue_array( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + } + + _setValue_array_setNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.needsUpdate = true; + + } + + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // ArrayElement + + _setValue_arrayElement( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + + } + + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // HasToFromArray + + _setValue_fromArray( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + + } + + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; + + } + + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + _getValue_unbound( targetArray, offset ) { + + this.bind(); + this.getValue( targetArray, offset ); + + } + + _setValue_unbound( sourceArray, offset ) { + + this.bind(); + this.setValue( sourceArray, offset ); + + } + + // create getter / setter pair for a property in the scene graph + bind() { + + let targetObject = this.node; + const parsedPath = this.parsedPath; + + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + + if ( ! targetObject ) { + + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + + this.node = targetObject; + + } + + // 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 ) { + + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; + + } + + if ( objectName ) { + + let objectIndex = parsedPath.objectIndex; + + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { + + case 'materials': + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.materials ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; + + } + + targetObject = targetObject.material.materials; + + break; + + case 'bones': + + if ( ! targetObject.skeleton ) { + + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; + + } + + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. + + targetObject = targetObject.skeleton.bones; + + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { + + if ( targetObject[ i ].name === objectIndex ) { + + objectIndex = i; + break; + + } + + } + + break; + + case 'map': + + if ( 'map' in targetObject ) { + + targetObject = targetObject.map; + break; + + } + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.map ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; + + } + + targetObject = targetObject.material.map; + break; + + default: + + if ( targetObject[ objectName ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; + + } + + targetObject = targetObject[ objectName ]; + + } + + + if ( objectIndex !== undefined ) { + + if ( targetObject[ objectIndex ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; + + } + + targetObject = targetObject[ objectIndex ]; + + } + + } + + // resolve property + const nodeProperty = targetObject[ propertyName ]; + + if ( nodeProperty === undefined ) { + + const nodeName = parsedPath.nodeName; + + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; + + } + + // determine versioning scheme + let versioning = this.Versioning.None; + + this.targetObject = targetObject; + + if ( targetObject.needsUpdate !== undefined ) { // material + + versioning = this.Versioning.NeedsUpdate; + + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + + versioning = this.Versioning.MatrixWorldNeedsUpdate; + + } + + // determine how the property gets bound + let 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. + + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; + + } + + if ( ! targetObject.geometry.morphAttributes ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + + } + + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + + } + + } + + bindingType = this.BindingType.ArrayElement; + + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + + // must use copy for Object3D.Euler/Quaternion + + bindingType = this.BindingType.HasFromToArray; + + this.resolvedProperty = nodeProperty; + + } else if ( Array.isArray( nodeProperty ) ) { + + bindingType = this.BindingType.EntireArray; + + this.resolvedProperty = nodeProperty; + + } else { + + this.propertyName = propertyName; + + } + + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + + } + + unbind() { + + this.node = null; + + // 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; + + } + +} + +PropertyBinding.Composite = Composite; + +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; + +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; + +PropertyBinding.prototype.GetterByBindingType = [ + + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, + +]; + +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, + + ], [ + + // EntireArray + + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, + + ], [ + + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, + + ], [ + + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, + + ] + +]; + +/** + * + * 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. + */ + +class AnimationObjectGroup { + + constructor() { + + this.isAnimationObjectGroup = true; + + this.uuid = generateUUID(); + + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); + + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite + + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + indices[ arguments[ i ].uuid ] = 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 + + const scope = this; + + this.stats = { + + objects: { + get total() { + + return scope._objects.length; + + }, + get inUse() { + + return this.total - scope.nCachedObjects_; + + } + }, + get bindingsPerObject() { + + return scope._bindings.length; + + } + + }; + + } + + add() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; + + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; + + if ( index === undefined ) { + + // unknown object -> add it to the ACTIVE region + + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + + } + + } else if ( index < nCachedObjects ) { + + knownObject = objects[ index ]; + + // move existing object to the ACTIVE region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; + + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; + + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; + + let binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = lastCached; + + if ( binding === undefined ) { + + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist + + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + + } + + bindingsForPath[ firstActiveIndex ] = binding; + + } + + } else if ( objects[ index ] !== knownObject ) { + + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); + + } // else the object is already where we want it to be + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + remove() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined && index >= nCachedObjects ) { + + // move existing object into the CACHED region + + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; + + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; + + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; + + } + + } + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // remove & forget + uncache() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined ) { + + delete indicesByUUID[ uuid ]; + + if ( index < nCachedObjects ) { + + // object is cached, shrink the CACHED region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + // 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(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; + + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); + + } + + } else { + + // object is active, just swap with the last and pop + + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + if ( lastIndex > 0 ) { + + indicesByUUID[ lastObject.uuid ] = index; + + } + + objects[ index ] = lastObject; + objects.pop(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ]; + + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); + + } + + } // cached or active + + } // if object is known + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // Internal interface used by befriended PropertyBinding.Composite: + + subscribe_( path, parsedPath ) { + + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group + + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; + + if ( index !== undefined ) return bindings[ index ]; + + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); + + index = bindings.length; + + indicesByPath[ path ] = index; + + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); + + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + + } + + return bindingsForPath; + + } + + unsubscribe_( path ) { + + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' + + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; + + if ( index !== undefined ) { + + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; + + indicesByPath[ lastBindingsPath ] = index; + + bindings[ index ] = lastBindings; + bindings.pop(); + + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); + + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); + + } + + } + +} + +class AnimationAction { + + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); + + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + + for ( let i = 0; i !== nTracks; ++ i ) { + + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; + + } + + this._interpolantSettings = interpolantSettings; + + this._interpolants = interpolants; // bound by the mixer + + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); + + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager + + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + + this.loop = LoopRepeat; + this._loopCount = - 1; + + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; + + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; + + this.timeScale = 1; + this._effectiveTimeScale = 1; + + this.weight = 1; + this._effectiveWeight = 1; + + this.repetitions = Infinity; // no. of repetitions when looping + + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight + + this.clampWhenFinished = false;// keep feeding the last frame? + + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end + + } + + // State & Scheduling + + play() { + + this._mixer._activateAction( this ); + + return this; + + } + + stop() { + + this._mixer._deactivateAction( this ); + + return this.reset(); + + } + + reset() { + + 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(); + + } + + isRunning() { + + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); + + } + + // return true when play has been called + isScheduled() { + + return this._mixer._isActiveAction( this ); + + } + + startAt( time ) { + + this._startTime = time; + + return this; + + } + + setLoop( mode, repetitions ) { + + this.loop = mode; + this.repetitions = repetitions; + + return this; + + } + + // Weight + + // 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( weight ) { + + this.weight = weight; + + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; + + return this.stopFading(); + + } + + // return the weight considering fading and .enabled + getEffectiveWeight() { + + return this._effectiveWeight; + + } + + fadeIn( duration ) { + + return this._scheduleFading( duration, 0, 1 ); + + } + + fadeOut( duration ) { + + return this._scheduleFading( duration, 1, 0 ); + + } + + crossFadeFrom( fadeOutAction, duration, warp ) { + + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); + + if ( warp ) { + + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, + + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; + + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); + + } + + return this; + + } + + crossFadeTo( fadeInAction, duration, warp ) { + + return fadeInAction.crossFadeFrom( this, duration, warp ); + + } + + stopFading() { + + const weightInterpolant = this._weightInterpolant; + + if ( weightInterpolant !== null ) { + + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); + + } + + return this; + + } + + // Time Scale Control + + // set the time scale 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( timeScale ) { + + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + + return this.stopWarping(); + + } + + // return the time scale considering warping and .paused + getEffectiveTimeScale() { + + return this._effectiveTimeScale; + + } + + setDuration( duration ) { + + this.timeScale = this._clip.duration / duration; + + return this.stopWarping(); + + } + + syncWith( action ) { + + this.time = action.time; + this.timeScale = action.timeScale; + + return this.stopWarping(); + + } + + halt( duration ) { + + return this.warp( this._effectiveTimeScale, 0, duration ); + + } + + warp( startTimeScale, endTimeScale, duration ) { + + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; + + let interpolant = this._timeScaleInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + times[ 1 ] = now + duration; + + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; + + return this; + + } + + stopWarping() { + + const timeScaleInterpolant = this._timeScaleInterpolant; + + if ( timeScaleInterpolant !== null ) { + + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + + } + + return this; + + } + + // Object Accessors + + getMixer() { + + return this._mixer; + + } + + getClip() { + + return this._clip; + + } + + getRoot() { + + return this._localRoot || this._mixer._root; + + } + + // Interna + + _update( time, deltaTime, timeDirection, accuIndex ) { + + // called by the mixer + + if ( ! this.enabled ) { + + // call ._updateWeight() to update ._effectiveWeight + + this._updateWeight( time ); + return; + + } + + const startTime = this._startTime; + + if ( startTime !== null ) { + + // check for scheduled start of action + + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { + + deltaTime = 0; + + } else { + + + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; + + } + + } + + // apply time scale and advance time + + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); + + // note: _updateTime may disable the action resulting in + // an effective weight of 0 + + const weight = this._updateWeight( time ); + + if ( weight > 0 ) { + + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + + switch ( this.blendMode ) { + + case AdditiveAnimationBlendMode: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); + + } + + break; + + case NormalAnimationBlendMode: + default: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); + + } + + } + + } + + } + + _updateWeight( time ) { + + let weight = 0; + + if ( this.enabled ) { + + weight = this.weight; + const interpolant = this._weightInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + weight *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopFading(); + + if ( interpolantValue === 0 ) { + + // faded out, disable + this.enabled = false; + + } + + } + + } + + } + + this._effectiveWeight = weight; + return weight; + + } + + _updateTimeScale( time ) { + + let timeScale = 0; + + if ( ! this.paused ) { + + timeScale = this.timeScale; + + const interpolant = this._timeScaleInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + timeScale *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopWarping(); + + if ( timeScale === 0 ) { + + // motion has halted, pause + this.paused = true; + + } else { + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + } + + } + + } + + this._effectiveTimeScale = timeScale; + return timeScale; + + } + + _updateTime( deltaTime ) { + + const duration = this._clip.duration; + const loop = this.loop; + + let time = this.time + deltaTime; + let loopCount = this._loopCount; + + const pingPong = ( loop === LoopPingPong ); + + if ( deltaTime === 0 ) { + + if ( loopCount === - 1 ) return time; + + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + + } + + if ( loop === LoopOnce ) { + + if ( loopCount === - 1 ) { + + // just started + + this._loopCount = 0; + this._setEndings( true, true, false ); + + } + + handle_stop: { + + if ( time >= duration ) { + + time = duration; + + } else if ( time < 0 ) { + + time = 0; + + } else { + + this.time = time; + + break handle_stop; + + } + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); + + } + + } else { // repetitive Repeat or PingPong + + if ( loopCount === - 1 ) { + + // just started + + if ( deltaTime >= 0 ) { + + loopCount = 0; + + this._setEndings( true, this.repetitions === 0, pingPong ); + + } else { + + // 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 ( time >= duration || time < 0 ) { + + // wrap around + + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; + + loopCount += Math.abs( loopDelta ); + + const pending = this.repetitions - loopCount; + + if ( pending <= 0 ) { + + // have to stop (switch state, clamp time, fire event) + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + time = deltaTime > 0 ? duration : 0; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); + + } else { + + // keep running + + if ( pending === 1 ) { + + // entering the last round + + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); + + } else { + + this._setEndings( false, false, pingPong ); + + } + + this._loopCount = loopCount; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); + + } + + } else { + + this.time = time; + + } + + if ( pingPong && ( loopCount & 1 ) === 1 ) { + + // invert time for the "pong round" + + return duration - time; + + } + + } + + return time; + + } + + _setEndings( atStart, atEnd, pingPong ) { + + const settings = this._interpolantSettings; + + if ( pingPong ) { + + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + + } else { + + // assuming for LoopOnce atStart == atEnd == true + + if ( atStart ) { + + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingStart = WrapAroundEnding; + + } + + if ( atEnd ) { + + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingEnd = WrapAroundEnding; + + } + + } + + } + + _scheduleFading( duration, weightNow, weightThen ) { + + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; + + return this; + + } + +} + +const _controlInterpolantsResultBuffer = new Float32Array( 1 ); + + +class AnimationMixer extends EventDispatcher { + + constructor( root ) { + + super(); + + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1.0; + + } + + _bindAction( action, prototypeAction ) { + + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; + + let bindingsByName = bindingsByRoot[ rootUuid ]; + + if ( bindingsByName === undefined ) { + + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; + + } + + for ( let i = 0; i !== nTracks; ++ i ) { + + const track = tracks[ i ], + trackName = track.name; + + let binding = bindingsByName[ trackName ]; + + if ( binding !== undefined ) { + + ++ binding.referenceCount; + bindings[ i ] = binding; + + } else { + + binding = bindings[ i ]; + + if ( binding !== undefined ) { + + // existing binding, make sure the cache knows + + if ( binding._cacheIndex === null ) { + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + } + + continue; + + } + + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; + + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + bindings[ i ] = binding; + + } + + interpolants[ i ].resultBuffer = binding.buffer; + + } + + } + + _activateAction( action ) { + + if ( ! this._isActiveAction( action ) ) { + + if ( action._cacheIndex === null ) { + + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind + + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; + + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); + + this._addInactiveAction( action, clipUuid, rootUuid ); + + } + + const bindings = action._propertyBindings; + + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( binding.useCount ++ === 0 ) { + + this._lendBinding( binding ); + binding.saveOriginalState(); + + } + + } + + this._lendAction( action ); + + } + + } + + _deactivateAction( action ) { + + if ( this._isActiveAction( action ) ) { + + const bindings = action._propertyBindings; + + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.useCount === 0 ) { + + binding.restoreOriginalState(); + this._takeBackBinding( binding ); + + } + + } + + this._takeBackAction( action ); + + } + + } + + // Memory manager + + _initMemoryManager() { + + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; + + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } + + + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; + + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + + + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; + + const scope = this; + + this.stats = { + + 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; + + } + } + + }; + + } + + // Memory management for AnimationAction objects + + _isActiveAction( action ) { + + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + + } + + _addInactiveAction( action, clipUuid, rootUuid ) { + + const actions = this._actions, + actionsByClip = this._actionsByClip; + + let actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip === undefined ) { + + actionsForClip = { + + knownActions: [ action ], + actionByRoot: {} + + }; + + action._byClipCacheIndex = 0; + + actionsByClip[ clipUuid ] = actionsForClip; + + } else { + + const knownActions = actionsForClip.knownActions; + + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); + + } + + action._cacheIndex = actions.length; + actions.push( action ); + + actionsForClip.actionByRoot[ rootUuid ] = action; + + } + + _removeInactiveAction( action ) { + + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + action._cacheIndex = null; + + + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, + + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], + + byClipCacheIndex = action._byClipCacheIndex; + + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); + + action._byClipCacheIndex = null; + + + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; + + delete actionByRoot[ rootUuid ]; + + if ( knownActionsForClip.length === 0 ) { + + delete actionsByClip[ clipUuid ]; + + } + + this._removeInactiveBindingsForAction( action ); + + } + + _removeInactiveBindingsForAction( action ) { + + const bindings = action._propertyBindings; + + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.referenceCount === 0 ) { + + this._removeInactiveBinding( binding ); + + } + + } + + } + + _lendAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s + + const actions = this._actions, + prevIndex = action._cacheIndex, + + lastActiveIndex = this._nActiveActions ++, + + firstInactiveAction = actions[ lastActiveIndex ]; + + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; + + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; + + } + + _takeBackAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a + + const actions = this._actions, + prevIndex = action._cacheIndex, + + firstInactiveIndex = -- this._nActiveActions, + + lastActiveAction = actions[ firstInactiveIndex ]; + + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; + + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; + + } + + // Memory management for PropertyMixer objects + + _addInactiveBinding( binding, rootUuid, trackName ) { + + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; + + let bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName === undefined ) { + + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; + + } + + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); + + } + + _removeInactiveBinding( binding ) { + + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], + + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; + + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); + + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { + + delete bindingsByRoot[ rootUuid ]; + + } + + } + + _lendBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + lastActiveIndex = this._nActiveBindings ++, + + firstInactiveBinding = bindings[ lastActiveIndex ]; + + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; + + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; + + } + + _takeBackBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + firstInactiveIndex = -- this._nActiveBindings, + + lastActiveBinding = bindings[ firstInactiveIndex ]; + + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; + + } + + + // Memory management of Interpolants for weight and time scale + + _lendControlInterpolant() { + + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; + + let interpolant = interpolants[ lastActiveIndex ]; + + if ( interpolant === undefined ) { + + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); + + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; + + } + + return interpolant; + + } + + _takeBackControlInterpolant( interpolant ) { + + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, + + firstInactiveIndex = -- this._nActiveControlInterpolants, + + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; + + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; + + } + + // 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( clip, optionalRoot, blendMode ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid; + + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; + + if ( blendMode === undefined ) { + + if ( clipObject !== null ) { + + blendMode = clipObject.blendMode; + + } else { + + blendMode = NormalAnimationBlendMode; + + } + + } + + if ( actionsForClip !== undefined ) { + + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + + return existingAction; + + } + + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; + + // 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 + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); + + this._bindAction( newAction, prototypeAction ); + + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); + + return newAction; + + } + + // get an existing action + existingAction( clip, optionalRoot ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid, + + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, + + clipUuid = clipObject ? clipObject.uuid : clip, + + actionsForClip = this._actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + return actionsForClip.actionByRoot[ rootUuid ] || null; + + } + + return null; + + } + + // deactivates all previously scheduled actions + stopAllAction() { + + const actions = this._actions, + nActions = this._nActiveActions; + + for ( let i = nActions - 1; i >= 0; -- i ) { + + actions[ i ].stop(); + + } + + return this; + + } + + // advance the time and update apply the animation + update( deltaTime ) { + + deltaTime *= this.timeScale; + + const actions = this._actions, + nActions = this._nActiveActions, + + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), + + accuIndex = this._accuIndex ^= 1; + + // run active actions + + for ( let i = 0; i !== nActions; ++ i ) { + + const action = actions[ i ]; + + action._update( time, deltaTime, timeDirection, accuIndex ); + + } + + // update scene graph + + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { + + bindings[ i ].apply( accuIndex ); + + } + + return this; + + } + + // Allows you to seek to a specific time in an animation. + setTime( timeInSeconds ) { + + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { + + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. + + } + + // return this mixer's root target object + getRoot() { + + return this._root; + + } + + // free all resources specific to a particular clip + uncacheClip( clip ) { + + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away + + const actionsToRemove = actionsForClip.knownActions; + + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + + const action = actionsToRemove[ i ]; + + this._deactivateAction( action ); + + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; + + action._cacheIndex = null; + action._byClipCacheIndex = null; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + this._removeInactiveBindingsForAction( action ); + + } + + delete actionsByClip[ clipUuid ]; + + } + + } + + // free all resources specific to a particular root target object + uncacheRoot( root ) { + + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; + + for ( const clipUuid in actionsByClip ) { + + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; + + if ( action !== undefined ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName !== undefined ) { + + for ( const trackName in bindingByName ) { + + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); + + } + + } + + } + + // remove a targeted clip from the cache + uncacheAction( clip, optionalRoot ) { + + const action = this.existingAction( clip, optionalRoot ); + + if ( action !== null ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + +} + +class Uniform { + + constructor( value ) { + + this.value = value; + + } + + clone() { + + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + + } + +} + +let id = 0; + +class UniformsGroup extends EventDispatcher { + + constructor() { + + super(); + + this.isUniformsGroup = true; + + Object.defineProperty( this, 'id', { value: id ++ } ); + + this.name = ''; + + this.usage = StaticDrawUsage; + this.uniforms = []; + + } + + add( uniform ) { + + this.uniforms.push( uniform ); + + return this; + + } + + remove( uniform ) { + + const index = this.uniforms.indexOf( uniform ); + + if ( index !== - 1 ) this.uniforms.splice( index, 1 ); + + return this; + + } + + setName( name ) { + + this.name = name; + + return this; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.usage = source.usage; + + const uniformsSource = source.uniforms; + + this.uniforms.length = 0; + + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { + + this.uniforms.push( uniformsSource[ i ].clone() ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class InstancedInterleavedBuffer extends InterleavedBuffer { + + constructor( array, stride, meshPerAttribute = 1 ) { + + super( array, stride ); + + this.isInstancedInterleavedBuffer = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + clone( data ) { + + const ib = super.clone( data ); + + ib.meshPerAttribute = this.meshPerAttribute; + + return ib; + + } + + toJSON( data ) { + + const json = super.toJSON( data ); + + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + + return json; + + } + +} + +class GLBufferAttribute { + + constructor( buffer, type, itemSize, elementSize, count ) { + + this.isGLBufferAttribute = true; + + this.name = ''; + + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setBuffer( buffer ) { + + this.buffer = buffer; + + return this; + + } + + setType( type, elementSize ) { + + this.type = type; + this.elementSize = elementSize; + + return this; + + } + + setItemSize( itemSize ) { + + this.itemSize = itemSize; + + return this; + + } + + setCount( count ) { + + this.count = count; + + return this; + + } + +} + +class Raycaster { + + constructor( origin, direction, near = 0, far = Infinity ) { + + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) + + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } + + set( origin, direction ) { + + // direction is assumed to be normalized (for accurate distance calculations) + + this.ray.set( origin, direction ); + + } + + setFromCamera( coords, camera ) { + + if ( camera.isPerspectiveCamera ) { + + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; + + } else if ( camera.isOrthographicCamera ) { + + 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 ); + this.camera = camera; + + } else { + + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + + } + + } + + intersectObject( object, recursive = true, intersects = [] ) { + + intersectObject( object, this, intersects, recursive ); + + intersects.sort( ascSort ); + + return intersects; + + } + + intersectObjects( objects, recursive = true, intersects = [] ) { + + for ( let i = 0, l = objects.length; i < l; i ++ ) { + + intersectObject( objects[ i ], this, intersects, recursive ); + + } + + intersects.sort( ascSort ); + + return intersects; + + } + +} + +function ascSort( a, b ) { + + return a.distance - b.distance; + +} + +function intersectObject( object, raycaster, intersects, recursive ) { + + if ( object.layers.test( raycaster.layers ) ) { + + object.raycast( raycaster, intersects ); + + } + + if ( recursive === true ) { + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + intersectObject( children[ i ], raycaster, intersects, true ); + + } + + } + +} + +/** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ + +class Spherical { + + constructor( radius = 1, phi = 0, theta = 0 ) { + + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle + + return this; + + } + + set( radius, phi, theta ) { + + this.radius = radius; + this.phi = phi; + this.theta = theta; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + + return this; + + } + + // restrict phi to be between EPS and PI-EPS + makeSafe() { + + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + y * y + z * z ); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + */ + +class Cylindrical { + + constructor( radius = 1, theta = 0, y = 0 ) { + + this.radius = radius; // distance from the origin to a point in the x-z plane + this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = y; // height above the x-z plane + + return this; + + } + + set( radius, theta, y ) { + + this.radius = radius; + this.theta = theta; + this.y = y; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$4 = /*@__PURE__*/ new Vector2(); + +class Box2 { + + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + + this.isBox2 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + containsPoint( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; + + } + + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + + } + + intersectsBox( box ) { + + // using 4 splitting planes to rule out intersections + + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); + + } + + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + +} + +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); + +class Line3 { + + constructor( start = new Vector3(), end = new Vector3() ) { + + this.start = start; + this.end = end; + + } + + set( start, end ) { + + this.start.copy( start ); + this.end.copy( end ); + + return this; + + } + + copy( line ) { + + this.start.copy( line.start ); + this.end.copy( line.end ); + + return this; + + } + + getCenter( target ) { + + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + + } + + delta( target ) { + + return target.subVectors( this.end, this.start ); + + } + + distanceSq() { + + return this.start.distanceToSquared( this.end ); + + } + + distance() { + + return this.start.distanceTo( this.end ); + + } + + at( t, target ) { + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + closestPointToPointParameter( point, clampToLine ) { + + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); + + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); + + let t = startEnd_startP / startEnd2; + + if ( clampToLine ) { + + t = clamp( t, 0, 1 ); + + } + + return t; + + } + + closestPointToPoint( point, clampToLine, target ) { + + const t = this.closestPointToPointParameter( point, clampToLine ); + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + applyMatrix4( matrix ) { + + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); + + return this; + + } + + equals( line ) { + + return line.start.equals( this.start ) && line.end.equals( this.end ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$3 = /*@__PURE__*/ new Vector3(); + +class SpotLightHelper extends Object3D { + + constructor( light, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'SpotLightHelper'; + + const geometry = new BufferGeometry(); + + const 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 ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; + + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); + + this.update(); + + } + + dispose() { + + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); + + this.cone.scale.set( coneWidth, coneWidth, coneLength ); + + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); + + this.cone.lookAt( _vector$3 ); + + if ( this.color !== undefined ) { + + this.cone.material.color.set( this.color ); + + } else { + + this.cone.material.color.copy( this.light.color ); + + } + + } + +} + +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _boneMatrix = /*@__PURE__*/ new Matrix4(); +const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + + +class SkeletonHelper extends LineSegments { + + constructor( object ) { + + const bones = getBoneList( object ); + + const geometry = new BufferGeometry(); + + const vertices = []; + const colors = []; + + const color1 = new Color( 0, 0, 1 ); + const color2 = new Color( 0, 1, 0 ); + + for ( let i = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); + + } + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + + super( geometry, material ); + + this.isSkeletonHelper = true; + + this.type = 'SkeletonHelper'; + + this.root = object; + this.bones = bones; + + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + + } + + updateMatrixWorld( force ) { + + const bones = this.bones; + + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); + + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + + for ( let i = 0, j = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); + + j += 2; + + } + + } + + geometry.getAttribute( 'position' ).needsUpdate = true; + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function getBoneList( object ) { + + const boneList = []; + + if ( object.isBone === true ) { + + boneList.push( object ); + + } + + for ( let i = 0; i < object.children.length; i ++ ) { + + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + + } + + return boneList; + +} + +class PointLightHelper extends Mesh { + + constructor( light, sphereSize, color ) { + + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + + super( geometry, material ); + + this.light = light; + + this.color = color; + + this.type = 'PointLightHelper'; + + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + + this.update(); + + + /* + // TODO: delete this comment? + const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + + const d = light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.scale.set( d, d, d ); + + } + + this.add( this.lightDistance ); + */ + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ); + + } + + /* + const d = this.light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); + + } + */ + + } + +} + +const _vector$1 = /*@__PURE__*/ new Vector3(); +const _color1 = /*@__PURE__*/ new Color(); +const _color2 = /*@__PURE__*/ new Color(); + +class HemisphereLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'HemisphereLightHelper'; + + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); + + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; + + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); + + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + + this.add( new Mesh( geometry, this.material ) ); + + this.update(); + + } + + dispose() { + + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + + update() { + + const mesh = this.children[ 0 ]; + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + const colors = mesh.geometry.getAttribute( 'color' ); + + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); + + for ( let i = 0, l = colors.count; i < l; i ++ ) { + + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + + colors.setXYZ( i, color.r, color.g, color.b ); + + } + + colors.needsUpdate = true; + + } + + this.light.updateWorldMatrix( true, false ); + + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + + } + +} + +class GridHelper extends LineSegments { + + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + + const vertices = [], colors = []; + + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); + + const color = i === center ? color1 : color2; + + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'GridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class PolarGridHelper extends LineSegments { + + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const vertices = []; + const colors = []; + + // create the sectors + + if ( sectors > 1 ) { + + for ( let i = 0; i < sectors; i ++ ) { + + const v = ( i / sectors ) * ( Math.PI * 2 ); + + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; + + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); + + const color = ( i & 1 ) ? color1 : color2; + + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); + + } + + } + + // create the rings + + for ( let i = 0; i < rings; i ++ ) { + + const color = ( i & 1 ) ? color1 : color2; + + const r = radius - ( radius / rings * i ); + + for ( let j = 0; j < divisions; j ++ ) { + + // first vertex + + let v = ( j / divisions ) * ( Math.PI * 2 ); + + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + // second vertex + + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + } + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'PolarGridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +const _v1 = /*@__PURE__*/ new Vector3(); +const _v2 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); + +class DirectionalLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'DirectionalLightHelper'; + + if ( size === undefined ) size = 1; + + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); + + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); + + this.update(); + + } + + dispose() { + + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); + + this.lightPlane.lookAt( _v2 ); + + if ( this.color !== undefined ) { + + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); + + } else { + + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); + + } + + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); + + } + +} + +const _vector = /*@__PURE__*/ new Vector3(); +const _camera = /*@__PURE__*/ new Camera(); + +/** + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html + */ + +class CameraHelper extends LineSegments { + + constructor( camera ) { + + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + + const vertices = []; + const colors = []; + + const pointMap = {}; + + // near + + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); + + // far + + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); + + // sides + + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); + + // cone + + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); + + // up + + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); + + // target + + addLine( 'c', 't' ); + addLine( 'p', 'c' ); + + // cross + + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); + + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); + + function addLine( a, b ) { + + addPoint( a ); + addPoint( b ); + + } + + function addPoint( id ) { + + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + + if ( pointMap[ id ] === undefined ) { + + pointMap[ id ] = []; + + } + + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + super( geometry, material ); + + this.type = 'CameraHelper'; + + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + + this.pointMap = pointMap; + + this.update(); + + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + + } + + update() { + + const geometry = this.geometry; + const pointMap = this.pointMap; + + const w = 1, h = 1; + + // we need just camera projection matrix inverse + // world matrix must be identity + + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + + // center / target + + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + + // near + + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); + + // far + + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + + // up + + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + + // cross + + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + + geometry.getAttribute( 'position' ).needsUpdate = true; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function setPoint( point, pointMap, geometry, camera, x, y, z ) { + + _vector.set( x, y, z ).unproject( camera ); + + const points = pointMap[ point ]; + + if ( points !== undefined ) { + + const position = geometry.getAttribute( 'position' ); + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); + + } + + } + +} + +const _box = /*@__PURE__*/ new Box3(); + +class BoxHelper extends LineSegments { + + constructor( object, color = 0xffff00 ) { + + const 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 ] ); + const positions = new Float32Array( 8 * 3 ); + + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.object = object; + this.type = 'BoxHelper'; + + this.matrixAutoUpdate = false; + + this.update(); + + } + + update( object ) { + + if ( object !== undefined ) { + + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + + } + + if ( this.object !== undefined ) { + + _box.setFromObject( this.object ); + + } + + if ( _box.isEmpty() ) return; + + const min = _box.min; + const max = _box.max; + + /* + 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 + */ + + const position = this.geometry.attributes.position; + const 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; + + position.needsUpdate = true; + + this.geometry.computeBoundingSphere(); + + } + + setFromObject( object ) { + + this.object = object; + this.update(); + + return this; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.object = source.object; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class Box3Helper extends LineSegments { + + constructor( box, color = 0xffff00 ) { + + const 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 ] ); + + const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + + const geometry = new BufferGeometry(); + + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.box = box; + + this.type = 'Box3Helper'; + + this.geometry.computeBoundingSphere(); + + } + + updateMatrixWorld( force ) { + + const box = this.box; + + if ( box.isEmpty() ) return; + + box.getCenter( this.position ); + + box.getSize( this.scale ); + + this.scale.multiplyScalar( 0.5 ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class PlaneHelper extends Line { + + constructor( plane, size = 1, hex = 0xffff00 ) { + + const color = hex; + + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.type = 'PlaneHelper'; + + this.plane = plane; + + this.size = size; + + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; + + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + + } + + updateMatrixWorld( force ) { + + this.position.set( 0, 0, 0 ); + + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); + + this.lookAt( this.plane.normal ); + + this.translateZ( - this.plane.constant ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + +} + +const _axis = /*@__PURE__*/ new Vector3(); +let _lineGeometry, _coneGeometry; + +class ArrowHelper extends Object3D { + + // dir is assumed to be normalized + + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + super(); + + this.type = 'ArrowHelper'; + + if ( _lineGeometry === undefined ) { + + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + + _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); + + } + + this.position.copy( origin ); + + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); + + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); + + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); + + } + + setDirection( dir ) { + + // dir is assumed to be normalized + + if ( dir.y > 0.99999 ) { + + this.quaternion.set( 0, 0, 0, 1 ); + + } else if ( dir.y < - 0.99999 ) { + + this.quaternion.set( 1, 0, 0, 0 ); + + } else { + + _axis.set( dir.z, 0, - dir.x ).normalize(); + + const radians = Math.acos( dir.y ); + + this.quaternion.setFromAxisAngle( _axis, radians ); + + } + + } + + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); + + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); + + } + + setColor( color ) { + + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } + + copy( source ) { + + super.copy( source, false ); + + this.line.copy( source.line ); + this.cone.copy( source.cone ); + + return this; + + } + + dispose() { + + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + +} + +class AxesHelper extends LineSegments { + + constructor( size = 1 ) { + + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; + + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'AxesHelper'; + + } + + setColors( xAxisColor, yAxisColor, zAxisColor ) { + + const color = new Color(); + const array = this.geometry.attributes.color.array; + + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); + + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); + + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); + + this.geometry.attributes.color.needsUpdate = true; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class ShapePath { + + constructor() { + + this.type = 'ShapePath'; + + this.color = new Color(); + + this.subPaths = []; + this.currentPath = null; + + } + + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); + + return this; + + } + + lineTo( x, y ) { + + this.currentPath.lineTo( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + + return this; + + } + + splineThru( pts ) { + + this.currentPath.splineThru( pts ); + + return this; + + } + + toShapes( isCCW ) { + + function toShapesNoHoles( inSubpaths ) { + + const shapes = []; + + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + + const tmpPath = inSubpaths[ i ]; + + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + + shapes.push( tmpShape ); + + } + + return shapes; + + } + + function isPointInsidePolygon( inPt, inPolygon ) { + + const polyLen = inPolygon.length; + + // 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 + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; + + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + + if ( Math.abs( edgeDy ) > Number.EPSILON ) { + + // not parallel + if ( edgeDy < 0 ) { + + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + + } + + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + + 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 { + + const 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 + + } + + } 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; + + } + + } + + return inside; + + } + + const isClockWise = ShapeUtils.isClockWise; + + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; + + let solid, tmpPath, tmpShape; + const shapes = []; + + if ( subPaths.length === 1 ) { + + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; + + } + + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; + + // console.log("Holes first", holesFirst); + + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; + + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { + + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; + + if ( solid ) { + + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; + + //console.log('cw', i); + + } else { + + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + + //console.log('ccw', i); + + } + + } + + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + + + if ( newShapes.length > 1 ) { + + let ambiguous = false; + let toChange = 0; + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + betterShapeHoles[ sIdx ] = []; + + } + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + const sho = newShapeHoles[ sIdx ]; + + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { + + const ho = sho[ hIdx ]; + let hole_unassigned = true; + + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + + if ( sIdx !== s2Idx ) toChange ++; + + if ( hole_unassigned ) { + + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); + + } else { + + ambiguous = true; + + } + + } + + } + + if ( hole_unassigned ) { + + betterShapeHoles[ sIdx ].push( ho ); + + } + + } + + } + + if ( toChange > 0 && ambiguous === false ) { + + newShapeHoles = betterShapeHoles; + + } + + } + + let tmpHoles; + + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; + + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + + tmpShape.holes.push( tmpHoles[ j ].h ); + + } + + } + + //console.log("shape", shapes); + + return shapes; + + } + +} + +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf + +const _tables = /*@__PURE__*/ _generateTables(); + +function _generateTables() { + + // float32 to float16 helpers + + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); + + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); + + for ( let i = 0; i < 256; ++ i ) { + + const e = i - 127; + + // very small number (0, -0) + + if ( e < - 27 ) { + + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // small number (denorm) + + } else if ( e < - 14 ) { + + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; + + // normal number + + } else if ( e <= 15 ) { + + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + // large number (Infinity, -Infinity) + + } else if ( e < 128 ) { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // stay (NaN, Infinity, -Infinity) + + } else { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + } + + } + + // float16 to float32 helpers + + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); + + for ( let i = 1; i < 1024; ++ i ) { + + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent + + // normalized + while ( ( m & 0x00800000 ) === 0 ) { + + m <<= 1; + e -= 0x00800000; // decrement exponent + + } + + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias + + mantissaTable[ i ] = m | e; + + } + + for ( let i = 1024; i < 2048; ++ i ) { + + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + + } + + for ( let i = 1; i < 31; ++ i ) { + + exponentTable[ i ] = i << 23; + + } + + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; + + for ( let i = 33; i < 63; ++ i ) { + + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + + } + + exponentTable[ 63 ] = 0xc7800000; + + for ( let i = 1; i < 64; ++ i ) { + + if ( i !== 32 ) { + + offsetTable[ i ] = 1024; + + } + + } + + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; + +} + +// float32 to float16 + +function toHalfFloat( val ) { + + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); + + val = clamp( val, - 65504, 65504 ); + + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); + +} + +// float16 to float32 + +function fromHalfFloat( val ) { + + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; + +} + +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + fromHalfFloat: fromHalfFloat, + toHalfFloat: toHalfFloat +}); + +// r144 + +class BoxBufferGeometry extends BoxGeometry { + + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { + + console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' ); + super( width, height, depth, widthSegments, heightSegments, depthSegments ); + + + } + +} + +// r144 + +class CapsuleBufferGeometry extends CapsuleGeometry { + + constructor( radius, length, capSegments, radialSegments ) { + + console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' ); + super( radius, length, capSegments, radialSegments ); + + } + +} + +// r144 + +class CircleBufferGeometry extends CircleGeometry { + + constructor( radius, segments, thetaStart, thetaLength ) { + + console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' ); + super( radius, segments, thetaStart, thetaLength ); + + } + +} + +// r144 + +class ConeBufferGeometry extends ConeGeometry { + + constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' ); + super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + +} + +// r144 + +class CylinderBufferGeometry extends CylinderGeometry { + + constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' ); + super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + +} + +// r144 + +class DodecahedronBufferGeometry extends DodecahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class ExtrudeBufferGeometry extends ExtrudeGeometry { + + constructor( shapes, options ) { + + console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' ); + super( shapes, options ); + + } + +} + +// r144 + +class IcosahedronBufferGeometry extends IcosahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class LatheBufferGeometry extends LatheGeometry { + + constructor( points, segments, phiStart, phiLength ) { + + console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' ); + super( points, segments, phiStart, phiLength ); + + } + +} + +// r144 + +class OctahedronBufferGeometry extends OctahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class PlaneBufferGeometry extends PlaneGeometry { + + constructor( width, height, widthSegments, heightSegments ) { + + console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' ); + super( width, height, widthSegments, heightSegments ); + + } + +} + +// r144 + +class PolyhedronBufferGeometry extends PolyhedronGeometry { + + constructor( vertices, indices, radius, detail ) { + + console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' ); + super( vertices, indices, radius, detail ); + + } + +} + +// r144 + +class RingBufferGeometry extends RingGeometry { + + constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + + console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' ); + super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ); + + } + +} + +// r144 + +class ShapeBufferGeometry extends ShapeGeometry { + + constructor( shapes, curveSegments ) { + + console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' ); + super( shapes, curveSegments ); + + } + +} + +// r144 + +class SphereBufferGeometry extends SphereGeometry { + + constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + + console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' ); + super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ); + + } + +} + +// r144 + +class TetrahedronBufferGeometry extends TetrahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class TorusBufferGeometry extends TorusGeometry { + + constructor( radius, tube, radialSegments, tubularSegments, arc ) { + + console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' ); + super( radius, tube, radialSegments, tubularSegments, arc ); + + } + +} + +// r144 + +class TorusKnotBufferGeometry extends TorusKnotGeometry { + + constructor( radius, tube, tubularSegments, radialSegments, p, q ) { + + console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' ); + super( radius, tube, tubularSegments, radialSegments, p, q ); + + } + +} + +// r144 + +class TubeBufferGeometry extends TubeGeometry { + + constructor( path, tubularSegments, radius, radialSegments, closed ) { + + console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' ); + super( path, tubularSegments, radius, radialSegments, closed ); + + } + +} + +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + +} + +if ( typeof window !== 'undefined' ) { + + if ( window.__THREE__ ) { + + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); + + } else { + + window.__THREE__ = REVISION; + + } + +} + +exports.ACESFilmicToneMapping = ACESFilmicToneMapping; +exports.AddEquation = AddEquation; +exports.AddOperation = AddOperation; +exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode; +exports.AdditiveBlending = AdditiveBlending; +exports.AlphaFormat = AlphaFormat; +exports.AlwaysDepth = AlwaysDepth; +exports.AlwaysStencilFunc = AlwaysStencilFunc; +exports.AmbientLight = AmbientLight; +exports.AmbientLightProbe = AmbientLightProbe; +exports.AnimationClip = AnimationClip; +exports.AnimationLoader = AnimationLoader; +exports.AnimationMixer = AnimationMixer; +exports.AnimationObjectGroup = AnimationObjectGroup; +exports.AnimationUtils = AnimationUtils; +exports.ArcCurve = ArcCurve; +exports.ArrayCamera = ArrayCamera; +exports.ArrowHelper = ArrowHelper; +exports.Audio = Audio; +exports.AudioAnalyser = AudioAnalyser; +exports.AudioContext = AudioContext; +exports.AudioListener = AudioListener; +exports.AudioLoader = AudioLoader; +exports.AxesHelper = AxesHelper; +exports.BackSide = BackSide; +exports.BasicDepthPacking = BasicDepthPacking; +exports.BasicShadowMap = BasicShadowMap; +exports.Bone = Bone; +exports.BooleanKeyframeTrack = BooleanKeyframeTrack; +exports.Box2 = Box2; +exports.Box3 = Box3; +exports.Box3Helper = Box3Helper; +exports.BoxBufferGeometry = BoxBufferGeometry; +exports.BoxGeometry = BoxGeometry; +exports.BoxHelper = BoxHelper; +exports.BufferAttribute = BufferAttribute; +exports.BufferGeometry = BufferGeometry; +exports.BufferGeometryLoader = BufferGeometryLoader; +exports.ByteType = ByteType; +exports.Cache = Cache; +exports.Camera = Camera; +exports.CameraHelper = CameraHelper; +exports.CanvasTexture = CanvasTexture; +exports.CapsuleBufferGeometry = CapsuleBufferGeometry; +exports.CapsuleGeometry = CapsuleGeometry; +exports.CatmullRomCurve3 = CatmullRomCurve3; +exports.CineonToneMapping = CineonToneMapping; +exports.CircleBufferGeometry = CircleBufferGeometry; +exports.CircleGeometry = CircleGeometry; +exports.ClampToEdgeWrapping = ClampToEdgeWrapping; +exports.Clock = Clock; +exports.Color = Color; +exports.ColorKeyframeTrack = ColorKeyframeTrack; +exports.ColorManagement = ColorManagement; +exports.CompressedArrayTexture = CompressedArrayTexture; +exports.CompressedTexture = CompressedTexture; +exports.CompressedTextureLoader = CompressedTextureLoader; +exports.ConeBufferGeometry = ConeBufferGeometry; +exports.ConeGeometry = ConeGeometry; +exports.CubeCamera = CubeCamera; +exports.CubeReflectionMapping = CubeReflectionMapping; +exports.CubeRefractionMapping = CubeRefractionMapping; +exports.CubeTexture = CubeTexture; +exports.CubeTextureLoader = CubeTextureLoader; +exports.CubeUVReflectionMapping = CubeUVReflectionMapping; +exports.CubicBezierCurve = CubicBezierCurve; +exports.CubicBezierCurve3 = CubicBezierCurve3; +exports.CubicInterpolant = CubicInterpolant; +exports.CullFaceBack = CullFaceBack; +exports.CullFaceFront = CullFaceFront; +exports.CullFaceFrontBack = CullFaceFrontBack; +exports.CullFaceNone = CullFaceNone; +exports.Curve = Curve; +exports.CurvePath = CurvePath; +exports.CustomBlending = CustomBlending; +exports.CustomToneMapping = CustomToneMapping; +exports.CylinderBufferGeometry = CylinderBufferGeometry; +exports.CylinderGeometry = CylinderGeometry; +exports.Cylindrical = Cylindrical; +exports.Data3DTexture = Data3DTexture; +exports.DataArrayTexture = DataArrayTexture; +exports.DataTexture = DataTexture; +exports.DataTextureLoader = DataTextureLoader; +exports.DataUtils = DataUtils; +exports.DecrementStencilOp = DecrementStencilOp; +exports.DecrementWrapStencilOp = DecrementWrapStencilOp; +exports.DefaultLoadingManager = DefaultLoadingManager; +exports.DepthFormat = DepthFormat; +exports.DepthStencilFormat = DepthStencilFormat; +exports.DepthTexture = DepthTexture; +exports.DirectionalLight = DirectionalLight; +exports.DirectionalLightHelper = DirectionalLightHelper; +exports.DiscreteInterpolant = DiscreteInterpolant; +exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry; +exports.DodecahedronGeometry = DodecahedronGeometry; +exports.DoubleSide = DoubleSide; +exports.DstAlphaFactor = DstAlphaFactor; +exports.DstColorFactor = DstColorFactor; +exports.DynamicCopyUsage = DynamicCopyUsage; +exports.DynamicDrawUsage = DynamicDrawUsage; +exports.DynamicReadUsage = DynamicReadUsage; +exports.EdgesGeometry = EdgesGeometry; +exports.EllipseCurve = EllipseCurve; +exports.EqualDepth = EqualDepth; +exports.EqualStencilFunc = EqualStencilFunc; +exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; +exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; +exports.Euler = Euler; +exports.EventDispatcher = EventDispatcher; +exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry; +exports.ExtrudeGeometry = ExtrudeGeometry; +exports.FileLoader = FileLoader; +exports.Float16BufferAttribute = Float16BufferAttribute; +exports.Float32BufferAttribute = Float32BufferAttribute; +exports.Float64BufferAttribute = Float64BufferAttribute; +exports.FloatType = FloatType; +exports.Fog = Fog; +exports.FogExp2 = FogExp2; +exports.FramebufferTexture = FramebufferTexture; +exports.FrontSide = FrontSide; +exports.Frustum = Frustum; +exports.GLBufferAttribute = GLBufferAttribute; +exports.GLSL1 = GLSL1; +exports.GLSL3 = GLSL3; +exports.GreaterDepth = GreaterDepth; +exports.GreaterEqualDepth = GreaterEqualDepth; +exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc; +exports.GreaterStencilFunc = GreaterStencilFunc; +exports.GridHelper = GridHelper; +exports.Group = Group; +exports.HalfFloatType = HalfFloatType; +exports.HemisphereLight = HemisphereLight; +exports.HemisphereLightHelper = HemisphereLightHelper; +exports.HemisphereLightProbe = HemisphereLightProbe; +exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry; +exports.IcosahedronGeometry = IcosahedronGeometry; +exports.ImageBitmapLoader = ImageBitmapLoader; +exports.ImageLoader = ImageLoader; +exports.ImageUtils = ImageUtils; +exports.IncrementStencilOp = IncrementStencilOp; +exports.IncrementWrapStencilOp = IncrementWrapStencilOp; +exports.InstancedBufferAttribute = InstancedBufferAttribute; +exports.InstancedBufferGeometry = InstancedBufferGeometry; +exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; +exports.InstancedMesh = InstancedMesh; +exports.Int16BufferAttribute = Int16BufferAttribute; +exports.Int32BufferAttribute = Int32BufferAttribute; +exports.Int8BufferAttribute = Int8BufferAttribute; +exports.IntType = IntType; +exports.InterleavedBuffer = InterleavedBuffer; +exports.InterleavedBufferAttribute = InterleavedBufferAttribute; +exports.Interpolant = Interpolant; +exports.InterpolateDiscrete = InterpolateDiscrete; +exports.InterpolateLinear = InterpolateLinear; +exports.InterpolateSmooth = InterpolateSmooth; +exports.InvertStencilOp = InvertStencilOp; +exports.KeepStencilOp = KeepStencilOp; +exports.KeyframeTrack = KeyframeTrack; +exports.LOD = LOD; +exports.LatheBufferGeometry = LatheBufferGeometry; +exports.LatheGeometry = LatheGeometry; +exports.Layers = Layers; +exports.LessDepth = LessDepth; +exports.LessEqualDepth = LessEqualDepth; +exports.LessEqualStencilFunc = LessEqualStencilFunc; +exports.LessStencilFunc = LessStencilFunc; +exports.Light = Light; +exports.LightProbe = LightProbe; +exports.Line = Line; +exports.Line3 = Line3; +exports.LineBasicMaterial = LineBasicMaterial; +exports.LineCurve = LineCurve; +exports.LineCurve3 = LineCurve3; +exports.LineDashedMaterial = LineDashedMaterial; +exports.LineLoop = LineLoop; +exports.LineSegments = LineSegments; +exports.LinearEncoding = LinearEncoding; +exports.LinearFilter = LinearFilter; +exports.LinearInterpolant = LinearInterpolant; +exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; +exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; +exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter; +exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter; +exports.LinearSRGBColorSpace = LinearSRGBColorSpace; +exports.LinearToneMapping = LinearToneMapping; +exports.Loader = Loader; +exports.LoaderUtils = LoaderUtils; +exports.LoadingManager = LoadingManager; +exports.LoopOnce = LoopOnce; +exports.LoopPingPong = LoopPingPong; +exports.LoopRepeat = LoopRepeat; +exports.LuminanceAlphaFormat = LuminanceAlphaFormat; +exports.LuminanceFormat = LuminanceFormat; +exports.MOUSE = MOUSE; +exports.Material = Material; +exports.MaterialLoader = MaterialLoader; +exports.MathUtils = MathUtils; +exports.Matrix3 = Matrix3; +exports.Matrix4 = Matrix4; +exports.MaxEquation = MaxEquation; +exports.Mesh = Mesh; +exports.MeshBasicMaterial = MeshBasicMaterial; +exports.MeshDepthMaterial = MeshDepthMaterial; +exports.MeshDistanceMaterial = MeshDistanceMaterial; +exports.MeshLambertMaterial = MeshLambertMaterial; +exports.MeshMatcapMaterial = MeshMatcapMaterial; +exports.MeshNormalMaterial = MeshNormalMaterial; +exports.MeshPhongMaterial = MeshPhongMaterial; +exports.MeshPhysicalMaterial = MeshPhysicalMaterial; +exports.MeshStandardMaterial = MeshStandardMaterial; +exports.MeshToonMaterial = MeshToonMaterial; +exports.MinEquation = MinEquation; +exports.MirroredRepeatWrapping = MirroredRepeatWrapping; +exports.MixOperation = MixOperation; +exports.MultiplyBlending = MultiplyBlending; +exports.MultiplyOperation = MultiplyOperation; +exports.NearestFilter = NearestFilter; +exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; +exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; +exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; +exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; +exports.NeverDepth = NeverDepth; +exports.NeverStencilFunc = NeverStencilFunc; +exports.NoBlending = NoBlending; +exports.NoColorSpace = NoColorSpace; +exports.NoToneMapping = NoToneMapping; +exports.NormalAnimationBlendMode = NormalAnimationBlendMode; +exports.NormalBlending = NormalBlending; +exports.NotEqualDepth = NotEqualDepth; +exports.NotEqualStencilFunc = NotEqualStencilFunc; +exports.NumberKeyframeTrack = NumberKeyframeTrack; +exports.Object3D = Object3D; +exports.ObjectLoader = ObjectLoader; +exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap; +exports.OctahedronBufferGeometry = OctahedronBufferGeometry; +exports.OctahedronGeometry = OctahedronGeometry; +exports.OneFactor = OneFactor; +exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; +exports.OneMinusDstColorFactor = OneMinusDstColorFactor; +exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; +exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; +exports.OrthographicCamera = OrthographicCamera; +exports.PCFShadowMap = PCFShadowMap; +exports.PCFSoftShadowMap = PCFSoftShadowMap; +exports.PMREMGenerator = PMREMGenerator; +exports.Path = Path; +exports.PerspectiveCamera = PerspectiveCamera; +exports.Plane = Plane; +exports.PlaneBufferGeometry = PlaneBufferGeometry; +exports.PlaneGeometry = PlaneGeometry; +exports.PlaneHelper = PlaneHelper; +exports.PointLight = PointLight; +exports.PointLightHelper = PointLightHelper; +exports.Points = Points; +exports.PointsMaterial = PointsMaterial; +exports.PolarGridHelper = PolarGridHelper; +exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry; +exports.PolyhedronGeometry = PolyhedronGeometry; +exports.PositionalAudio = PositionalAudio; +exports.PropertyBinding = PropertyBinding; +exports.PropertyMixer = PropertyMixer; +exports.QuadraticBezierCurve = QuadraticBezierCurve; +exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; +exports.Quaternion = Quaternion; +exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; +exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; +exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format; +exports.RED_RGTC1_Format = RED_RGTC1_Format; +exports.REVISION = REVISION; +exports.RGBADepthPacking = RGBADepthPacking; +exports.RGBAFormat = RGBAFormat; +exports.RGBAIntegerFormat = RGBAIntegerFormat; +exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; +exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; +exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; +exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; +exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; +exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; +exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; +exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; +exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; +exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; +exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; +exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; +exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; +exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; +exports.RGBA_BPTC_Format = RGBA_BPTC_Format; +exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format; +exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; +exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_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_ETC1_Format = RGB_ETC1_Format; +exports.RGB_ETC2_Format = RGB_ETC2_Format; +exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; +exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; +exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; +exports.RGFormat = RGFormat; +exports.RGIntegerFormat = RGIntegerFormat; +exports.RawShaderMaterial = RawShaderMaterial; +exports.Ray = Ray; +exports.Raycaster = Raycaster; +exports.RectAreaLight = RectAreaLight; +exports.RedFormat = RedFormat; +exports.RedIntegerFormat = RedIntegerFormat; +exports.ReinhardToneMapping = ReinhardToneMapping; +exports.RepeatWrapping = RepeatWrapping; +exports.ReplaceStencilOp = ReplaceStencilOp; +exports.ReverseSubtractEquation = ReverseSubtractEquation; +exports.RingBufferGeometry = RingBufferGeometry; +exports.RingGeometry = RingGeometry; +exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format; +exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format; +exports.SRGBColorSpace = SRGBColorSpace; +exports.Scene = Scene; +exports.ShaderChunk = ShaderChunk; +exports.ShaderLib = ShaderLib; +exports.ShaderMaterial = ShaderMaterial; +exports.ShadowMaterial = ShadowMaterial; +exports.Shape = Shape; +exports.ShapeBufferGeometry = ShapeBufferGeometry; +exports.ShapeGeometry = ShapeGeometry; +exports.ShapePath = ShapePath; +exports.ShapeUtils = ShapeUtils; +exports.ShortType = ShortType; +exports.Skeleton = Skeleton; +exports.SkeletonHelper = SkeletonHelper; +exports.SkinnedMesh = SkinnedMesh; +exports.Source = Source; +exports.Sphere = Sphere; +exports.SphereBufferGeometry = SphereBufferGeometry; +exports.SphereGeometry = SphereGeometry; +exports.Spherical = Spherical; +exports.SphericalHarmonics3 = SphericalHarmonics3; +exports.SplineCurve = SplineCurve; +exports.SpotLight = SpotLight; +exports.SpotLightHelper = SpotLightHelper; +exports.Sprite = Sprite; +exports.SpriteMaterial = SpriteMaterial; +exports.SrcAlphaFactor = SrcAlphaFactor; +exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; +exports.SrcColorFactor = SrcColorFactor; +exports.StaticCopyUsage = StaticCopyUsage; +exports.StaticDrawUsage = StaticDrawUsage; +exports.StaticReadUsage = StaticReadUsage; +exports.StereoCamera = StereoCamera; +exports.StreamCopyUsage = StreamCopyUsage; +exports.StreamDrawUsage = StreamDrawUsage; +exports.StreamReadUsage = StreamReadUsage; +exports.StringKeyframeTrack = StringKeyframeTrack; +exports.SubtractEquation = SubtractEquation; +exports.SubtractiveBlending = SubtractiveBlending; +exports.TOUCH = TOUCH; +exports.TangentSpaceNormalMap = TangentSpaceNormalMap; +exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry; +exports.TetrahedronGeometry = TetrahedronGeometry; +exports.Texture = Texture; +exports.TextureLoader = TextureLoader; +exports.TorusBufferGeometry = TorusBufferGeometry; +exports.TorusGeometry = TorusGeometry; +exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; +exports.TorusKnotGeometry = TorusKnotGeometry; +exports.Triangle = Triangle; +exports.TriangleFanDrawMode = TriangleFanDrawMode; +exports.TriangleStripDrawMode = TriangleStripDrawMode; +exports.TrianglesDrawMode = TrianglesDrawMode; +exports.TubeBufferGeometry = TubeBufferGeometry; +exports.TubeGeometry = TubeGeometry; +exports.TwoPassDoubleSide = TwoPassDoubleSide; +exports.UVMapping = UVMapping; +exports.Uint16BufferAttribute = Uint16BufferAttribute; +exports.Uint32BufferAttribute = Uint32BufferAttribute; +exports.Uint8BufferAttribute = Uint8BufferAttribute; +exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute; +exports.Uniform = Uniform; +exports.UniformsGroup = UniformsGroup; +exports.UniformsLib = UniformsLib; +exports.UniformsUtils = UniformsUtils; +exports.UnsignedByteType = UnsignedByteType; +exports.UnsignedInt248Type = UnsignedInt248Type; +exports.UnsignedIntType = UnsignedIntType; +exports.UnsignedShort4444Type = UnsignedShort4444Type; +exports.UnsignedShort5551Type = UnsignedShort5551Type; +exports.UnsignedShortType = UnsignedShortType; +exports.VSMShadowMap = VSMShadowMap; +exports.Vector2 = Vector2; +exports.Vector3 = Vector3; +exports.Vector4 = Vector4; +exports.VectorKeyframeTrack = VectorKeyframeTrack; +exports.VideoTexture = VideoTexture; +exports.WebGL1Renderer = WebGL1Renderer; +exports.WebGL3DRenderTarget = WebGL3DRenderTarget; +exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget; +exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget; +exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets; +exports.WebGLRenderTarget = WebGLRenderTarget; +exports.WebGLRenderer = WebGLRenderer; +exports.WebGLUtils = WebGLUtils; +exports.WireframeGeometry = WireframeGeometry; +exports.WrapAroundEnding = WrapAroundEnding; +exports.ZeroCurvatureEnding = ZeroCurvatureEnding; +exports.ZeroFactor = ZeroFactor; +exports.ZeroSlopeEnding = ZeroSlopeEnding; +exports.ZeroStencilOp = ZeroStencilOp; +exports._SRGBAFormat = _SRGBAFormat; +exports.sRGBEncoding = sRGBEncoding; diff --git a/renderer/build/three.js b/renderer/build/three.js new file mode 100644 index 0000000..c274142 --- /dev/null +++ b/renderer/build/three.js @@ -0,0 +1,50597 @@ +/** + * @license + * Copyright 2010-2023 Three.js Authors + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {})); +})(this, (function (exports) { 'use strict'; + + const REVISION = '149dev'; + const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + const CullFaceNone = 0; + const CullFaceBack = 1; + const CullFaceFront = 2; + const CullFaceFrontBack = 3; + const BasicShadowMap = 0; + const PCFShadowMap = 1; + const PCFSoftShadowMap = 2; + const VSMShadowMap = 3; + const FrontSide = 0; + const BackSide = 1; + const DoubleSide = 2; + const TwoPassDoubleSide = 3; + const NoBlending = 0; + const NormalBlending = 1; + const AdditiveBlending = 2; + const SubtractiveBlending = 3; + const MultiplyBlending = 4; + const CustomBlending = 5; + const AddEquation = 100; + const SubtractEquation = 101; + const ReverseSubtractEquation = 102; + const MinEquation = 103; + const MaxEquation = 104; + const ZeroFactor = 200; + const OneFactor = 201; + const SrcColorFactor = 202; + const OneMinusSrcColorFactor = 203; + const SrcAlphaFactor = 204; + const OneMinusSrcAlphaFactor = 205; + const DstAlphaFactor = 206; + const OneMinusDstAlphaFactor = 207; + const DstColorFactor = 208; + const OneMinusDstColorFactor = 209; + const SrcAlphaSaturateFactor = 210; + const NeverDepth = 0; + const AlwaysDepth = 1; + const LessDepth = 2; + const LessEqualDepth = 3; + const EqualDepth = 4; + const GreaterEqualDepth = 5; + const GreaterDepth = 6; + const NotEqualDepth = 7; + const MultiplyOperation = 0; + const MixOperation = 1; + const AddOperation = 2; + const NoToneMapping = 0; + const LinearToneMapping = 1; + const ReinhardToneMapping = 2; + const CineonToneMapping = 3; + const ACESFilmicToneMapping = 4; + const CustomToneMapping = 5; + + const UVMapping = 300; + const CubeReflectionMapping = 301; + const CubeRefractionMapping = 302; + const EquirectangularReflectionMapping = 303; + const EquirectangularRefractionMapping = 304; + const CubeUVReflectionMapping = 306; + const RepeatWrapping = 1000; + const ClampToEdgeWrapping = 1001; + const MirroredRepeatWrapping = 1002; + const NearestFilter = 1003; + const NearestMipmapNearestFilter = 1004; + const NearestMipMapNearestFilter = 1004; + const NearestMipmapLinearFilter = 1005; + const NearestMipMapLinearFilter = 1005; + const LinearFilter = 1006; + const LinearMipmapNearestFilter = 1007; + const LinearMipMapNearestFilter = 1007; + const LinearMipmapLinearFilter = 1008; + const LinearMipMapLinearFilter = 1008; + const UnsignedByteType = 1009; + const ByteType = 1010; + const ShortType = 1011; + const UnsignedShortType = 1012; + const IntType = 1013; + const UnsignedIntType = 1014; + const FloatType = 1015; + const HalfFloatType = 1016; + const UnsignedShort4444Type = 1017; + const UnsignedShort5551Type = 1018; + const UnsignedInt248Type = 1020; + const AlphaFormat = 1021; + const RGBAFormat = 1023; + const LuminanceFormat = 1024; + const LuminanceAlphaFormat = 1025; + const DepthFormat = 1026; + const DepthStencilFormat = 1027; + const RedFormat = 1028; + const RedIntegerFormat = 1029; + const RGFormat = 1030; + const RGIntegerFormat = 1031; + const RGBAIntegerFormat = 1033; + + const RGB_S3TC_DXT1_Format = 33776; + const RGBA_S3TC_DXT1_Format = 33777; + const RGBA_S3TC_DXT3_Format = 33778; + const RGBA_S3TC_DXT5_Format = 33779; + const RGB_PVRTC_4BPPV1_Format = 35840; + const RGB_PVRTC_2BPPV1_Format = 35841; + const RGBA_PVRTC_4BPPV1_Format = 35842; + const RGBA_PVRTC_2BPPV1_Format = 35843; + const RGB_ETC1_Format = 36196; + const RGB_ETC2_Format = 37492; + const RGBA_ETC2_EAC_Format = 37496; + const RGBA_ASTC_4x4_Format = 37808; + const RGBA_ASTC_5x4_Format = 37809; + const RGBA_ASTC_5x5_Format = 37810; + const RGBA_ASTC_6x5_Format = 37811; + const RGBA_ASTC_6x6_Format = 37812; + const RGBA_ASTC_8x5_Format = 37813; + const RGBA_ASTC_8x6_Format = 37814; + const RGBA_ASTC_8x8_Format = 37815; + const RGBA_ASTC_10x5_Format = 37816; + const RGBA_ASTC_10x6_Format = 37817; + const RGBA_ASTC_10x8_Format = 37818; + const RGBA_ASTC_10x10_Format = 37819; + const RGBA_ASTC_12x10_Format = 37820; + const RGBA_ASTC_12x12_Format = 37821; + const RGBA_BPTC_Format = 36492; + const RED_RGTC1_Format = 36283; + const SIGNED_RED_RGTC1_Format = 36284; + const RED_GREEN_RGTC2_Format = 36285; + const SIGNED_RED_GREEN_RGTC2_Format = 36286; + const LoopOnce = 2200; + const LoopRepeat = 2201; + const LoopPingPong = 2202; + const InterpolateDiscrete = 2300; + const InterpolateLinear = 2301; + const InterpolateSmooth = 2302; + const ZeroCurvatureEnding = 2400; + const ZeroSlopeEnding = 2401; + const WrapAroundEnding = 2402; + const NormalAnimationBlendMode = 2500; + const AdditiveAnimationBlendMode = 2501; + const TrianglesDrawMode = 0; + const TriangleStripDrawMode = 1; + const TriangleFanDrawMode = 2; + const LinearEncoding = 3000; + const sRGBEncoding = 3001; + const BasicDepthPacking = 3200; + const RGBADepthPacking = 3201; + const TangentSpaceNormalMap = 0; + const ObjectSpaceNormalMap = 1; + + // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. + const NoColorSpace = ''; + const SRGBColorSpace = 'srgb'; + const LinearSRGBColorSpace = 'srgb-linear'; + + const ZeroStencilOp = 0; + const KeepStencilOp = 7680; + const ReplaceStencilOp = 7681; + const IncrementStencilOp = 7682; + const DecrementStencilOp = 7683; + const IncrementWrapStencilOp = 34055; + const DecrementWrapStencilOp = 34056; + const InvertStencilOp = 5386; + + const NeverStencilFunc = 512; + const LessStencilFunc = 513; + const EqualStencilFunc = 514; + const LessEqualStencilFunc = 515; + const GreaterStencilFunc = 516; + const NotEqualStencilFunc = 517; + const GreaterEqualStencilFunc = 518; + const AlwaysStencilFunc = 519; + + const StaticDrawUsage = 35044; + const DynamicDrawUsage = 35048; + const StreamDrawUsage = 35040; + const StaticReadUsage = 35045; + const DynamicReadUsage = 35049; + const StreamReadUsage = 35041; + const StaticCopyUsage = 35046; + const DynamicCopyUsage = 35050; + const StreamCopyUsage = 35042; + + const GLSL1 = '100'; + const GLSL3 = '300 es'; + + const _SRGBAFormat = 1035; // fallback for WebGL 1 + + /** + * https://github.com/mrdoob/eventdispatcher.js/ + */ + + class EventDispatcher { + + addEventListener( type, listener ) { + + if ( this._listeners === undefined ) this._listeners = {}; + + const listeners = this._listeners; + + if ( listeners[ type ] === undefined ) { + + listeners[ type ] = []; + + } + + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + + listeners[ type ].push( listener ); + + } + + } + + hasEventListener( type, listener ) { + + if ( this._listeners === undefined ) return false; + + const listeners = this._listeners; + + return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; + + } + + removeEventListener( type, listener ) { + + if ( this._listeners === undefined ) return; + + const listeners = this._listeners; + const listenerArray = listeners[ type ]; + + if ( listenerArray !== undefined ) { + + const index = listenerArray.indexOf( listener ); + + if ( index !== - 1 ) { + + listenerArray.splice( index, 1 ); + + } + + } + + } + + dispatchEvent( event ) { + + if ( this._listeners === undefined ) return; + + const listeners = this._listeners; + const listenerArray = listeners[ event.type ]; + + if ( listenerArray !== undefined ) { + + event.target = this; + + // Make a copy, in case listeners are removed while iterating. + const array = listenerArray.slice( 0 ); + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + array[ i ].call( this, event ); + + } + + event.target = null; + + } + + } + + } + + const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + + let _seed = 1234567; + + + const DEG2RAD = Math.PI / 180; + const RAD2DEG = 180 / Math.PI; + + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 + function generateUUID() { + + const d0 = Math.random() * 0xffffffff | 0; + const d1 = Math.random() * 0xffffffff | 0; + const d2 = Math.random() * 0xffffffff | 0; + const d3 = Math.random() * 0xffffffff | 0; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; + + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); + + } + + function clamp( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); + + } + + // compute euclidean modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation + function euclideanModulo( n, m ) { + + return ( ( n % m ) + m ) % m; + + } + + // Linear mapping from range to range + function mapLinear( x, a1, a2, b1, b2 ) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + + } + + // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ + function inverseLerp( x, y, value ) { + + if ( x !== y ) { + + return ( value - x ) / ( y - x ); + + } else { + + return 0; + + } + + } + + // https://en.wikipedia.org/wiki/Linear_interpolation + function lerp( x, y, t ) { + + return ( 1 - t ) * x + t * y; + + } + + // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ + function damp( x, y, lambda, dt ) { + + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); + + } + + // https://www.desmos.com/calculator/vcsjnyz7x4 + function pingpong( x, length = 1 ) { + + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); + + } + + // http://en.wikipedia.org/wiki/Smoothstep + function smoothstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * ( 3 - 2 * x ); + + } + + function smootherstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + + } + + // Random integer from interval + function randInt( low, high ) { + + return low + Math.floor( Math.random() * ( high - low + 1 ) ); + + } + + // Random float from interval + function randFloat( low, high ) { + + return low + Math.random() * ( high - low ); + + } + + // Random float from <-range/2, range/2> interval + function randFloatSpread( range ) { + + return range * ( 0.5 - Math.random() ); + + } + + // Deterministic pseudo-random float in the interval [ 0, 1 ] + function seededRandom( s ) { + + if ( s !== undefined ) _seed = s; + + // Mulberry32 generator + + let t = _seed += 0x6D2B79F5; + + t = Math.imul( t ^ t >>> 15, t | 1 ); + + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); + + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; + + } + + function degToRad( degrees ) { + + return degrees * DEG2RAD; + + } + + function radToDeg( radians ) { + + return radians * RAD2DEG; + + } + + function isPowerOfTwo( value ) { + + return ( value & ( value - 1 ) ) === 0 && value !== 0; + + } + + function ceilPowerOfTwo( value ) { + + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + + } + + function floorPowerOfTwo( value ) { + + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + + } + + function setQuaternionFromProperEuler( q, a, b, c, order ) { + + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles + + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians + + const cos = Math.cos; + const sin = Math.sin; + + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); + + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); + + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); + + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); + + switch ( order ) { + + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; + + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; + + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; + + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; + + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; + + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; + + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + + } + + } + + function denormalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return value / 65535.0; + + case Uint8Array: + + return value / 255.0; + + case Int16Array: + + return Math.max( value / 32767.0, - 1.0 ); + + case Int8Array: + + return Math.max( value / 127.0, - 1.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + + } + + function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + + return Math.round( value * 255.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + + } + + var MathUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + ceilPowerOfTwo: ceilPowerOfTwo, + clamp: clamp, + damp: damp, + degToRad: degToRad, + denormalize: denormalize, + euclideanModulo: euclideanModulo, + floorPowerOfTwo: floorPowerOfTwo, + generateUUID: generateUUID, + inverseLerp: inverseLerp, + isPowerOfTwo: isPowerOfTwo, + lerp: lerp, + mapLinear: mapLinear, + normalize: normalize, + pingpong: pingpong, + radToDeg: radToDeg, + randFloat: randFloat, + randFloatSpread: randFloatSpread, + randInt: randInt, + seededRandom: seededRandom, + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + smootherstep: smootherstep, + smoothstep: smoothstep + }); + + class Vector2 { + + constructor( x = 0, y = 0 ) { + + Vector2.prototype.isVector2 = true; + + this.x = x; + this.y = y; + + } + + get width() { + + return this.x; + + } + + set width( value ) { + + this.x = value; + + } + + get height() { + + return this.y; + + } + + set height( value ) { + + this.y = value; + + } + + set( x, y ) { + + this.x = x; + this.y = y; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + + return this; + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + + return this; + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + + return this; + + } + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y; + + } + + cross( v ) { + + return this.x * v.y - this.y * v.x; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + angle() { + + // computes the angle in radians with respect to the positive x-axis + + const angle = Math.atan2( - this.y, - this.x ) + Math.PI; + + return angle; + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + + return this; + + } + + rotateAround( center, angle ) { + + const c = Math.cos( angle ), s = Math.sin( angle ); + + const x = this.x - center.x; + const y = this.y - center.y; + + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } + + } + + class Matrix3 { + + constructor() { + + Matrix3.prototype.isMatrix3 = true; + + this.elements = [ + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + + const te = this.elements; + + 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; + + } + + identity() { + + this.set( + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ); + + return this; + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); + + return this; + + } + + setFromMatrix4( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] + + ); + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + + const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + + return this; + + } + + multiplyScalar( s ) { + + const te = this.elements; + + 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; + + return this; + + } + + determinant() { + + const te = this.elements; + + const 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 a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + + } + + invert() { + + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], + n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], + n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], + + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, + + det = n11 * t11 + n21 * t12 + n31 * t13; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + + return this; + + } + + transpose() { + + let tmp; + const 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; + + return this; + + } + + getNormalMatrix( matrix4 ) { + + return this.setFromMatrix4( matrix4 ).invert().transpose(); + + } + + transposeIntoArray( r ) { + + const m = this.elements; + + 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 ]; + + return this; + + } + + setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { + + const c = Math.cos( rotation ); + const s = Math.sin( rotation ); + + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); + + return this; + + } + + // + + scale( sx, sy ) { + + this.premultiply( _m3.makeScale( sx, sy ) ); + + return this; + + } + + rotate( theta ) { + + this.premultiply( _m3.makeRotation( - theta ) ); + + return this; + + } + + translate( tx, ty ) { + + this.premultiply( _m3.makeTranslation( tx, ty ) ); + + return this; + + } + + // for 2D Transforms + + makeTranslation( x, y ) { + + this.set( + + 1, 0, x, + 0, 1, y, + 0, 0, 1 + + ); + + return this; + + } + + makeRotation( theta ) { + + // counterclockwise + + const c = Math.cos( theta ); + const s = Math.sin( theta ); + + this.set( + + c, - s, 0, + s, c, 0, + 0, 0, 1 + + ); + + return this; + + } + + makeScale( x, y ) { + + this.set( + + x, 0, 0, + 0, y, 0, + 0, 0, 1 + + ); + + return this; + + } + + // + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 9; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; + + return array; + + } + + clone() { + + return new this.constructor().fromArray( this.elements ); + + } + + } + + const _m3 = /*@__PURE__*/ new Matrix3(); + + function arrayNeedsUint32( array ) { + + // assumes larger values usually on last + + for ( let i = array.length - 1; i >= 0; -- i ) { + + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + + } + + return false; + + } + + const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array + }; + + function getTypedArray( type, buffer ) { + + return new TYPED_ARRAYS[ type ]( buffer ); + + } + + function createElementNS( name ) { + + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); + + } + + function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + + } + + function LinearToSRGB( c ) { + + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + + } + + // JavaScript RGB-to-RGB transforms, defined as + // FN[InputColorSpace][OutputColorSpace] callback functions. + const FN = { + [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear }, + [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB }, + }; + + const ColorManagement = { + + legacyMode: true, + + get workingColorSpace() { + + return LinearSRGBColorSpace; + + }, + + set workingColorSpace( colorSpace ) { + + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); + + }, + + convert: function ( color, sourceColorSpace, targetColorSpace ) { + + if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { + + return color; + + } + + if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) { + + const fn = FN[ sourceColorSpace ][ targetColorSpace ]; + + color.r = fn( color.r ); + color.g = fn( color.g ); + color.b = fn( color.b ); + + return color; + + } + + throw new Error( 'Unsupported color space conversion.' ); + + }, + + fromWorkingColorSpace: function ( color, targetColorSpace ) { + + return this.convert( color, this.workingColorSpace, targetColorSpace ); + + }, + + toWorkingColorSpace: function ( color, sourceColorSpace ) { + + return this.convert( color, sourceColorSpace, this.workingColorSpace ); + + }, + + }; + + const _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, 'rebeccapurple': 0x663399, '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 }; + + const _rgb$1 = { r: 0, g: 0, b: 0 }; + const _hslA = { h: 0, s: 0, l: 0 }; + const _hslB = { h: 0, s: 0, l: 0 }; + + 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; + + } + + function toComponents( source, target ) { + + target.r = source.r; + target.g = source.g; + target.b = source.b; + + return target; + + } + + class Color { + + constructor( r, g, b ) { + + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + return this.set( r ); + + } + + return this.setRGB( r, g, b ); + + } + + set( value ) { + + if ( value && value.isColor ) { + + this.copy( value ); + + } else if ( typeof value === 'number' ) { + + this.setHex( value ); + + } else if ( typeof value === 'string' ) { + + this.setStyle( value ); + + } + + return this; + + } + + setScalar( scalar ) { + + this.r = scalar; + this.g = scalar; + this.b = scalar; + + return this; + + } + + setHex( hex, colorSpace = SRGBColorSpace ) { + + hex = Math.floor( hex ); + + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { + + this.r = r; + this.g = g; + this.b = b; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); + + if ( s === 0 ) { + + this.r = this.g = this.b = l; + + } else { + + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const 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 ); + + } + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setStyle( style, colorSpace = SRGBColorSpace ) { + + function handleAlpha( string ) { + + if ( string === undefined ) return; + + if ( parseFloat( string ) < 1 ) { + + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + + } + + } + + + let m; + + if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { + + // rgb / hsl + + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; + + switch ( name ) { + + case 'rgb': + case 'rgba': + + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // 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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + break; + + case 'hsl': + case 'hsla': + + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + const h = parseFloat( color[ 1 ] ) / 360; + const s = parseFloat( color[ 2 ] ) / 100; + const l = parseFloat( color[ 3 ] ) / 100; + + handleAlpha( color[ 4 ] ); + + return this.setHSL( h, s, l, colorSpace ); + + } + + break; + + } + + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + + // hex color + + const hex = m[ 1 ]; + const size = hex.length; + + if ( size === 3 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } else if ( size === 6 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + } + + if ( style && style.length > 0 ) { + + return this.setColorName( style, colorSpace ); + + } + + return this; + + } + + setColorName( style, colorSpace = SRGBColorSpace ) { + + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; + + if ( hex !== undefined ) { + + // red + this.setHex( hex, colorSpace ); + + } else { + + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); + + } + + return this; + + } + + clone() { + + return new this.constructor( this.r, this.g, this.b ); + + } + + copy( color ) { + + this.r = color.r; + this.g = color.g; + this.b = color.b; + + return this; + + } + + copySRGBToLinear( color ) { + + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); + + return this; + + } + + copyLinearToSRGB( color ) { + + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); + + return this; + + } + + convertSRGBToLinear() { + + this.copySRGBToLinear( this ); + + return this; + + } + + convertLinearToSRGB() { + + this.copyLinearToSRGB( this ); + + return this; + + } + + getHex( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0; + + } + + getHexString( colorSpace = SRGBColorSpace ) { + + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); + + } + + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b; + + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); + + let hue, saturation; + const lightness = ( min + max ) / 2.0; + + if ( min === max ) { + + hue = 0; + saturation = 0; + + } else { + + const delta = max - min; + + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + 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; + + } + + hue /= 6; + + } + + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + + } + + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + target.r = _rgb$1.r; + target.g = _rgb$1.g; + target.b = _rgb$1.b; + + return target; + + } + + getStyle( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + if ( colorSpace !== SRGBColorSpace ) { + + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`; + + } + + return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`; + + } + + offsetHSL( h, s, l ) { + + this.getHSL( _hslA ); + + _hslA.h += h; _hslA.s += s; _hslA.l += l; + + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + + return this; + + } + + add( color ) { + + this.r += color.r; + this.g += color.g; + this.b += color.b; + + return this; + + } + + addColors( color1, color2 ) { + + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + + return this; + + } + + addScalar( s ) { + + this.r += s; + this.g += s; + this.b += s; + + return this; + + } + + sub( color ) { + + 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; + + } + + multiply( color ) { + + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + + return this; + + } + + multiplyScalar( s ) { + + this.r *= s; + this.g *= s; + this.b *= s; + + return this; + + } + + lerp( color, alpha ) { + + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; + + return this; + + } + + lerpColors( color1, color2, alpha ) { + + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; + + return this; + + } + + lerpHSL( color, alpha ) { + + this.getHSL( _hslA ); + color.getHSL( _hslB ); + + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); + + return this; + + } + + equals( c ) { + + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + + } + + fromArray( array, offset = 0 ) { + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); + + return this; + + } + + toJSON() { + + return this.getHex(); + + } + + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + + } + + Color.NAMES = _colorKeywords; + + let _canvas; + + class ImageUtils { + + static getDataURL( image ) { + + if ( /^data:/i.test( image.src ) ) { + + return image.src; + + } + + if ( typeof HTMLCanvasElement == 'undefined' ) { + + return image.src; + + } + + let canvas; + + if ( image instanceof HTMLCanvasElement ) { + + canvas = image; + + } else { + + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); + + _canvas.width = image.width; + _canvas.height = image.height; + + const context = _canvas.getContext( '2d' ); + + if ( image instanceof ImageData ) { + + context.putImageData( image, 0, 0 ); + + } else { + + context.drawImage( image, 0, 0, image.width, image.height ); + + } + + canvas = _canvas; + + } + + if ( canvas.width > 2048 || canvas.height > 2048 ) { + + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); + + return canvas.toDataURL( 'image/jpeg', 0.6 ); + + } else { + + return canvas.toDataURL( 'image/png' ); + + } + + } + + static sRGBToLinear( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const canvas = createElementNS( 'canvas' ); + + canvas.width = image.width; + canvas.height = image.height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); + + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; + + for ( let i = 0; i < data.length; i ++ ) { + + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; + + } + + context.putImageData( imageData, 0, 0 ); + + return canvas; + + } else if ( image.data ) { + + const data = image.data.slice( 0 ); + + for ( let i = 0; i < data.length; i ++ ) { + + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { + + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); + + } else { + + // assuming float + + data[ i ] = SRGBToLinear( data[ i ] ); + + } + + } + + return { + data: data, + width: image.width, + height: image.height + }; + + } else { + + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; + + } + + } + + } + + class Source { + + constructor( data = null ) { + + this.isSource = true; + + this.uuid = generateUUID(); + + this.data = data; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { + + return meta.images[ this.uuid ]; + + } + + const output = { + uuid: this.uuid, + url: '' + }; + + const data = this.data; + + if ( data !== null ) { + + let url; + + if ( Array.isArray( data ) ) { + + // cube texture + + url = []; + + for ( let i = 0, l = data.length; i < l; i ++ ) { + + if ( data[ i ].isDataTexture ) { + + url.push( serializeImage( data[ i ].image ) ); + + } else { + + url.push( serializeImage( data[ i ] ) ); + + } + + } + + } else { + + // texture + + url = serializeImage( data ); + + } + + output.url = url; + + } + + if ( ! isRootObject ) { + + meta.images[ this.uuid ] = output; + + } + + return output; + + } + + } + + function serializeImage( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + // default images + + return ImageUtils.getDataURL( image ); + + } else { + + if ( image.data ) { + + // images of DataTexture + + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + + } else { + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); + return {}; + + } + + } + + } + + let textureId = 0; + + class Texture extends EventDispatcher { + + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding ) { + + super(); + + this.isTexture = true; + + Object.defineProperty( this, 'id', { value: textureId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + + this.source = new Source( image ); + this.mipmaps = []; + + this.mapping = mapping; + + this.wrapS = wrapS; + this.wrapT = wrapT; + + this.magFilter = magFilter; + this.minFilter = minFilter; + + this.anisotropy = anisotropy; + + this.format = format; + this.internalFormat = null; + this.type = type; + + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; + + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + + 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) + + // 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; + + this.userData = {}; + + this.version = 0; + this.onUpdate = null; + + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not + this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) + + } + + get image() { + + return this.source.data; + + } + + set image( value ) { + + this.source.data = value; + + } + + updateMatrix() { + + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); + + this.mapping = source.mapping; + + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + + this.anisotropy = source.anisotropy; + + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); + + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + this.needsUpdate = true; + + return this; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + + return meta.textures[ this.uuid ]; + + } + + const output = { + + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, + + uuid: this.uuid, + name: this.name, + + image: this.source.toJSON( meta ).uuid, + + mapping: this.mapping, + + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, + + wrap: [ this.wrapS, this.wrapT ], + + format: this.format, + type: this.type, + encoding: this.encoding, + + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + + flipY: this.flipY, + + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + + }; + + if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData; + + if ( ! isRootObject ) { + + meta.textures[ this.uuid ] = output; + + } + + return output; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + transformUv( uv ) { + + if ( this.mapping !== UVMapping ) return uv; + + uv.applyMatrix3( this.matrix ); + + if ( uv.x < 0 || uv.x > 1 ) { + + switch ( this.wrapS ) { + + case RepeatWrapping: + + uv.x = uv.x - Math.floor( uv.x ); + break; + + case ClampToEdgeWrapping: + + uv.x = uv.x < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + + uv.x = Math.ceil( uv.x ) - uv.x; + + } else { + + uv.x = uv.x - Math.floor( uv.x ); + + } + + break; + + } + + } + + if ( uv.y < 0 || uv.y > 1 ) { + + switch ( this.wrapT ) { + + case RepeatWrapping: + + uv.y = uv.y - Math.floor( uv.y ); + break; + + case ClampToEdgeWrapping: + + uv.y = uv.y < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + + uv.y = Math.ceil( uv.y ) - uv.y; + + } else { + + uv.y = uv.y - Math.floor( uv.y ); + + } + + break; + + } + + } + + if ( this.flipY ) { + + uv.y = 1 - uv.y; + + } + + return uv; + + } + + set needsUpdate( value ) { + + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } + + } + + } + + Texture.DEFAULT_IMAGE = null; + Texture.DEFAULT_MAPPING = UVMapping; + Texture.DEFAULT_ANISOTROPY = 1; + + class Vector4 { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + Vector4.prototype.isVector4 = true; + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + } + + get width() { + + return this.z; + + } + + set width( value ) { + + this.z = value; + + } + + get height() { + + return this.w; + + } + + set height( value ) { + + this.w = value; + + } + + set( x, y, z, w ) { + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setW( w ) { + + this.w = w; + + return this; + + } + + setComponent( index, value ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z, this.w ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + this.w += s; + + return this; + + } + + addVectors( 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( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + + return this; + + } + + subVectors( 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; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + + return this; + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z, w = this.w; + const 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; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + setAxisAngleFromQuaternion( q ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + + // q is assumed to be normalized + + this.w = 2 * Math.acos( q.w ); + + const s = Math.sqrt( 1 - q.w * q.w ); + + if ( s < 0.0001 ) { + + this.x = 1; + this.y = 0; + this.z = 0; + + } else { + + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + + } + + return this; + + } + + setAxisAngleFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + + 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 ]; + + 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 + + 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 + + this.set( 1, 0, 0, 0 ); + + return this; // zero angle, arbitrary axis + + } + + // otherwise this singularity is angle = 180 + + angle = Math.PI; + + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; + + if ( ( xx > yy ) && ( xx > zz ) ) { + + // m11 is the largest diagonal term + + if ( xx < epsilon ) { + + x = 0; + y = 0.707106781; + z = 0.707106781; + + } else { + + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; + + } + + } else if ( yy > zz ) { + + // m22 is the largest diagonal term + + if ( yy < epsilon ) { + + x = 0.707106781; + y = 0; + z = 0.707106781; + + } else { + + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; + + } + + } else { + + // m33 is the largest diagonal term so base result on this + + if ( zz < epsilon ) { + + x = 0.707106781; + y = 0.707106781; + z = 0; + + } else { + + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; + + } + + } + + this.set( x, y, z, angle ); + + return this; // return 180 deg rotation + + } + + // as we have reached here there are no singularities so we can handle normally + + let 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 ); + + return this; + + } + + min( v ) { + + 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; + + } + + max( 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 ); + this.w = Math.max( this.w, v.w ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + 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() { + + 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() { + + 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() { + + 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; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + 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; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + yield this.w; + + } + + } + + /* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers + */ + class WebGLRenderTarget extends EventDispatcher { + + constructor( width = 1, height = 1, options = {} ) { + + super(); + + this.isWebGLRenderTarget = true; + + this.width = width; + this.height = height; + this.depth = 1; + + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; + + this.viewport = new Vector4( 0, 0, width, height ); + + const image = { width: width, height: height, depth: 1 }; + + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; + + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; + + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + + this.samples = options.samples !== undefined ? options.samples : 0; + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.copy( source.viewport ); + + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; + + // ensure image object is not shared, see #20328 + + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.samples = source.samples; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + } + + class DataArrayTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + super( null ); + + this.isDataArrayTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + + } + + class WebGLArrayRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGLArrayRenderTarget = true; + + this.depth = depth; + + this.texture = new DataArrayTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + + } + + class Data3DTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + super( null ); + + this.isData3DTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + + } + + class WebGL3DRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGL3DRenderTarget = true; + + this.depth = depth; + + this.texture = new Data3DTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + + } + + class WebGLMultipleRenderTargets extends WebGLRenderTarget { + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + super( width, height, options ); + + this.isWebGLMultipleRenderTargets = true; + + const texture = this.texture; + + this.texture = []; + + for ( let i = 0; i < count; i ++ ) { + + this.texture[ i ] = texture.clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + for ( let i = 0, il = this.texture.length; i < il; i ++ ) { + + this.texture[ i ].image.width = width; + this.texture[ i ].image.height = height; + this.texture[ i ].image.depth = depth; + + } + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + return this; + + } + + copy( source ) { + + this.dispose(); + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.set( 0, 0, this.width, this.height ); + this.scissor.set( 0, 0, this.width, this.height ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.texture.length = 0; + + for ( let i = 0, il = source.texture.length; i < il; i ++ ) { + + this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + return this; + + } + + } + + class Quaternion { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + this.isQuaternion = true; + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + } + + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + + // fuzz-free, array-based Quaternion SLERP operation + + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; + + if ( t === 0 ) { + + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; + + } + + if ( t === 1 ) { + + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; + + } + + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; + + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { + + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); + + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; + + } + + const tDir = t * dir; + + 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 ) { + + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + + } + + } + + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + + } + + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; + + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + + return dst; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get w() { + + return this._w; + + } + + set w( value ) { + + this._w = value; + this._onChangeCallback(); + + } + + set( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._w ); + + } + + copy( quaternion ) { + + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); + + return this; + + } + + setFromEuler( euler, update ) { + + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m + + const cos = Math.cos; + const sin = Math.sin; + + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); + + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); + + switch ( order ) { + + case 'XYZ': + 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; + break; + + case '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; + break; + + case 'ZXY': + 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; + break; + + case '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; + break; + + case '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; + break; + + case 'XZY': + 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; + break; + + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + + } + + if ( update !== false ) this._onChangeCallback(); + + return this; + + } + + setFromAxisAngle( axis, angle ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + + // assumes axis is normalized + + const halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const 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 ], + + trace = m11 + m22 + m33; + + if ( trace > 0 ) { + + const s = 0.5 / Math.sqrt( trace + 1.0 ); + + 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 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; + + } else { + + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._onChangeCallback(); + + return this; + + } + + setFromUnitVectors( vFrom, vTo ) { + + // assumes direction vectors vFrom and vTo are normalized + + let r = vFrom.dot( vTo ) + 1; + + if ( r < Number.EPSILON ) { + + // vFrom and vTo point in opposite directions + + r = 0; + + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + + } else { + + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; + + } + + } else { + + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + + } + + return this.normalize(); + + } + + angleTo( q ) { + + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); + + } + + rotateTowards( q, step ) { + + const angle = this.angleTo( q ); + + if ( angle === 0 ) return this; + + const t = Math.min( 1, step / angle ); + + this.slerp( q, t ); + + return this; + + } + + identity() { + + return this.set( 0, 0, 0, 1 ); + + } + + invert() { + + // quaternion is assumed to have unit length + + return this.conjugate(); + + } + + conjugate() { + + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); + + return this; + + } + + dot( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + + } + + lengthSq() { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + + } + + length() { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + + } + + normalize() { + + let l = this.length(); + + if ( l === 0 ) { + + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + + } else { + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + + } + + this._onChangeCallback(); + + return this; + + } + + multiply( q ) { + + return this.multiplyQuaternions( this, q ); + + } + + premultiply( q ) { + + return this.multiplyQuaternions( q, this ); + + } + + multiplyQuaternions( a, b ) { + + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + 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(); + + return this; + + } + + slerp( qb, t ) { + + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); + + const x = this._x, y = this._y, z = this._z, w = this._w; + + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + + if ( cosHalfTheta < 0 ) { + + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; + + cosHalfTheta = - cosHalfTheta; + + } else { + + this.copy( qb ); + + } + + if ( cosHalfTheta >= 1.0 ) { + + this._w = w; + this._x = x; + this._y = y; + this._z = z; + + return this; + + } + + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); + + return this; + + } + + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const 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 ); + + this._onChangeCallback(); + + return this; + + } + + slerpQuaternions( qa, qb, t ) { + + return this.copy( qa ).slerp( qb, t ); + + } + + random() { + + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. + + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); + + const u2 = 2 * Math.PI * Math.random(); + + const u3 = 2 * Math.PI * Math.random(); + + return this.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), + ); + + } + + equals( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + + } + + fromArray( array, offset = 0 ) { + + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); + + return this; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + + } + + class Vector3 { + + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; + + } + + set( x, y, z ) { + + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + + this.x = x; + this.y = y; + this.z = z; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + + return this; + + } + + multiplyVectors( a, b ) { + + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + + return this; + + } + + applyEuler( euler ) { + + return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) ); + + } + + applyAxisAngle( axis, angle ) { + + return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y, z = this.z; + const 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; + + } + + applyNormalMatrix( m ) { + + return this.applyMatrix3( m ).normalize(); + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + 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; + + return this; + + } + + applyQuaternion( q ) { + + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vector + + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; + + // 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; + + return this; + + } + + project( camera ) { + + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + + } + + unproject( camera ) { + + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + + } + + transformDirection( m ) { + + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + 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; + + return this.normalize(); + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + + return this; + + } + + max( 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 ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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 ) ); + + return this; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z; + + } + + // TODO lengthSquared? + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + + return this; + + } + + cross( v ) { + + return this.crossVectors( this, v ); + + } + + crossVectors( a, b ) { + + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + + } + + projectOnVector( v ) { + + const denominator = v.lengthSq(); + + if ( denominator === 0 ) return this.set( 0, 0, 0 ); + + const scalar = v.dot( this ) / denominator; + + return this.copy( v ).multiplyScalar( scalar ); + + } + + projectOnPlane( planeNormal ) { + + _vector$c.copy( this ).projectOnVector( planeNormal ); + + return this.sub( _vector$c ); + + } + + reflect( normal ) { + + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length + + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + + } + + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, - 1, 1 ) ); + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + + return dx * dx + dy * dy + dz * dz; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + + } + + setFromSpherical( s ) { + + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + + } + + setFromSphericalCoords( radius, phi, theta ) { + + const sinPhiRadius = Math.sin( phi ) * radius; + + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); + + return this; + + } + + setFromCylindrical( c ) { + + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + + } + + setFromCylindricalCoords( radius, theta, y ) { + + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); + + return this; + + } + + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + + return this; + + } + + setFromMatrixScale( m ) { + + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); + + this.x = sx; + this.y = sy; + this.z = sz; + + return this; + + } + + setFromMatrixColumn( m, index ) { + + return this.fromArray( m.elements, index * 4 ); + + } + + setFromMatrix3Column( m, index ) { + + return this.fromArray( m.elements, index * 3 ); + + } + + setFromEuler( e ) { + + this.x = e._x; + this.y = e._y; + this.z = e._z; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; + + } + + randomDirection() { + + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); + + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + + } + + } + + const _vector$c = /*@__PURE__*/ new Vector3(); + const _quaternion$4 = /*@__PURE__*/ new Quaternion(); + + class Box3 { + + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + + this.isBox3 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromArray( array ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const x = array[ i ]; + const y = array[ i + 1 ]; + const z = array[ i + 2 ]; + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromBufferAttribute( attribute ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = attribute.count; i < l; i ++ ) { + + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + setFromObject( object, precise = false ) { + + this.makeEmpty(); + + return this.expandByObject( object, precise ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ) || ( this.max.z < this.min.z ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + expandByObject( object, precise = false ) { + + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms + + object.updateWorldMatrix( false, false ); + + const geometry = object.geometry; + + if ( geometry !== undefined ) { + + if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) { + + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { + + _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); + + } + + } else { + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + _box$3.copy( geometry.boundingBox ); + _box$3.applyMatrix4( object.matrixWorld ); + + this.union( _box$3 ); + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } + + return this; + + } + + containsPoint( point ) { + + return 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 ? false : true; + + } + + containsBox( box ) { + + return 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; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.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 ) + ); + + } + + intersectsBox( box ) { + + // using 6 splitting planes to rule out intersections. + return 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 ? false : true; + + } + + intersectsSphere( sphere ) { + + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); + + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + intersectsPlane( plane ) { + + // 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. + + let min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + + } else { + + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + + } + + if ( plane.normal.y > 0 ) { + + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + + } else { + + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + + } + + if ( plane.normal.z > 0 ) { + + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + + } else { + + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); + + } + + intersectsTriangle( triangle ) { + + if ( this.isEmpty() ) { + + return false; + + } + + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); + + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$7.subVectors( triangle.b, _center ); + _v2$4.subVectors( triangle.c, _center ); + + // compute edge vectors for triangle + _f0.subVectors( _v1$7, _v0$2 ); + _f1.subVectors( _v2$4, _v1$7 ); + _f2.subVectors( _v0$2, _v2$4 ); + + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + + return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ); + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max ); + + return clampedPoint.sub( point ).length(); + + } + + getBoundingSphere( target ) { + + this.getCenter( target.center ); + + target.radius = this.getSize( _vector$b ).length() * 0.5; + + return target; + + } + + intersect( box ) { + + 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(); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + applyMatrix4( matrix ) { + + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; + + // 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 + + this.setFromPoints( _points ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + + } + + const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() + ]; + + const _vector$b = /*@__PURE__*/ new Vector3(); + + const _box$3 = /*@__PURE__*/ new Box3(); + + // triangle centered vertices + + const _v0$2 = /*@__PURE__*/ new Vector3(); + const _v1$7 = /*@__PURE__*/ new Vector3(); + const _v2$4 = /*@__PURE__*/ new Vector3(); + + // triangle edge vectors + + const _f0 = /*@__PURE__*/ new Vector3(); + const _f1 = /*@__PURE__*/ new Vector3(); + const _f2 = /*@__PURE__*/ new Vector3(); + + const _center = /*@__PURE__*/ new Vector3(); + const _extents = /*@__PURE__*/ new Vector3(); + const _triangleNormal = /*@__PURE__*/ new Vector3(); + const _testAxis = /*@__PURE__*/ new Vector3(); + + function satForAxes( axes, v0, v1, v2, extents ) { + + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; + + } + + } + + return true; + + } + + const _box$2 = /*@__PURE__*/ new Box3(); + const _v1$6 = /*@__PURE__*/ new Vector3(); + const _v2$3 = /*@__PURE__*/ new Vector3(); + + class Sphere { + + constructor( center = new Vector3(), radius = - 1 ) { + + this.center = center; + this.radius = radius; + + } + + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; + + } + + setFromPoints( points, optionalCenter ) { + + const center = this.center; + + if ( optionalCenter !== undefined ) { + + center.copy( optionalCenter ); + + } else { + + _box$2.setFromPoints( points ).getCenter( center ); + + } + + let maxRadiusSq = 0; + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + + } + + this.radius = Math.sqrt( maxRadiusSq ); + + return this; + + } + + copy( sphere ) { + + this.center.copy( sphere.center ); + this.radius = sphere.radius; + + return this; + + } + + isEmpty() { + + return ( this.radius < 0 ); + + } + + makeEmpty() { + + this.center.set( 0, 0, 0 ); + this.radius = - 1; + + return this; + + } + + containsPoint( point ) { + + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + + } + + distanceToPoint( point ) { + + return ( point.distanceTo( this.center ) - this.radius ); + + } + + intersectsSphere( sphere ) { + + const radiusSum = this.radius + sphere.radius; + + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + + } + + intersectsBox( box ) { + + return box.intersectsSphere( this ); + + } + + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + + } + + clampPoint( point, target ) { + + const deltaLengthSq = this.center.distanceToSquared( point ); + + target.copy( point ); + + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); + + } + + return target; + + } + + getBoundingBox( target ) { + + if ( this.isEmpty() ) { + + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; + + } + + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); + + return target; + + } + + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + + return this; + + } + + translate( offset ) { + + this.center.add( offset ); + + return this; + + } + + expandByPoint( point ) { + + if ( this.isEmpty() ) { + + this.center.copy( point ); + + this.radius = 0; + + return this; + + } + + _v1$6.subVectors( point, this.center ); + + const lengthSq = _v1$6.lengthSq(); + + if ( lengthSq > ( this.radius * this.radius ) ) { + + // calculate the minimal sphere + + const length = Math.sqrt( lengthSq ); + + const delta = ( length - this.radius ) * 0.5; + + this.center.addScaledVector( _v1$6, delta / length ); + + this.radius += delta; + + } + + return this; + + } + + union( sphere ) { + + if ( sphere.isEmpty() ) { + + return this; + + } + + if ( this.isEmpty() ) { + + this.copy( sphere ); + + return this; + + } + + if ( this.center.equals( sphere.center ) === true ) { + + this.radius = Math.max( this.radius, sphere.radius ); + + } else { + + _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius ); + + this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) ); + + this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) ); + + } + + return this; + + } + + equals( sphere ) { + + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + const _vector$a = /*@__PURE__*/ new Vector3(); + const _segCenter = /*@__PURE__*/ new Vector3(); + const _segDir = /*@__PURE__*/ new Vector3(); + const _diff = /*@__PURE__*/ new Vector3(); + + const _edge1 = /*@__PURE__*/ new Vector3(); + const _edge2 = /*@__PURE__*/ new Vector3(); + const _normal$1 = /*@__PURE__*/ new Vector3(); + + class Ray { + + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + + this.origin = origin; + this.direction = direction; + + } + + set( origin, direction ) { + + this.origin.copy( origin ); + this.direction.copy( direction ); + + return this; + + } + + copy( ray ) { + + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); + + return this; + + } + + at( t, target ) { + + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + + } + + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); + + return this; + + } + + recast( t ) { + + this.origin.copy( this.at( t, _vector$a ) ); + + return this; + + } + + closestPointToPoint( point, target ) { + + target.subVectors( point, this.origin ); + + const directionDistance = target.dot( this.direction ); + + if ( directionDistance < 0 ) { + + return target.copy( this.origin ); + + } + + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + } + + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); + + } + + distanceSqToPoint( point ) { + + const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction ); + + // point behind the ray + + if ( directionDistance < 0 ) { + + return this.origin.distanceToSquared( point ); + + } + + _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + return _vector$a.distanceToSquared( point ); + + } + + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + + // from https://github.com/pmjoniak/GeometricTools/blob/master/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 + + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); + + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; + + if ( det > 0 ) { + + // The ray and segment are not parallel. + + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { + + if ( s1 >= - extDet ) { + + if ( s1 <= extDet ) { + + // region 0 + // Minimum at interior points of ray and segment. + + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + + } else { + + // region 1 + + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + if ( s1 <= - extDet ) { + + // 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 ) { + + // region 3 + + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; + + } else { + + // region 2 + + 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 { + + // Ray and segment are parallel. + + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + if ( optionalPointOnRay ) { + + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + + } + + if ( optionalPointOnSegment ) { + + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + + } + + return sqrDist; + + } + + intersectSphere( sphere, target ) { + + _vector$a.subVectors( sphere.center, this.origin ); + const tca = _vector$a.dot( this.direction ); + const d2 = _vector$a.dot( _vector$a ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + const thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + const 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; + + // 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, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); + + } + + intersectsSphere( sphere ) { + + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + distanceToPlane( plane ) { + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { + + return 0; + + } + + // Null is preferable to undefined since undefined means.... it is undefined + + return null; + + } + + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + + // Return if the ray never intersects the plane + + return t >= 0 ? t : null; + + } + + intersectPlane( plane, target ) { + + const t = this.distanceToPlane( plane ); + + if ( t === null ) { + + return null; + + } + + return this.at( t, target ); + + } + + intersectsPlane( plane ) { + + // check if the ray lies on the plane first + + const distToPoint = plane.distanceToPoint( this.origin ); + + if ( distToPoint === 0 ) { + + return true; + + } + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator * distToPoint < 0 ) { + + return true; + + } + + // ray origin is behind the plane (and is pointing behind it) + + return false; + + } + + intersectBox( box, target ) { + + let tmin, tmax, tymin, tymax, tzmin, tzmax; + + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; + + const origin = this.origin; + + if ( invdirx >= 0 ) { + + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; + + } else { + + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + + } + + if ( invdiry >= 0 ) { + + 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; + + } + + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + + if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin; + + if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; + + } else { + + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + + } + + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + + //return point closest to the ray (positive side) + + if ( tmax < 0 ) return null; + + return this.at( tmin >= 0 ? tmin : tmax, target ); + + } + + intersectsBox( box ) { + + return this.intersectBox( box, _vector$a ) !== null; + + } + + intersectTriangle( a, b, c, backfaceCulling, target ) { + + // Compute the offset origin, edges, and normal. + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.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) + let DdN = this.direction.dot( _normal$1 ); + let sign; + + if ( DdN > 0 ) { + + if ( backfaceCulling ) return null; + sign = 1; + + } else if ( DdN < 0 ) { + + sign = - 1; + DdN = - DdN; + + } else { + + return null; + + } + + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { + + return null; + + } + + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { + + return null; + + } + + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { + + return null; + + } + + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); + + // t < 0, no intersection + if ( QdN < 0 ) { + + return null; + + } + + // Ray intersects triangle. + return this.at( QdN / DdN, target ); + + } + + applyMatrix4( matrix4 ) { + + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); + + return this; + + } + + equals( ray ) { + + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + class Matrix4 { + + constructor() { + + Matrix4.prototype.isMatrix4 = true; + + this.elements = [ + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + const 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; + + return this; + + } + + identity() { + + this.set( + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + clone() { + + return new Matrix4().fromArray( this.elements ); + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + + return this; + + } + + copyPosition( m ) { + + const te = this.elements, me = m.elements; + + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; + + return this; + + } + + setFromMatrix3( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); + + return this; + + } + + makeBasis( xAxis, yAxis, zAxis ) { + + 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; + + } + + extractRotation( m ) { + + // this method does not support reflection matrices + + const te = this.elements; + const me = m.elements; + + const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length(); + + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; + + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; + + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; + + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromEuler( euler ) { + + const te = this.elements; + + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); + + if ( euler.order === 'XYZ' ) { + + const ae = a * e, af = a * f, be = b * e, bf = b * f; + + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; + + 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; + + } else if ( euler.order === 'YXZ' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZXY' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZYX' ) { + + const 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; + + 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; + + } else if ( euler.order === 'YZX' ) { + + const 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' ) { + + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; + + 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; + + } + + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; + + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromQuaternion( q ) { + + return this.compose( _zero, q, _one ); + + } + + lookAt( eye, target, up ) { + + const te = this.elements; + + _z.subVectors( eye, target ); + + if ( _z.lengthSq() === 0 ) { + + // eye and target are in the same position + + _z.z = 1; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + if ( _x.lengthSq() === 0 ) { + + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { + + _z.x += 0.0001; + + } else { + + _z.z += 0.0001; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + } + + _x.normalize(); + _y.crossVectors( _z, _x ); + + 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; + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const 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; + + 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; + + } + + multiplyScalar( s ) { + + const 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; + + } + + determinant() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + + 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 + ) + + ); + + } + + transpose() { + + const te = this.elements; + let 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; + + 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; + + } + + setPosition( x, y, z ) { + + const te = this.elements; + + if ( x.isVector3 ) { + + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; + + } else { + + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; + + } + + return this; + + } + + invert() { + + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 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; + + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + 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; + + 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; + + 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; + + return this; + + } + + scale( v ) { + + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + + 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; + + return this; + + } + + getMaxScaleOnAxis() { + + const te = this.elements; + + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + + } + + makeTranslation( x, y, z ) { + + this.set( + + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationX( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationY( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationZ( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationAxis( axis, angle ) { + + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + + this.set( + + 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 + + ); + + return this; + + } + + makeScale( x, y, z ) { + + this.set( + + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeShear( xy, xz, yx, yz, zx, zy ) { + + this.set( + + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + compose( position, quaternion, scale ) { + + const te = this.elements; + + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + + const sx = scale.x, sy = scale.y, sz = scale.z; + + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; + + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; + + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; + + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; + + return this; + + } + + decompose( position, quaternion, scale ) { + + const te = this.elements; + + let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; + + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; + + // scale the rotation part + _m1$2.copy( this ); + + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; + + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; + + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; + + quaternion.setFromRotationMatrix( _m1$2 ); + + scale.x = sx; + scale.y = sy; + scale.z = sz; + + return this; + + } + + makePerspective( left, right, top, bottom, near, far ) { + + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); + + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + const c = - ( far + near ) / ( far - near ); + const 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; + + return this; + + } + + makeOrthographic( left, right, top, bottom, near, far ) { + + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); + + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; + const 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; + + return this; + + } + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 16; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 16; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + 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 ]; + + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; + + return array; + + } + + } + + const _v1$5 = /*@__PURE__*/ new Vector3(); + const _m1$2 = /*@__PURE__*/ new Matrix4(); + const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); + const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); + const _x = /*@__PURE__*/ new Vector3(); + const _y = /*@__PURE__*/ new Vector3(); + const _z = /*@__PURE__*/ new Vector3(); + + const _matrix$1 = /*@__PURE__*/ new Matrix4(); + const _quaternion$3 = /*@__PURE__*/ new Quaternion(); + + class Euler { + + constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) { + + this.isEuler = true; + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get order() { + + return this._order; + + } + + set order( value ) { + + this._order = value; + this._onChangeCallback(); + + } + + set( x, y, z, order = this._order ) { + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._order ); + + } + + copy( euler ) { + + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m, order = this._order, update = true ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + switch ( order ) { + + case 'XYZ': + + this._y = Math.asin( clamp( m13, - 1, 1 ) ); + + if ( Math.abs( m13 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); + + } else { + + this._x = Math.atan2( m32, m22 ); + this._z = 0; + + } + + break; + + case 'YXZ': + + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + + if ( Math.abs( m23 ) < 0.9999999 ) { + + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); + + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; + + } + + break; + + case 'ZXY': + + this._x = Math.asin( clamp( m32, - 1, 1 ) ); + + if ( Math.abs( m32 ) < 0.9999999 ) { + + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); + + } else { + + this._y = 0; + this._z = Math.atan2( m21, m11 ); + + } + + break; + + case 'ZYX': + + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + + if ( Math.abs( m31 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); + + } else { + + this._x = 0; + this._z = Math.atan2( - m12, m22 ); + + } + + break; + + case 'YZX': + + this._z = Math.asin( clamp( m21, - 1, 1 ) ); + + if ( Math.abs( m21 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); + + } else { + + this._x = 0; + this._y = Math.atan2( m13, m33 ); + + } + + break; + + case 'XZY': + + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + + if ( Math.abs( m12 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); + + } else { + + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + break; + + default: + + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + + } + + this._order = order; + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + setFromQuaternion( q, order, update ) { + + _matrix$1.makeRotationFromQuaternion( q ); + + return this.setFromRotationMatrix( _matrix$1, order, update ); + + } + + setFromVector3( v, order = this._order ) { + + return this.set( v.x, v.y, v.z, order ); + + } + + reorder( newOrder ) { + + // WARNING: this discards revolution information -bhouston + + _quaternion$3.setFromEuler( this ); + + return this.setFromQuaternion( _quaternion$3, newOrder ); + + } + + equals( euler ) { + + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + + } + + fromArray( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; + + return array; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + + } + + Euler.DEFAULT_ORDER = 'XYZ'; + + class Layers { + + constructor() { + + this.mask = 1 | 0; + + } + + set( channel ) { + + this.mask = ( 1 << channel | 0 ) >>> 0; + + } + + enable( channel ) { + + this.mask |= 1 << channel | 0; + + } + + enableAll() { + + this.mask = 0xffffffff | 0; + + } + + toggle( channel ) { + + this.mask ^= 1 << channel | 0; + + } + + disable( channel ) { + + this.mask &= ~ ( 1 << channel | 0 ); + + } + + disableAll() { + + this.mask = 0; + + } + + test( layers ) { + + return ( this.mask & layers.mask ) !== 0; + + } + + isEnabled( channel ) { + + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; + + } + + } + + let _object3DId = 0; + + const _v1$4 = /*@__PURE__*/ new Vector3(); + const _q1 = /*@__PURE__*/ new Quaternion(); + const _m1$1 = /*@__PURE__*/ new Matrix4(); + const _target = /*@__PURE__*/ new Vector3(); + + const _position$3 = /*@__PURE__*/ new Vector3(); + const _scale$2 = /*@__PURE__*/ new Vector3(); + const _quaternion$2 = /*@__PURE__*/ new Quaternion(); + + const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); + const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); + const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); + + const _addedEvent = { type: 'added' }; + const _removedEvent = { type: 'removed' }; + + class Object3D extends EventDispatcher { + + constructor() { + + super(); + + this.isObject3D = true; + + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Object3D'; + + this.parent = null; + this.children = []; + + this.up = Object3D.DEFAULT_UP.clone(); + + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); + + function onRotationChange() { + + quaternion.setFromEuler( rotation, false ); + + } + + function onQuaternionChange() { + + rotation.setFromQuaternion( quaternion, undefined, false ); + + } + + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); + + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); + + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer + + this.layers = new Layers(); + this.visible = true; + + this.castShadow = false; + this.receiveShadow = false; + + this.frustumCulled = true; + this.renderOrder = 0; + + this.animations = []; + + this.userData = {}; + + } + + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + applyMatrix4( matrix ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + this.matrix.premultiply( matrix ); + + this.matrix.decompose( this.position, this.quaternion, this.scale ); + + } + + applyQuaternion( q ) { + + this.quaternion.premultiply( q ); + + return this; + + } + + setRotationFromAxisAngle( axis, angle ) { + + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); + + } + + setRotationFromEuler( euler ) { + + this.quaternion.setFromEuler( euler, true ); + + } + + setRotationFromMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + this.quaternion.setFromRotationMatrix( m ); + + } + + setRotationFromQuaternion( q ) { + + // assumes q is normalized + + this.quaternion.copy( q ); + + } + + rotateOnAxis( axis, angle ) { + + // rotate object on axis in object space + // axis is assumed to be normalized + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.multiply( _q1 ); + + return this; + + } + + rotateOnWorldAxis( axis, angle ) { + + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.premultiply( _q1 ); + + return this; + + } + + rotateX( angle ) { + + return this.rotateOnAxis( _xAxis, angle ); + + } + + rotateY( angle ) { + + return this.rotateOnAxis( _yAxis, angle ); + + } + + rotateZ( angle ) { + + return this.rotateOnAxis( _zAxis, angle ); + + } + + translateOnAxis( axis, distance ) { + + // translate object by distance along axis in object space + // axis is assumed to be normalized + + _v1$4.copy( axis ).applyQuaternion( this.quaternion ); + + this.position.add( _v1$4.multiplyScalar( distance ) ); + + return this; + + } + + translateX( distance ) { + + return this.translateOnAxis( _xAxis, distance ); + + } + + translateY( distance ) { + + return this.translateOnAxis( _yAxis, distance ); + + } + + translateZ( distance ) { + + return this.translateOnAxis( _zAxis, distance ); + + } + + localToWorld( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( this.matrixWorld ); + + } + + worldToLocal( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + + } + + lookAt( x, y, z ) { + + // This method does not support objects having non-uniformly-scaled parent(s) + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + const parent = this.parent; + + this.updateWorldMatrix( true, false ); + + _position$3.setFromMatrixPosition( this.matrixWorld ); + + if ( this.isCamera || this.isLight ) { + + _m1$1.lookAt( _position$3, _target, this.up ); + + } else { + + _m1$1.lookAt( _target, _position$3, this.up ); + + } + + this.quaternion.setFromRotationMatrix( _m1$1 ); + + if ( parent ) { + + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); + + } + + } + + add( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + } + + if ( object === this ) { + + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; + + } + + if ( object && object.isObject3D ) { + + if ( object.parent !== null ) { + + object.parent.remove( object ); + + } + + object.parent = this; + this.children.push( object ); + + object.dispatchEvent( _addedEvent ); + + } else { + + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + + } + + return this; + + } + + remove( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.remove( arguments[ i ] ); + + } + + return this; + + } + + const index = this.children.indexOf( object ); + + if ( index !== - 1 ) { + + object.parent = null; + this.children.splice( index, 1 ); + + object.dispatchEvent( _removedEvent ); + + } + + return this; + + } + + removeFromParent() { + + const parent = this.parent; + + if ( parent !== null ) { + + parent.remove( this ); + + } + + return this; + + } + + clear() { + + for ( let i = 0; i < this.children.length; i ++ ) { + + const object = this.children[ i ]; + + object.parent = null; + + object.dispatchEvent( _removedEvent ); + + } + + this.children.length = 0; + + return this; + + + } + + attach( object ) { + + // adds object as a child of this, while maintaining the object's world transform + + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + + this.updateWorldMatrix( true, false ); + + _m1$1.copy( this.matrixWorld ).invert(); + + if ( object.parent !== null ) { + + object.parent.updateWorldMatrix( true, false ); + + _m1$1.multiply( object.parent.matrixWorld ); + + } + + object.applyMatrix4( _m1$1 ); + + this.add( object ); + + object.updateWorldMatrix( false, true ); + + return this; + + } + + getObjectById( id ) { + + return this.getObjectByProperty( 'id', id ); + + } + + getObjectByName( name ) { + + return this.getObjectByProperty( 'name', name ); + + } + + getObjectByProperty( name, value ) { + + if ( this[ name ] === value ) return this; + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); + + if ( object !== undefined ) { + + return object; + + } + + } + + return undefined; + + } + + getObjectsByProperty( name, value ) { + + let result = []; + + if ( this[ name ] === value ) result.push( this ); + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const childResult = this.children[ i ].getObjectsByProperty( name, value ); + + if ( childResult.length > 0 ) { + + result = result.concat( childResult ); + + } + + } + + return result; + + } + + getWorldPosition( target ) { + + this.updateWorldMatrix( true, false ); + + return target.setFromMatrixPosition( this.matrixWorld ); + + } + + getWorldQuaternion( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, target, _scale$2 ); + + return target; + + } + + getWorldScale( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, _quaternion$2, target ); + + return target; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + + } + + raycast( /* raycaster, intersects */ ) {} + + traverse( callback ) { + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverse( callback ); + + } + + } + + traverseVisible( callback ) { + + if ( this.visible === false ) return; + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverseVisible( callback ); + + } + + } + + traverseAncestors( callback ) { + + const parent = this.parent; + + if ( parent !== null ) { + + callback( parent ); + + parent.traverseAncestors( callback ); + + } + + } + + updateMatrix() { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + this.matrixWorldNeedsUpdate = true; + + } + + updateMatrixWorld( force ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // update children + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } + + } + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + const parent = this.parent; + + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { + + parent.updateWorldMatrix( true, false ); + + } + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + // update children + + if ( updateChildren === true ) { + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true ) { + + child.updateWorldMatrix( false, true ); + + } + + } + + } + + } + + toJSON( meta ) { + + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + const output = {}; + + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { + + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; + + } + + // standard Object3D serialization + + const object = {}; + + object.uuid = this.uuid; + object.type = this.type; + + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData; + + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + + // object specific properties + + if ( this.isInstancedMesh ) { + + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); + + } + + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); + + } + + return element.uuid; + + } + + if ( this.isScene ) { + + if ( this.background ) { + + if ( this.background.isColor ) { + + object.background = this.background.toJSON(); + + } else if ( this.background.isTexture ) { + + object.background = this.background.toJSON( meta ).uuid; + + } + + } + + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { + + object.environment = this.environment.toJSON( meta ).uuid; + + } + + } else if ( this.isMesh || this.isLine || this.isPoints ) { + + object.geometry = serialize( meta.geometries, this.geometry ); + + const parameters = this.geometry.parameters; + + if ( parameters !== undefined && parameters.shapes !== undefined ) { + + const shapes = parameters.shapes; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + serialize( meta.shapes, shape ); + + } + + } else { + + serialize( meta.shapes, shapes ); + + } + + } + + } + + if ( this.isSkinnedMesh ) { + + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + + if ( this.skeleton !== undefined ) { + + serialize( meta.skeletons, this.skeleton ); + + object.skeleton = this.skeleton.uuid; + + } + + } + + if ( this.material !== undefined ) { + + if ( Array.isArray( this.material ) ) { + + const uuids = []; + + for ( let i = 0, l = this.material.length; i < l; i ++ ) { + + uuids.push( serialize( meta.materials, this.material[ i ] ) ); + + } + + object.material = uuids; + + } else { + + object.material = serialize( meta.materials, this.material ); + + } + + } + + // + + if ( this.children.length > 0 ) { + + object.children = []; + + for ( let i = 0; i < this.children.length; i ++ ) { + + object.children.push( this.children[ i ].toJSON( meta ).object ); + + } + + } + + // + + if ( this.animations.length > 0 ) { + + object.animations = []; + + for ( let i = 0; i < this.animations.length; i ++ ) { + + const animation = this.animations[ i ]; + + object.animations.push( serialize( meta.animations, animation ) ); + + } + + } + + if ( isRootObject ) { + + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); + + 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; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; + + } + + output.object = object; + + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { + + const values = []; + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + } + + clone( recursive ) { + + return new this.constructor().copy( this, recursive ); + + } + + copy( source, recursive = true ) { + + this.name = source.name; + + this.up.copy( source.up ); + + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); + + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + + this.layers.mask = source.layers.mask; + this.visible = source.visible; + + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { + + for ( let i = 0; i < source.children.length; i ++ ) { + + const child = source.children[ i ]; + this.add( child.clone() ); + + } + + } + + return this; + + } + + } + + Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 ); + Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + + const _v0$1 = /*@__PURE__*/ new Vector3(); + const _v1$3 = /*@__PURE__*/ new Vector3(); + const _v2$2 = /*@__PURE__*/ new Vector3(); + const _v3$1 = /*@__PURE__*/ new Vector3(); + + const _vab = /*@__PURE__*/ new Vector3(); + const _vac = /*@__PURE__*/ new Vector3(); + const _vbc = /*@__PURE__*/ new Vector3(); + const _vap = /*@__PURE__*/ new Vector3(); + const _vbp = /*@__PURE__*/ new Vector3(); + const _vcp = /*@__PURE__*/ new Vector3(); + + class Triangle { + + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + + this.a = a; + this.b = b; + this.c = c; + + } + + static getNormal( a, b, c, target ) { + + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); + + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { + + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + + } + + return target.set( 0, 0, 0 ); + + } + + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { + + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$2.subVectors( point, a ); + + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$3 ); + const dot02 = _v0$1.dot( _v2$2 ); + const dot11 = _v1$3.dot( _v1$3 ); + const dot12 = _v1$3.dot( _v2$2 ); + + const denom = ( dot00 * dot11 - dot01 * dot01 ); + + // 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 target.set( - 2, - 1, - 1 ); + + } + + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); + + } + + static containsPoint( point, a, b, c ) { + + this.getBarycoord( point, a, b, c, _v3$1 ); + + return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + + } + + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { + + this.getBarycoord( point, p1, p2, p3, _v3$1 ); + + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3$1.x ); + target.addScaledVector( uv2, _v3$1.y ); + target.addScaledVector( uv3, _v3$1.z ); + + return target; + + } + + static isFrontFacing( a, b, c, direction ) { + + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); + + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); + + return this; + + } + + setFromPointsAndIndices( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; + + } + + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { + + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( triangle ) { + + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; + + } + + getArea() { + + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); + + return _v0$1.cross( _v1$3 ).length() * 0.5; + + } + + getMidpoint( target ) { + + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + + } + + getNormal( target ) { + + return Triangle.getNormal( this.a, this.b, this.c, target ); + + } + + getPlane( target ) { + + return target.setFromCoplanarPoints( this.a, this.b, this.c ); + + } + + getBarycoord( point, target ) { + + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + + } + + getUV( point, uv1, uv2, uv3, target ) { + + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + + } + + containsPoint( point ) { + + return Triangle.containsPoint( point, this.a, this.b, this.c ); + + } + + isFrontFacing( direction ) { + + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + + } + + intersectsBox( box ) { + + return box.intersectsTriangle( this ); + + } + + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; + + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. + + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { + + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); + + } + + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { + + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } + + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); + + } + + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { + + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } + + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); + + } + + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + + } + + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; + + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + + } + + equals( triangle ) { + + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + + } + + } + + let materialId = 0; + + class Material extends EventDispatcher { + + constructor() { + + super(); + + this.isMaterial = true; + + Object.defineProperty( this, 'id', { value: materialId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Material'; + + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + + 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; + + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + + this.shadowSide = null; + + this.colorWrite = true; + + this.precision = null; // override the renderer's default precision for this material + + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + + this.dithering = false; + + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + + this.visible = true; + + this.toneMapped = true; + + this.userData = {}; + + this.version = 0; + + this._alphaTest = 0; + + } + + get alphaTest() { + + return this._alphaTest; + + } + + set alphaTest( value ) { + + if ( this._alphaTest > 0 !== value > 0 ) { + + this.version ++; + + } + + this._alphaTest = value; + + } + + onBuild( /* shaderobject, renderer */ ) {} + + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} + + onBeforeCompile( /* shaderobject, renderer */ ) {} + + customProgramCacheKey() { + + return this.onBeforeCompile.toString(); + + } + + setValues( values ) { + + if ( values === undefined ) return; + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); + continue; + + } + + if ( currentValue && currentValue.isColor ) { + + currentValue.set( newValue ); + + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( isRootObject ) { + + meta = { + textures: {}, + images: {} + }; + + } + + const data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; + + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; + + if ( this.name !== '' ) data.name = this.name; + + 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.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + + } + + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.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; + data.lightMapIntensity = this.lightMapIntensity; + + } + + if ( this.aoMap && this.aoMap.isTexture ) { + + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; + + } + + if ( this.bumpMap && this.bumpMap.isTexture ) { + + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; + + } + + if ( this.normalMap && this.normalMap.isTexture ) { + + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + + } + + if ( this.displacementMap && this.displacementMap.isTexture ) { + + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + + } + + 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 && 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.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; + + if ( this.envMap && this.envMap.isTexture ) { + + data.envMap = this.envMap.toJSON( meta ).uuid; + + if ( this.combine !== undefined ) data.combine = this.combine; + + } + + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; + + if ( this.gradientMap && this.gradientMap.isTexture ) { + + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + + } + + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); + + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; + + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; + + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; + + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; + + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; + + if ( this.dithering === true ) data.dithering = true; + + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + + if ( this.flatShading === true ) data.flatShading = this.flatShading; + + if ( this.visible === false ) data.visible = false; + + if ( this.toneMapped === false ) data.toneMapped = false; + + if ( this.fog === false ) data.fog = false; + + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + // TODO: Copied from Object3D.toJSON + + function extractFromCache( cache ) { + + const values = []; + + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + if ( isRootObject ) { + + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + + if ( srcPlanes !== null ) { + + const n = srcPlanes.length; + dstPlanes = new Array( n ); + + for ( let i = 0; i !== n; ++ i ) { + + dstPlanes[ i ] = srcPlanes[ i ].clone(); + + } + + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + } + + class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + 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'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + + } + + const _vector$9 = /*@__PURE__*/ new Vector3(); + const _vector2$1 = /*@__PURE__*/ new Vector2(); + + class BufferAttribute { + + constructor( array, itemSize, normalized = false ) { + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + + } + + this.isBufferAttribute = true; + + this.name = ''; + + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.itemSize; + index2 *= attribute.itemSize; + + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + copyArray( array ) { + + this.array.set( array ); + + return this; + + } + + applyMatrix3( m ) { + + if ( this.itemSize === 2 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector2$1.fromBufferAttribute( this, i ); + _vector2$1.applyMatrix3( m ); + + this.setXY( i, _vector2$1.x, _vector2$1.y ); + + } + + } else if ( this.itemSize === 3 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + _vector$9.applyMatrix3( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + } + + return this; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyMatrix4( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.transformDirection( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + set( value, offset = 0 ) { + + // Matching BufferAttribute constructor, do not normalize the array. + this.array.set( value, offset ); + + return this; + + } + + getX( index ) { + + let x = this.array[ index * this.itemSize ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = x; + + return this; + + } + + getY( index ) { + + let y = this.array[ index * this.itemSize + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = y; + + return this; + + } + + getZ( index ) { + + let z = this.array[ index * this.itemSize + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = z; + + return this; + + } + + getW( index ) { + + let w = this.array[ index * this.itemSize + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = w; + + return this; + + } + + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; + + return this; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + clone() { + + return new this.constructor( this.array, this.itemSize ).copy( this ); + + } + + toJSON() { + + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from( this.array ), + normalized: this.normalized + }; + + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; + + return data; + + } + + // @deprecated + + copyColorsArray() { + + console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' ); + + } + + copyVector2sArray() { + + console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' ); + + } + + copyVector3sArray() { + + console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' ); + + } + + copyVector4sArray() { + + console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' ); + + } + + } + + // + + class Int8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int8Array( array ), itemSize, normalized ); + + } + + } + + class Uint8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8Array( array ), itemSize, normalized ); + + } + + } + + class Uint8ClampedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8ClampedArray( array ), itemSize, normalized ); + + } + + } + + class Int16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int16Array( array ), itemSize, normalized ); + + } + + } + + class Uint16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + } + + } + + class Int32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int32Array( array ), itemSize, normalized ); + + } + + } + + class Uint32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint32Array( array ), itemSize, normalized ); + + } + + } + + class Float16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + this.isFloat16BufferAttribute = true; + + } + + } + + + class Float32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } + + } + + class Float64BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float64Array( array ), itemSize, normalized ); + + } + + } + + let _id$1 = 0; + + const _m1 = /*@__PURE__*/ new Matrix4(); + const _obj = /*@__PURE__*/ new Object3D(); + const _offset = /*@__PURE__*/ new Vector3(); + const _box$1 = /*@__PURE__*/ new Box3(); + const _boxMorphTargets = /*@__PURE__*/ new Box3(); + const _vector$8 = /*@__PURE__*/ new Vector3(); + + class BufferGeometry extends EventDispatcher { + + constructor() { + + super(); + + this.isBufferGeometry = true; + + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'BufferGeometry'; + + this.index = null; + this.attributes = {}; + + this.morphAttributes = {}; + this.morphTargetsRelative = false; + + this.groups = []; + + this.boundingBox = null; + this.boundingSphere = null; + + this.drawRange = { start: 0, count: Infinity }; + + this.userData = {}; + + } + + getIndex() { + + return this.index; + + } + + setIndex( index ) { + + if ( Array.isArray( index ) ) { + + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; + + } + + return this; + + } + + getAttribute( name ) { + + return this.attributes[ name ]; + + } + + setAttribute( name, attribute ) { + + this.attributes[ name ] = attribute; + + return this; + + } + + deleteAttribute( name ) { + + delete this.attributes[ name ]; + + return this; + + } + + hasAttribute( name ) { + + return this.attributes[ name ] !== undefined; + + } + + addGroup( start, count, materialIndex = 0 ) { + + this.groups.push( { + + start: start, + count: count, + materialIndex: materialIndex + + } ); + + } + + clearGroups() { + + this.groups = []; + + } + + setDrawRange( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; + + } + + applyMatrix4( matrix ) { + + const position = this.attributes.position; + + if ( position !== undefined ) { + + position.applyMatrix4( matrix ); + + position.needsUpdate = true; + + } + + const normal = this.attributes.normal; + + if ( normal !== undefined ) { + + const normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + normal.applyNormalMatrix( normalMatrix ); + + normal.needsUpdate = true; + + } + + const tangent = this.attributes.tangent; + + if ( tangent !== undefined ) { + + tangent.transformDirection( matrix ); + + tangent.needsUpdate = true; + + } + + if ( this.boundingBox !== null ) { + + this.computeBoundingBox(); + + } + + if ( this.boundingSphere !== null ) { + + this.computeBoundingSphere(); + + } + + return this; + + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateX( angle ) { + + // rotate geometry around world x-axis + + _m1.makeRotationX( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateY( angle ) { + + // rotate geometry around world y-axis + + _m1.makeRotationY( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateZ( angle ) { + + // rotate geometry around world z-axis + + _m1.makeRotationZ( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + translate( x, y, z ) { + + // translate geometry + + _m1.makeTranslation( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + scale( x, y, z ) { + + // scale geometry + + _m1.makeScale( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + lookAt( vector ) { + + _obj.lookAt( vector ); + + _obj.updateMatrix(); + + this.applyMatrix4( _obj.matrix ); + + return this; + + } + + center() { + + this.computeBoundingBox(); + + this.boundingBox.getCenter( _offset ).negate(); + + this.translate( _offset.x, _offset.y, _offset.z ); + + return this; + + } + + setFromPoints( points ) { + + const position = []; + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + const point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } + + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + return this; + + } + + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingBox.set( + new Vector3( - Infinity, - Infinity, - Infinity ), + new Vector3( + Infinity, + Infinity, + Infinity ) + ); + + return; + + } + + if ( position !== undefined ) { + + this.boundingBox.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _box$1.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( this.boundingBox.min, _box$1.min ); + this.boundingBox.expandByPoint( _vector$8 ); + + _vector$8.addVectors( this.boundingBox.max, _box$1.max ); + this.boundingBox.expandByPoint( _vector$8 ); + + } else { + + this.boundingBox.expandByPoint( _box$1.min ); + this.boundingBox.expandByPoint( _box$1.max ); + + } + + } + + } + + } else { + + this.boundingBox.makeEmpty(); + + } + + 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 ); + + } + + } + + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingSphere.set( new Vector3(), Infinity ); + + return; + + } + + if ( position ) { + + // first, find the center of the bounding sphere + + const center = this.boundingSphere.center; + + _box$1.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( _box$1.min, _boxMorphTargets.min ); + _box$1.expandByPoint( _vector$8 ); + + _vector$8.addVectors( _box$1.max, _boxMorphTargets.max ); + _box$1.expandByPoint( _vector$8 ); + + } else { + + _box$1.expandByPoint( _boxMorphTargets.min ); + _box$1.expandByPoint( _boxMorphTargets.max ); + + } + + } + + } + + _box$1.getCenter( center ); + + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + + let maxRadiusSq = 0; + + for ( let i = 0, il = position.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( position, i ); + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + const morphTargetsRelative = this.morphTargetsRelative; + + for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + + _vector$8.fromBufferAttribute( morphAttribute, j ); + + if ( morphTargetsRelative ) { + + _offset.fromBufferAttribute( position, j ); + _vector$8.add( _offset ); + + } + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + } + + } + + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + + if ( isNaN( this.boundingSphere.radius ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + } + + computeTangents() { + + const index = this.index; + const attributes = this.attributes; + + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) + + if ( index === null || + attributes.position === undefined || + attributes.normal === undefined || + attributes.uv === undefined ) { + + console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' ); + return; + + } + + const indices = index.array; + const positions = attributes.position.array; + const normals = attributes.normal.array; + const uvs = attributes.uv.array; + + const nVertices = positions.length / 3; + + if ( this.hasAttribute( 'tangent' ) === false ) { + + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + + } + + const tangents = this.getAttribute( 'tangent' ).array; + + const tan1 = [], tan2 = []; + + for ( let i = 0; i < nVertices; i ++ ) { + + tan1[ i ] = new Vector3(); + tan2[ i ] = new Vector3(); + + } + + const vA = new Vector3(), + vB = new Vector3(), + vC = new Vector3(), + + uvA = new Vector2(), + uvB = new Vector2(), + uvC = new Vector2(), + + sdir = new Vector3(), + tdir = new Vector3(); + + function handleTriangle( a, b, c ) { + + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); + + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); + + vB.sub( vA ); + vC.sub( vA ); + + uvB.sub( uvA ); + uvC.sub( uvA ); + + const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); + + // silently ignore degenerate uv triangles having coincident or colinear vertices + + if ( ! isFinite( r ) ) return; + + sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); + tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); + + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); + + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); + + } + + let groups = this.groups; + + if ( groups.length === 0 ) { + + groups = [ { + start: 0, + count: indices.length + } ]; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleTriangle( + indices[ j + 0 ], + indices[ j + 1 ], + indices[ j + 2 ] + ); + + } + + } + + const tmp = new Vector3(), tmp2 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + + function handleVertex( v ) { + + n.fromArray( normals, v * 3 ); + n2.copy( n ); + + const t = tan1[ v ]; + + // Gram-Schmidt orthogonalize + + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + + // Calculate handedness + + tmp2.crossVectors( n2, t ); + const test = tmp2.dot( tan2[ v ] ); + const w = ( test < 0.0 ) ? - 1.0 : 1.0; + + tangents[ v * 4 ] = tmp.x; + tangents[ v * 4 + 1 ] = tmp.y; + tangents[ v * 4 + 2 ] = tmp.z; + tangents[ v * 4 + 3 ] = w; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleVertex( indices[ j + 0 ] ); + handleVertex( indices[ j + 1 ] ); + handleVertex( indices[ j + 2 ] ); + + } + + } + + } + + computeVertexNormals() { + + const index = this.index; + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute !== undefined ) { + + let normalAttribute = this.getAttribute( 'normal' ); + + if ( normalAttribute === undefined ) { + + normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 ); + this.setAttribute( 'normal', normalAttribute ); + + } else { + + // reset existing normals to zero + + for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) { + + normalAttribute.setXYZ( i, 0, 0, 0 ); + + } + + } + + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + + // indexed elements + + if ( index ) { + + for ( let i = 0, il = index.count; i < il; i += 3 ) { + + const vA = index.getX( i + 0 ); + const vB = index.getX( i + 1 ); + const vC = index.getX( i + 2 ); + + pA.fromBufferAttribute( positionAttribute, vA ); + pB.fromBufferAttribute( positionAttribute, vB ); + pC.fromBufferAttribute( positionAttribute, vC ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + nA.fromBufferAttribute( normalAttribute, vA ); + nB.fromBufferAttribute( normalAttribute, vB ); + nC.fromBufferAttribute( normalAttribute, vC ); + + nA.add( cb ); + nB.add( cb ); + nC.add( cb ); + + normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z ); + normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z ); + normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z ); + + } + + } else { + + // non-indexed elements (unconnected triangle soup) + + for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) { + + pA.fromBufferAttribute( positionAttribute, i + 0 ); + pB.fromBufferAttribute( positionAttribute, i + 1 ); + pC.fromBufferAttribute( positionAttribute, i + 2 ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z ); + + } + + } + + this.normalizeNormals(); + + normalAttribute.needsUpdate = true; + + } + + } + + // @deprecated since r144 + + merge() { + + console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' ); + return this; + + } + + normalizeNormals() { + + const normals = this.attributes.normal; + + for ( let i = 0, il = normals.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( normals, i ); + + _vector$8.normalize(); + + normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + } + + toNonIndexed() { + + function convertBufferAttribute( attribute, indices ) { + + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array2 = new array.constructor( indices.length * itemSize ); + + let index = 0, index2 = 0; + + for ( let i = 0, l = indices.length; i < l; i ++ ) { + + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } + + for ( let j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + return new BufferAttribute( array2, itemSize, normalized ); + + } + + // + + if ( this.index === null ) { + + console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' ); + return this; + + } + + const geometry2 = new BufferGeometry(); + + const indices = this.index.array; + const attributes = this.attributes; + + // attributes + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + geometry2.setAttribute( name, newAttribute ); + + } + + // morph attributes + + const morphAttributes = this.morphAttributes; + + for ( const name in morphAttributes ) { + + const morphArray = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const attribute = morphAttribute[ i ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + morphArray.push( newAttribute ); + + } + + geometry2.morphAttributes[ name ] = morphArray; + + } + + geometry2.morphTargetsRelative = this.morphTargetsRelative; + + // groups + + const groups = this.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); + + } + + return geometry2; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; + + // standard BufferGeometry serialization + + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + if ( this.parameters !== undefined ) { + + const parameters = this.parameters; + + for ( const key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + + } + + return data; + + } + + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + + data.data = { attributes: {} }; + + const index = this.index; + + if ( index !== null ) { + + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; + + } + + const attributes = this.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + + data.data.attributes[ key ] = attribute.toJSON( data.data ); + + } + + const morphAttributes = {}; + let hasMorphAttributes = false; + + for ( const key in this.morphAttributes ) { + + const attributeArray = this.morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + + array.push( attribute.toJSON( data.data ) ); + + } + + if ( array.length > 0 ) { + + morphAttributes[ key ] = array; + + hasMorphAttributes = true; + + } + + } + + if ( hasMorphAttributes ) { + + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + + } + + const groups = this.groups; + + if ( groups.length > 0 ) { + + data.data.groups = JSON.parse( JSON.stringify( groups ) ); + + } + + const boundingSphere = this.boundingSphere; + + if ( boundingSphere !== null ) { + + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + // reset + + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + + // used for storing cloned, shared data + + const data = {}; + + // name + + this.name = source.name; + + // index + + const index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone( data ) ); + + } + + // attributes + + const attributes = source.attributes; + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone( data ) ); + + } + + // morph attributes + + const morphAttributes = source.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone( data ) ); + + } + + this.morphAttributes[ name ] = array; + + } + + this.morphTargetsRelative = source.morphTargetsRelative; + + // groups + + const groups = source.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); + + } + + // bounding box + + const boundingBox = source.boundingBox; + + if ( boundingBox !== null ) { + + this.boundingBox = boundingBox.clone(); + + } + + // bounding sphere + + const boundingSphere = source.boundingSphere; + + if ( boundingSphere !== null ) { + + this.boundingSphere = boundingSphere.clone(); + + } + + // draw range + + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + + // user data + + this.userData = source.userData; + + // geometry generator parameters + + if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + } + + const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); + const _ray$2 = /*@__PURE__*/ new Ray(); + const _sphere$3 = /*@__PURE__*/ new Sphere(); + + const _vA$1 = /*@__PURE__*/ new Vector3(); + const _vB$1 = /*@__PURE__*/ new Vector3(); + const _vC$1 = /*@__PURE__*/ new Vector3(); + + const _tempA = /*@__PURE__*/ new Vector3(); + const _morphA = /*@__PURE__*/ new Vector3(); + + const _uvA$1 = /*@__PURE__*/ new Vector2(); + const _uvB$1 = /*@__PURE__*/ new Vector2(); + const _uvC$1 = /*@__PURE__*/ new Vector2(); + + const _intersectionPoint = /*@__PURE__*/ new Vector3(); + const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); + + class Mesh extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { + + super(); + + this.isMesh = true; + + this.type = 'Mesh'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.morphTargetInfluences !== undefined ) { + + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + + } + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + getVertexPosition( index, target ) { + + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + + target.fromBufferAttribute( position, index ); + + const morphInfluences = this.morphTargetInfluences; + + if ( morphPosition && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + + for ( let i = 0, il = morphPosition.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morphAttribute = morphPosition[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morphAttribute, index ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( target ), influence ); + + } + + } + + target.add( _morphA ); + + } + + if ( this.isSkinnedMesh ) { + + this.boneTransform( index, target ); + + } + + return target; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + + // + + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + + // Check boundingBox before continuing + + if ( geometry.boundingBox !== null ) { + + if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return; + + } + + let intersection; + + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } else if ( position !== undefined ) { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = j; + const b = j + 1; + const c = j + 2; + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = i; + const b = i + 1; + const c = i + 2; + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } + + } + + } + + function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { + + let intersect; + + if ( material.side === BackSide ) { + + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + + } else { + + intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point ); + + } + + if ( intersect === null ) return null; + + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + + if ( distance < raycaster.near || distance > raycaster.far ) return null; + + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; + + } + + function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) { + + object.getVertexPosition( a, _vA$1 ); + object.getVertexPosition( b, _vB$1 ); + object.getVertexPosition( c, _vC$1 ); + + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); + + if ( intersection ) { + + if ( uv ) { + + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); + + intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + if ( uv2 ) { + + _uvA$1.fromBufferAttribute( uv2, a ); + _uvB$1.fromBufferAttribute( uv2, b ); + _uvC$1.fromBufferAttribute( uv2, c ); + + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + const face = { + a: a, + b: b, + c: c, + normal: new Vector3(), + materialIndex: 0 + }; + + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); + + intersection.face = face; + + } + + return intersection; + + } + + class BoxGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + this.type = 'BoxGeometry'; + + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; + + const scope = this; + + // segments + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let numberOfVertices = 0; + let groupStart = 0; + + // 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 + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + let vertexCounter = 0; + let groupCount = 0; + + const vector = new Vector3(); + + // generate vertices, normals and uvs + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segmentHeight - heightHalf; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segmentWidth - widthHalf; + + // set values to correct vector component + + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; + + // now apply vector to vertex buffer + + vertices.push( vector.x, vector.y, vector.z ); + + // set values to correct vector component + + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; + + // now apply vector to normal buffer + + normals.push( vector.x, vector.y, vector.z ); + + // uvs + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + // counters + + vertexCounter += 1; + + } + + } + + // indices + + // 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 + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // increase counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, materialIndex ); + + // calculate new start value for groups + + groupStart += groupCount; + + // update total number of vertices + + numberOfVertices += vertexCounter; + + } + + } + + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + + } + + /** + * Uniform Utilities + */ + + function cloneUniforms( src ) { + + const dst = {}; + + for ( const u in src ) { + + dst[ u ] = {}; + + for ( const p in src[ u ] ) { + + const property = src[ u ][ p ]; + + if ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ) { + + dst[ u ][ p ] = property.clone(); + + } else if ( Array.isArray( property ) ) { + + dst[ u ][ p ] = property.slice(); + + } else { + + dst[ u ][ p ] = property; + + } + + } + + } + + return dst; + + } + + function mergeUniforms( uniforms ) { + + const merged = {}; + + for ( let u = 0; u < uniforms.length; u ++ ) { + + const tmp = cloneUniforms( uniforms[ u ] ); + + for ( const p in tmp ) { + + merged[ p ] = tmp[ p ]; + + } + + } + + return merged; + + } + + function cloneUniformsGroups( src ) { + + const dst = []; + + for ( let u = 0; u < src.length; u ++ ) { + + dst.push( src[ u ].clone() ); + + } + + return dst; + + } + + function getUnlitUniformColorSpace( renderer ) { + + if ( renderer.getRenderTarget() === null ) { + + // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398 + return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; + + } + + return LinearSRGBColorSpace; + + } + + // Legacy + + const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + + var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + + var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + + class ShaderMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShaderMaterial = true; + + this.type = 'ShaderMaterial'; + + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + + this.linewidth = 1; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + 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 + + 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 + }; + + // 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; + this.uniformsNeedUpdate = false; + + this.glslVersion = null; + + if ( parameters !== undefined ) { + + this.setValues( parameters ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); + + this.defines = Object.assign( {}, source.defines ); + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + + this.extensions = Object.assign( {}, source.extensions ); + + this.glslVersion = source.glslVersion; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.glslVersion = this.glslVersion; + data.uniforms = {}; + + for ( const name in this.uniforms ) { + + const uniform = this.uniforms[ name ]; + const value = uniform.value; + + if ( value && value.isTexture ) { + + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; + + } else if ( value && value.isColor ) { + + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; + + } else if ( value && value.isVector2 ) { + + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; + + } else if ( value && value.isVector3 ) { + + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; + + } else if ( value && value.isVector4 ) { + + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; + + } else if ( value && value.isMatrix3 ) { + + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; + + } else if ( value && value.isMatrix4 ) { + + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; + + } else { + + data.uniforms[ name ] = { + value: value + }; + + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + + } + + } + + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + const extensions = {}; + + for ( const key in this.extensions ) { + + if ( this.extensions[ key ] === true ) extensions[ key ] = true; + + } + + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + + return data; + + } + + } + + class Camera extends Object3D { + + constructor() { + + super(); + + this.isCamera = true; + + this.type = 'Camera'; + + this.matrixWorldInverse = new Matrix4(); + + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); + + return this; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + super.updateWorldMatrix( updateParents, updateChildren ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + class PerspectiveCamera extends Camera { + + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + this.fov = fov; + this.zoom = 1; + + this.near = near; + this.far = far; + this.focus = 10; + + this.aspect = aspect; + this.view = null; + + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + 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( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * 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 + * + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( 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( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const near = this.near; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = - 0.5 * width; + const view = this.view; + + if ( this.view !== null && this.view.enabled ) { + + const fullWidth = view.fullWidth, + fullHeight = view.fullHeight; + + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + + } + + const skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.fov = this.fov; + data.object.zoom = this.zoom; + + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + + data.object.aspect = this.aspect; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + + return data; + + } + + } + + const fov = - 90; // negative fov is not an error + const aspect = 1; + + class CubeCamera extends Object3D { + + constructor( near, far, renderTarget ) { + + super(); + + this.type = 'CubeCamera'; + + this.renderTarget = renderTarget; + + const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + cameraPX.up.set( 0, 1, 0 ); + cameraPX.lookAt( 1, 0, 0 ); + this.add( cameraPX ); + + const cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + cameraNX.up.set( 0, 1, 0 ); + cameraNX.lookAt( - 1, 0, 0 ); + this.add( cameraNX ); + + const cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + cameraPY.up.set( 0, 0, - 1 ); + cameraPY.lookAt( 0, 1, 0 ); + this.add( cameraPY ); + + const cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + cameraNY.up.set( 0, 0, 1 ); + cameraNY.lookAt( 0, - 1, 0 ); + this.add( cameraNY ); + + const cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + cameraPZ.up.set( 0, 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + this.add( cameraPZ ); + + const cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + cameraNZ.up.set( 0, 1, 0 ); + cameraNZ.lookAt( 0, 0, - 1 ); + this.add( cameraNZ ); + + } + + update( renderer, scene ) { + + if ( this.parent === null ) this.updateMatrixWorld(); + + const renderTarget = this.renderTarget; + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; + + const currentRenderTarget = renderer.getRenderTarget(); + + const currentToneMapping = renderer.toneMapping; + const currentXrEnabled = renderer.xr.enabled; + + renderer.toneMapping = NoToneMapping; + renderer.xr.enabled = false; + + const generateMipmaps = renderTarget.texture.generateMipmaps; + + renderTarget.texture.generateMipmaps = false; + + renderer.setRenderTarget( renderTarget, 0 ); + renderer.render( scene, cameraPX ); + + renderer.setRenderTarget( renderTarget, 1 ); + renderer.render( scene, cameraNX ); + + renderer.setRenderTarget( renderTarget, 2 ); + renderer.render( scene, cameraPY ); + + renderer.setRenderTarget( renderTarget, 3 ); + renderer.render( scene, cameraNY ); + + renderer.setRenderTarget( renderTarget, 4 ); + renderer.render( scene, cameraPZ ); + + renderTarget.texture.generateMipmaps = generateMipmaps; + + renderer.setRenderTarget( renderTarget, 5 ); + renderer.render( scene, cameraNZ ); + + renderer.setRenderTarget( currentRenderTarget ); + + renderer.toneMapping = currentToneMapping; + renderer.xr.enabled = currentXrEnabled; + + renderTarget.texture.needsPMREMUpdate = true; + + } + + } + + class CubeTexture extends Texture { + + constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + + super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCubeTexture = true; + + this.flipY = false; + + } + + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + + } + + class WebGLCubeRenderTarget extends WebGLRenderTarget { + + constructor( size = 1, options = {} ) { + + super( size, size, options ); + + this.isWebGLCubeRenderTarget = true; + + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. + + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). + + this.texture.isRenderTargetTexture = true; + + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + } + + fromEquirectangularTexture( renderer, texture ) { + + this.texture.type = texture.type; + this.texture.encoding = texture.encoding; + + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + + const shader = { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: /* glsl */` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + + fragmentShader: /* glsl */` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + + const geometry = new BoxGeometry( 5, 5, 5 ); + + const material = new ShaderMaterial( { + + name: 'CubemapFromEquirect', + + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + + } ); + + material.uniforms.tEquirect.value = texture; + + const mesh = new Mesh( geometry, material ); + + const currentMinFilter = texture.minFilter; + + // Avoid blurred poles + if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter; + + const camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, mesh ); + + texture.minFilter = currentMinFilter; + + mesh.geometry.dispose(); + mesh.material.dispose(); + + return this; + + } + + clear( renderer, color, depth, stencil ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + for ( let i = 0; i < 6; i ++ ) { + + renderer.setRenderTarget( this, i ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( currentRenderTarget ); + + } + + } + + const _vector1 = /*@__PURE__*/ new Vector3(); + const _vector2 = /*@__PURE__*/ new Vector3(); + const _normalMatrix = /*@__PURE__*/ new Matrix3(); + + class Plane { + + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + + this.isPlane = true; + + // normal is assumed to be normalized + + this.normal = normal; + this.constant = constant; + + } + + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; + + } + + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; + + return this; + + } + + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + negate() { + + this.constant *= - 1; + this.normal.negate(); + + return this; + + } + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + projectPoint( point, target ) { + + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + + } + + intersectLine( line, target ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( t < 0 || t > 1 ) { + + return null; + + } + + return target.copy( direction ).multiplyScalar( t ).add( line.start ); + + } + + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + const _sphere$2 = /*@__PURE__*/ new Sphere(); + const _vector$7 = /*@__PURE__*/ new Vector3(); + + class Frustum { + + constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { + + this.planes = [ p0, p1, p2, p3, p4, p5 ]; + + } + + set( p0, p1, p2, p3, p4, p5 ) { + + const 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 ); + + return this; + + } + + copy( frustum ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + planes[ i ].copy( frustum.planes[ i ] ); + + } + + return this; + + } + + setFromProjectionMatrix( m ) { + + const planes = this.planes; + const me = m.elements; + const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + + 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(); + + return this; + + } + + intersectsObject( object ) { + + const geometry = object.geometry; + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSprite( sprite ) { + + _sphere$2.center.set( 0, 0, 0 ); + _sphere$2.radius = 0.7071067811865476; + _sphere$2.applyMatrix4( sprite.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSphere( sphere ) { + + const planes = this.planes; + const center = sphere.center; + const negRadius = - sphere.radius; + + for ( let i = 0; i < 6; i ++ ) { + + const distance = planes[ i ].distanceToPoint( center ); + + if ( distance < negRadius ) { + + return false; + + } + + } + + return true; + + } + + intersectsBox( box ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + const plane = planes[ i ]; + + // corner at max distance + + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; + + if ( plane.distanceToPoint( _vector$7 ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + containsPoint( point ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + function WebGLAnimation() { + + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + + function onAnimationFrame( time, frame ) { + + animationLoop( time, frame ); + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + } + + return { + + start: function () { + + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + isAnimating = true; + + }, + + stop: function () { + + context.cancelAnimationFrame( requestId ); + + isAnimating = false; + + }, + + setAnimationLoop: function ( callback ) { + + animationLoop = callback; + + }, + + setContext: function ( value ) { + + context = value; + + } + + }; + + } + + function WebGLAttributes( gl, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + const buffers = new WeakMap(); + + function createBuffer( attribute, bufferType ) { + + const array = attribute.array; + const usage = attribute.usage; + + const buffer = gl.createBuffer(); + + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); + + attribute.onUploadCallback(); + + let type; + + if ( array instanceof Float32Array ) { + + type = gl.FLOAT; + + } else if ( array instanceof Uint16Array ) { + + if ( attribute.isFloat16BufferAttribute ) { + + if ( isWebGL2 ) { + + type = gl.HALF_FLOAT; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); + + } + + } else { + + type = gl.UNSIGNED_SHORT; + + } + + } else if ( array instanceof Int16Array ) { + + type = gl.SHORT; + + } else if ( array instanceof Uint32Array ) { + + type = gl.UNSIGNED_INT; + + } else if ( array instanceof Int32Array ) { + + type = gl.INT; + + } else if ( array instanceof Int8Array ) { + + type = gl.BYTE; + + } else if ( array instanceof Uint8Array ) { + + type = gl.UNSIGNED_BYTE; + + } else if ( array instanceof Uint8ClampedArray ) { + + type = gl.UNSIGNED_BYTE; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + + } + + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; + + } + + function updateBuffer( buffer, attribute, bufferType ) { + + const array = attribute.array; + const updateRange = attribute.updateRange; + + gl.bindBuffer( bufferType, buffer ); + + if ( updateRange.count === - 1 ) { + + // Not using update ranges + + gl.bufferSubData( bufferType, 0, array ); + + } else { + + if ( isWebGL2 ) { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array, updateRange.offset, updateRange.count ); + + } else { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); + + } + + updateRange.count = - 1; // reset range + + } + + attribute.onUploadCallback(); + + } + + // + + function get( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + return buffers.get( attribute ); + + } + + function remove( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data ) { + + gl.deleteBuffer( data.buffer ); + + buffers.delete( attribute ); + + } + + } + + function update( attribute, bufferType ) { + + if ( attribute.isGLBufferAttribute ) { + + const cached = buffers.get( attribute ); + + if ( ! cached || cached.version < attribute.version ) { + + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); + + } + + return; + + } + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data === undefined ) { + + buffers.set( attribute, createBuffer( attribute, bufferType ) ); + + } else if ( data.version < attribute.version ) { + + updateBuffer( data.buffer, attribute, bufferType ); + + data.version = attribute.version; + + } + + } + + return { + + get: get, + remove: remove, + update: update + + }; + + } + + class PlaneGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { + + super(); + + this.type = 'PlaneGeometry'; + + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + + const width_half = width / 2; + const height_half = height / 2; + + const gridX = Math.floor( widthSegments ); + const gridY = Math.floor( heightSegments ); + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + const segment_width = width / gridX; + const segment_height = height / gridY; + + // + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segment_height - height_half; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segment_width - width_half; + + vertices.push( x, - y, 0 ); + + normals.push( 0, 0, 1 ); + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + } + + } + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = ix + gridX1 * iy; + const b = ix + gridX1 * ( iy + 1 ); + const c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = ( ix + 1 ) + gridX1 * iy; + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + + } + + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; + + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + + var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + + var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + + var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + + var begin_vertex = "vec3 transformed = vec3( position );"; + + var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + + var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + + var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + + var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + + var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + + var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + + var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; + + var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; + + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + + var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; + + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + + var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + + var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}"; + + var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + + var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + + var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + + var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + + var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + + var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + + var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + + var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + + var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + + var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + + var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + + var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + + var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; + + var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + + var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; + + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + + var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + + var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + + var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + + var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + + var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + + var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + + var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + + var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + + var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; + + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; + + var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + + var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + + var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + + var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + + var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + + var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + + var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; + + var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; + + var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + + var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; + + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + + var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + + var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + + var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + + var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + + var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + + var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + + var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + + var skinbase_vertex = "#ifdef USE_SKINNING\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#endif"; + + var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; + + var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + + var skinnormal_vertex = "#ifdef USE_SKINNING\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\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + + var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + + var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + + var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; + + var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; + + var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; + + var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; + + var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; + + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; + + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; + + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + + const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + + const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + + const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + + const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + + const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + + const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + + const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + + const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; + + const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + + const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + + const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + + const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + + const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}"; + + const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}"; + + const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + + const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + + const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + + const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const fragment$6 = "#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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + + const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + + const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}"; + + const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + + const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + + const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + + const ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + 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_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + 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_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + 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, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + output_fragment: output_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + 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, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_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, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 + }; + + /** + * Uniforms library for shared webgl shaders + */ + + const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + + }, + + envmap: { + + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 } + + }, + + emissivemap: { + + emissiveMap: { value: null } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + roughnessmap: { + + roughnessMap: { value: null } + + }, + + metalnessmap: { + + metalnessMap: { value: null } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + } + + }; + + const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distanceRGBA: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + + }; + + ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatNormalMap: { value: null }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }; + + const _rgb = { r: 0, b: 0, g: 0 }; + + function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function render( renderList, scene ) { + + let forceClear = false; + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background ); + + } + + // Ignore background in AR + // TODO: Reconsider this. + + const xr = renderer.xr; + const session = xr.getSession && xr.getSession(); + + if ( session && session.environmentBlendMode === 'additive' ) { + + background = null; + + } + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + if ( renderer.autoClear || forceClear ) { + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render + + }; + + } + + function WebGLBindingStates( gl, extensions, attributes, capabilities ) { + + const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + + const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' ); + const vaoAvailable = capabilities.isWebGL2 || extension !== null; + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + if ( vaoAvailable ) { + + const state = getBindingState( geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + } else { + + const wireframe = ( material.wireframe === true ); + + if ( currentState.geometry !== geometry.id || + currentState.program !== program.id || + currentState.wireframe !== wireframe ) { + + currentState.geometry = geometry.id; + currentState.program = program.id; + currentState.wireframe = wireframe; + + updateBuffers = true; + + } + + } + + if ( index !== null ) { + + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + if ( capabilities.isWebGL2 ) return gl.createVertexArray(); + + return extension.createVertexArrayOES(); + + } + + function bindVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao ); + + return extension.bindVertexArrayOES( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao ); + + return extension.deleteVertexArrayOES( vao ); + + } + + function getBindingState( geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let programMap = bindingStates[ geometry.id ]; + + if ( programMap === undefined ) { + + programMap = {}; + bindingStates[ geometry.id ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + + extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset ) { + + if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { + + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return; + + } + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const programMap = bindingStates[ geometry.id ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + + } + + function WebGLBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawArraysInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawArraysInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + + } + + function WebGLCapabilities( gl, extensions, parameters ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext; + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + + const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + + const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + + const vertexTextures = maxVertexTextures > 0; + const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' ); + const floatVertexTextures = vertexTextures && floatFragmentTextures; + + const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0; + + return { + + isWebGL2: isWebGL2, + + drawBuffers: drawBuffers, + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures, + + maxSamples: maxSamples + + }; + + } + + function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const 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; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + + } + + function WebGLCubeMaps( renderer ) { + + let cubemaps = new WeakMap(); + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function get( texture ) { + + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubemaps.has( texture ) ) { + + const cubemap = cubemaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubemaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemap = cubemaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubemaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function dispose() { + + cubemaps = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + + } + + class OrthographicCamera extends Camera { + + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + + super(); + + this.isOrthographicCamera = true; + + this.type = 'OrthographicCamera'; + + this.zoom = 1; + this.view = null; + + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + + this.near = near; + this.far = far; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + return this; + + } + + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + 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 ); + + return data; + + } + + } + + const LOD_MIN = 4; + + // The standard deviations (radians) associated with the extra mips. These are + // chosen to approximate a Trowbridge-Reitz distribution function times the + // geometric shadowing function. These sigma values squared must match the + // variance #defines in cube_uv_reflection_fragment.glsl.js. + const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + + // The maximum length of the blur for loop. Smaller sigmas will use fewer + // samples and exit early, but not recompile the shader. + const MAX_SAMPLES = 20; + + const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); + const _clearColor = /*@__PURE__*/ new Color(); + let _oldTarget = null; + + // Golden Ratio + const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; + const INV_PHI = 1 / PHI; + + // Vertices of a dodecahedron (except the opposites, which represent the + // same axis), used as axis directions evenly spread on a sphere. + const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + + /** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view + */ + + class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._compileMaterial( this._blurMaterial ); + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + + _oldTarget = this._renderer.getRenderTarget(); + + this._setSize( 256 ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + + this._lodPlanes[ i ].dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + encoding: LinearEncoding, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); + + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); + + let useSolidColor = false; + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { + + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); + + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); + + } + + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); + + } + + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; + + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; + + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + + if ( samples > MAX_SAMPLES ) { + + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + + } + + const weights = []; + let sum = 0; + + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); + + if ( i === 0 ) { + + sum += weight; + + } else if ( i < samples ) { + + sum += 2 * weight; + + } + + } + + for ( let i = 0; i < weights.length; i ++ ) { + + weights[ i ] = weights[ i ] / sum; + + } + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + + if ( poleAxis ) { + + blurUniforms[ 'poleAxis' ].value = poleAxis; + + } + + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + + } + + + + function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas }; + + } + + function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + + } + + function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + + } + + function _getBlurShader( lodMax, width, height ) { + + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + + } + + function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + } + + function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + } + + function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + + } + + function WebGLCubeUVMaps( renderer ) { + + let cubeUVmaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { + + texture.needsPMREMUpdate = false; + + let renderTarget = cubeUVmaps.get( texture ); + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( cubeUVmaps.has( texture ) ) { + + return cubeUVmaps.get( texture ).texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemapUV = cubeUVmaps.get( texture ); + + if ( cubemapUV !== undefined ) { + + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); + + } + + } + + function dispose() { + + cubeUVmaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + + } + + function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + let 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; + + 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; + + default: + extension = gl.getExtension( name ); + + } + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function ( capabilities ) { + + if ( capabilities.isWebGL2 ) { + + getExtension( 'EXT_color_buffer_float' ); + + } else { + + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); + + } + + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + + } + + function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + + } + + // morph targets + + const morphAttributes = geometry.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = morphAttributes[ name ]; + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + attributes.update( array[ i ], gl.ARRAY_BUFFER ); + + } + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } + + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + + } + + function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawElementsInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + + } + + function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; + + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; + + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; + + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + + case gl.POINTS: + render.points += instanceCount * count; + break; + + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + + } + + function numericalSort( a, b ) { + + return a[ 0 ] - b[ 0 ]; + + } + + function absNumericalSort( a, b ) { + + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + + } + + function WebGLMorphtargets( gl, capabilities, textures ) { + + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + const workInfluences = []; + + for ( let i = 0; i < 8; i ++ ) { + + workInfluences[ i ] = [ i, 0 ]; + + } + + function update( object, geometry, material, program ) { + + const objectInfluences = object.morphTargetInfluences; + + if ( capabilities.isWebGL2 === true ) { + + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + + } else { + + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + + const length = objectInfluences === undefined ? 0 : objectInfluences.length; + + let influences = influencesList[ geometry.id ]; + + if ( influences === undefined || influences.length !== length ) { + + // initialise list + + influences = []; + + for ( let i = 0; i < length; i ++ ) { + + influences[ i ] = [ i, 0 ]; + + } + + influencesList[ geometry.id ] = influences; + + } + + // Collect influences + + for ( let i = 0; i < length; i ++ ) { + + const influence = influences[ i ]; + + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; + + } + + influences.sort( absNumericalSort ); + + for ( let i = 0; i < 8; i ++ ) { + + if ( i < length && influences[ i ][ 1 ] ) { + + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + + } else { + + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; + + } + + } + + workInfluences.sort( numericalSort ); + + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < 8; i ++ ) { + + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; + + if ( index !== Number.MAX_SAFE_INTEGER && value ) { + + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + + } + + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + + } + + morphInfluences[ i ] = value; + morphInfluencesSum += value; + + } else { + + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + + geometry.deleteAttribute( 'morphTarget' + i ); + + } + + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + + geometry.deleteAttribute( 'morphNormal' + i ); + + } + + morphInfluences[ i ] = 0; + + } + + } + + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + + } + + } + + return { + + update: update + + }; + + } + + function WebGLObjects( gl, geometries, attributes, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, gl.ARRAY_BUFFER ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + + } + + /** + * 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 )'. + * + * + * 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, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + + const emptyTexture = /*@__PURE__*/ new Texture(); + const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); + const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); + const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + + // --- Utilities --- + + // Array Caches (provide typed arrays for temporary by size) + + const arrayCacheF32 = []; + const arrayCacheI32 = []; + + // Float32Array caches used for uploading Matrix uniforms + + const mat4array = new Float32Array( 16 ); + const mat3array = new Float32Array( 9 ); + const mat2array = new Float32Array( 4 ); + + // Flattening for arrays of vectors and matrices + + function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + + } + + function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + + } + + function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + + } + + // Texture unit allocation + + function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + + } + + // --- Setters --- + + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. + + // Single scalar + + function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + + } + + // Single float vector (from flat array or THREE.VectorN) + + function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + // Single matrix (from flat array or THREE.MatrixN) + + function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + + } + + function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + + } + + function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + + } + + // Single integer / boolean + + function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + + } + + // Single integer / boolean vector (from flat array or THREE.VectorN) + + function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + // Single unsigned integer + + function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + + } + + // Single unsigned integer vector (from flat array or THREE.VectorN) + + function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + + } + + + // Single texture (2D / Cube) + + function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2D( v || emptyTexture, unit ); + + } + + function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + + } + + function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + + } + + function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + + } + + // Helper to pick the right setter for the singular case + + function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + + } + + + // Array of scalars + + function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + + } + + // Array of vectors (from flat array or array of THREE.VectorN) + + function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + + } + + function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + + } + + function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + + } + + // Array of matrices (from flat array or array of THREE.MatrixN) + + function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + + } + + function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + + } + + function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + + } + + // Array of integer / boolean + + function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + + } + + // Array of integer / boolean vectors (from flat array) + + function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + + } + + function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + + } + + function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + + } + + // Array of unsigned integer + + function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + + } + + // Array of unsigned integer vectors (from flat array) + + function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + + } + + function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + + } + + function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + + } + + + // Array of textures (2D / 3D / Cube / 2DArray) + + function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + + } + + } + + function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + + } + + function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + + } + + function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + + } + + + // Helper to pick the right setter for a pure (bottom-level) array + + function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + + } + + // --- Uniform Classes --- + + class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + + } + + class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + + } + + class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + + } + + // --- Top-level --- + + // Parser - builds up the property tree from the path strings + + const RePathPart = /(\w+)(\])?(\[|\.)?/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. + + function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + + } + + function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + + } + + // Root Container + + class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + + } + + function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + + } + + let programIdCount = 0; + + function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + + } + + function getEncodingComponents( encoding ) { + + switch ( encoding ) { + + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); + return [ 'Linear', '( value )' ]; + + } + + } + + function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS ); + const errors = gl.getShaderInfoLog( shader ).trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + + } + + function getTexelEncodingFunction( functionName, encoding ) { + + const components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + + } + + function getToneMappingFunction( functionName, toneMapping ) { + + let toneMappingName; + + switch ( toneMapping ) { + + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + + } + + function generateExtensions( parameters ) { + + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + + } + + function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + + } + + function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2; + if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3; + if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + + } + + function filterEmptyLine( string ) { + + return string !== ''; + + } + + function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + + } + + function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + + } + + // Resolve Includes + + const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + + function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + + } + + function includeReplacer( match, include ) { + + const string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + return resolveIncludes( string ); + + } + + // Unroll Loops + + const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + + function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + + } + + function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + + } + + // + + function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + + } + + function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + + } + + function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + + } + + function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + + } + + function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + + } + + function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + + } + + function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + 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 && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( 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.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + + runnable = false; + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + + } + + let _id = 0; + + class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + + } + + class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + + } + + function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const isWebGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const vertexTextures = capabilities.vertexTextures; + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const useAlphaTest = material.alphaTest > 0; + const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; + + const parameters = { + + isWebGL2: isWebGL2, + + shaderID: shaderID, + shaderName: material.type, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: object.isInstancedMesh === true, + instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ), + map: !! material.map, + matcap: !! material.matcap, + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + + decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ), + + clearcoat: useClearcoat, + clearcoatMap: useClearcoat && !! material.clearcoatMap, + clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, + clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + specularIntensityMap: !! material.specularIntensityMap, + specularColorMap: !! material.specularColorMap, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: !! material.alphaMap, + alphaTest: useAlphaTest, + + gradientMap: !! material.gradientMap, + + sheen: material.sheen > 0, + sheenColorMap: !! material.sheenColorMap, + sheenRoughnessMap: !! material.sheenRoughnessMap, + + transmission: material.transmission > 0, + transmissionMap: !! material.transmissionMap, + thicknessMap: !! material.thicknessMap, + + combine: material.combine, + + vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: !! material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + + rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputEncoding ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputEncoding ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.combine ); + array.push( parameters.vertexUvs ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.map ) + _programLayers.enable( 4 ); + if ( parameters.matcap ) + _programLayers.enable( 5 ); + if ( parameters.envMap ) + _programLayers.enable( 6 ); + if ( parameters.lightMap ) + _programLayers.enable( 7 ); + if ( parameters.aoMap ) + _programLayers.enable( 8 ); + if ( parameters.emissiveMap ) + _programLayers.enable( 9 ); + if ( parameters.bumpMap ) + _programLayers.enable( 10 ); + if ( parameters.normalMap ) + _programLayers.enable( 11 ); + if ( parameters.objectSpaceNormalMap ) + _programLayers.enable( 12 ); + if ( parameters.tangentSpaceNormalMap ) + _programLayers.enable( 13 ); + if ( parameters.clearcoat ) + _programLayers.enable( 14 ); + if ( parameters.clearcoatMap ) + _programLayers.enable( 15 ); + if ( parameters.clearcoatRoughnessMap ) + _programLayers.enable( 16 ); + if ( parameters.clearcoatNormalMap ) + _programLayers.enable( 17 ); + if ( parameters.iridescence ) + _programLayers.enable( 18 ); + if ( parameters.iridescenceMap ) + _programLayers.enable( 19 ); + if ( parameters.iridescenceThicknessMap ) + _programLayers.enable( 20 ); + if ( parameters.displacementMap ) + _programLayers.enable( 21 ); + if ( parameters.specularMap ) + _programLayers.enable( 22 ); + if ( parameters.roughnessMap ) + _programLayers.enable( 23 ); + if ( parameters.metalnessMap ) + _programLayers.enable( 24 ); + if ( parameters.gradientMap ) + _programLayers.enable( 25 ); + if ( parameters.alphaMap ) + _programLayers.enable( 26 ); + if ( parameters.alphaTest ) + _programLayers.enable( 27 ); + if ( parameters.vertexColors ) + _programLayers.enable( 28 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 29 ); + if ( parameters.vertexUvs ) + _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.physicallyCorrectLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.specularIntensityMap ) + _programLayers.enable( 15 ); + if ( parameters.specularColorMap ) + _programLayers.enable( 16 ); + if ( parameters.transmission ) + _programLayers.enable( 17 ); + if ( parameters.transmissionMap ) + _programLayers.enable( 18 ); + if ( parameters.thicknessMap ) + _programLayers.enable( 19 ); + if ( parameters.sheen ) + _programLayers.enable( 20 ); + if ( parameters.sheenColorMap ) + _programLayers.enable( 21 ); + if ( parameters.sheenRoughnessMap ) + _programLayers.enable( 22 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 23 ); + if ( parameters.opaque ) + _programLayers.enable( 24 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + + } + + function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + + } + + function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + + } + + function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + + } + + + function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + + } + + function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + + } + + function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + + } + + function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + + } + + + + let nextVersion = 0; + + function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + + } + + function WebGLLights( extensions, capabilities ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + directionalLength: - 1, + pointLength: - 1, + spotLength: - 1, + rectAreaLength: - 1, + hemiLength: - 1, + + numDirectionalShadows: - 1, + numPointShadows: - 1, + numSpotShadows: - 1, + numSpotMaps: - 1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights, physicallyCorrectLights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + + if ( light.isAmbientLight ) { + + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( capabilities.isWebGL2 ) { + + // WebGL 2 + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + // WebGL 1 + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } else { + + console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' ); + + } + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { + + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + + } + + function WebGLRenderState( extensions, capabilities ) { + + const lights = new WebGLLights( extensions, capabilities ); + + const lightsArray = []; + const shadowsArray = []; + + function init() { + + lightsArray.length = 0; + shadowsArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function setupLights( physicallyCorrectLights ) { + + lights.setup( lightsArray, physicallyCorrectLights ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + + lights: lights + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow + }; + + } + + function WebGLRenderStates( extensions, capabilities ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + + } + + class MeshDepthMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDepthMaterial = true; + + this.type = 'MeshDepthMaterial'; + + this.depthPacking = BasicDepthPacking; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.depthPacking = source.depthPacking; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + return this; + + } + + } + + class MeshDistanceMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDistanceMaterial = true; + + this.type = 'MeshDistanceMaterial'; + + this.referencePosition = new Vector3(); + this.nearDistance = 1; + this.farDistance = 1000; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.referencePosition.copy( source.referencePosition ); + this.nearDistance = source.nearDistance; + this.farDistance = source.farDistance; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + return this; + + } + + } + + const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + + const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + + function WebGLShadowMap( _renderer, _objects, _capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = _capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide, [ TwoPassDoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + const currentRenderTarget = _renderer.getRenderTarget(); + const activeCubeFace = _renderer.getActiveCubeFace(); + const activeMipmapLevel = _renderer.getActiveMipmapLevel(); + + const _state = _renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + if ( shadow.map === null ) { + + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + '.shadowMap'; + + shadow.camera.updateProjectionMatrix(); + + } + + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + + const viewportCount = shadow.getViewportCount(); + + for ( let vp = 0; vp < viewportCount; vp ++ ) { + + const viewport = shadow.getViewport( vp ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + shadow.updateMatrices( light, vp ); + + _frustum = shadow.getFrustum(); + + renderObject( scene, camera, shadow.camera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + scope.needsUpdate = false; + + _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = _objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // vertical pass + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.mapPass ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + result.referencePosition.setFromMatrixPosition( light.matrixWorld ); + result.nearDistance = shadowCameraNear; + result.farDistance = shadowCameraFar; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = _objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + + } + + function WebGLState( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( gl.NEVER ); + break; + + case AlwaysDepth: + + gl.depthFunc( gl.ALWAYS ); + break; + + case LessDepth: + + gl.depthFunc( gl.LESS ); + break; + + case LessEqualDepth: + + gl.depthFunc( gl.LEQUAL ); + break; + + case EqualDepth: + + gl.depthFunc( gl.EQUAL ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( gl.GEQUAL ); + break; + + case GreaterDepth: + + gl.depthFunc( gl.GREATER ); + break; + + case NotEqualDepth: + + gl.depthFunc( gl.NOTEQUAL ); + break; + + default: + + gl.depthFunc( gl.LEQUAL ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + gl.clearDepth( depth ); + currentDepthClear = depth; + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( gl.STENCIL_TEST ); + + } else { + + disable( gl.STENCIL_TEST ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( gl.SCISSOR_BOX ); + const viewportParam = gl.getParameter( gl.VIEWPORT ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const 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 ); + + for ( let i = 0; i < count; i ++ ) { + + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } + + return texture; + + } + + const 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 ); + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + + if ( target === gl.DRAW_FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer; + + } + + if ( target === gl.FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0; + + needsUpdate = true; + + } + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.BACK ) { + + drawBuffers[ 0 ] = gl.BACK; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + if ( capabilities.isWebGL2 ) { + + gl.drawBuffers( drawBuffers ); + + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } + + } + + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: gl.FUNC_ADD, + [ SubtractEquation ]: gl.FUNC_SUBTRACT, + [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT + }; + + if ( isWebGL2 ) { + + equationToGL[ MinEquation ] = gl.MIN; + equationToGL[ MaxEquation ] = gl.MAX; + + } else { + + const extension = extensions.get( 'EXT_blend_minmax' ); + + if ( extension !== null ) { + + equationToGL[ MinEquation ] = extension.MIN_EXT; + equationToGL[ MaxEquation ] = extension.MAX_EXT; + + } + + } + + const factorToGL = { + [ ZeroFactor ]: gl.ZERO, + [ OneFactor ]: gl.ONE, + [ SrcColorFactor ]: gl.SRC_COLOR, + [ SrcAlphaFactor ]: gl.SRC_ALPHA, + [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE, + [ DstColorFactor ]: gl.DST_COLOR, + [ DstAlphaFactor ]: gl.DST_ALPHA, + [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR, + [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA, + [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR, + [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( gl.BLEND ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( gl.BLEND ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( gl.FUNC_ADD ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( gl.CULL_FACE ) + : enable( gl.CULL_FACE ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE ) + : disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( gl.CW ); + + } else { + + gl.frontFace( gl.CCW ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( gl.CULL_FACE ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( gl.BACK ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( gl.FRONT ); + + } else { + + gl.cullFace( gl.FRONT_AND_BACK ); + + } + + } + + } else { + + disable( gl.CULL_FACE ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( gl.POLYGON_OFFSET_FILL ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + gl.polygonOffset( factor, units ); + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + } + + } else { + + disable( gl.POLYGON_OFFSET_FILL ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( gl.SCISSOR_TEST ); + + } else { + + disable( gl.SCISSOR_TEST ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = gl.TEXTURE0 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( gl.BLEND ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.POLYGON_OFFSET_FILL ); + gl.disable( gl.SCISSOR_TEST ); + gl.disable( gl.STENCIL_TEST ); + gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ONE, gl.ZERO ); + gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( gl.LESS ); + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff ); + gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP ); + gl.clearStencil( 0 ); + + gl.cullFace( gl.BACK ); + gl.frontFace( gl.CCW ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( gl.TEXTURE0 ); + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + + if ( isWebGL2 === true ) { + + gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); + + } + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + // reset internals + + enabledCapabilities = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + + } + + function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _videoTextures = new WeakMap(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { + + let scale = 1; + + // handle case if texture exceeds max size + + if ( image.width > maxSize || image.height > maxSize ) { + + scale = maxSize / Math.max( image.width, image.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 || needsPowerOfTwo === true ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; + + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function isPowerOfTwo$1( image ) { + + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + + } + + function textureNeedsPowerOfTwo( texture ) { + + if ( isWebGL2 ) return false; + + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + + } + + function textureNeedsGenerateMipmaps( texture, supportsMips ) { + + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) { + + if ( isWebGL2 === false ) return glFormat; + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let internalFormat = glFormat; + + if ( glFormat === _gl.RED ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; + + } + + if ( glFormat === _gl.RG ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8; + + } + + if ( glFormat === _gl.RGBA ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4; + if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1; + + } + + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || + internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getMipLevels( texture, image, supportsMips ) { + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // Fallback filters for non-power-of-2 textures + + function filterFallback( f ) { + + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + + return _gl.NEAREST; + + } + + return _gl.LINEAR; + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; + + } + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + for ( let i = 0, il = texture.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( texture[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( texture[ i ] ); + + } + + } + + properties.remove( texture ); + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= maxTextures ) { + + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.encoding ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } + + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: _gl.REPEAT, + [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, + [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT + }; + + const filterToGL = { + [ NearestFilter ]: _gl.NEAREST, + [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, + [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, + + [ LinearFilter ]: _gl.LINEAR, + [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, + [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR + }; + + function setTextureParameters( textureType, texture, supportsMips ) { + + if ( supportsMips ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); + + } else { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _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.' ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + + 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.' ); + + } + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + + 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; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create Source <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = _gl.TEXTURE_2D; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY; + if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _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 ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ); + + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture ); + + setTextureParameters( textureType, texture, supportsMips ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); + + if ( texture.isDepthTexture ) { + + // populate depth texture with dummy data + + glInternalFormat = _gl.DEPTH_COMPONENT; + + if ( isWebGL2 ) { + + if ( texture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( texture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( texture.type === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } else { + + glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D + + } + + } else { + + if ( texture.type === FloatType ) { + + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + + } + + } + + // validation checks for WebGL 1 + + if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); + + } + + } + + if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { + + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = _gl.DEPTH_STENCIL; + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); + + } + + } + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( 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 + + if ( mipmaps.length > 0 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } else { + + state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else { + + // regular Texture (image, video, canvas) + + // 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 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + _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 ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); + + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) { + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const renderTargetProperties = properties.get( renderTarget ); + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) { + + state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753 + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + + let glInternalFormat = _gl.DEPTH_COMPONENT16; + + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { + + const depthTexture = renderTarget.depthTexture; + + if ( depthTexture && depthTexture.isDepthTexture ) { + + if ( depthTexture.type === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( depthTexture.type === UnsignedIntType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } + + } + + const samples = getRenderTargetSamples( renderTarget ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + + } + + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + + } else { + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { + + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + + } + + // 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; + + } + + setTexture2D( renderTarget.depthTexture, 0 ); + + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'Unknown depthTexture format' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } + + } else { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + if ( isMultipleRenderTargets ) { + + if ( capabilities.drawBuffers ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); + + } + + } + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = isMultipleRenderTargets ? texture : [ texture ]; + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); + + for ( let i = 0; i < 6; i ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D ); + + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { + + generateMipmap( _gl.TEXTURE_2D ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + if ( isWebGL2 ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } else { + + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); + + } + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType ); + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); + + } + + } + + } + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i ); + + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; + if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] ); + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); + + if ( supportsInvalidateFramebuffer ) { + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray ); + + } + + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const encoding = texture.encoding; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image; + + if ( encoding !== LinearEncoding ) { + + // sRGB + + if ( encoding === sRGBEncoding ) { + + if ( isWebGL2 === false ) { + + // in WebGL 1, try to use EXT_sRGB extension and unsized formats + + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { + + texture.format = _SRGBAFormat; + + // it's not possible to generate mips in WebGL 1 with this extension + + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; + + } else { + + // slow fallback (CPU decode) + + image = ImageUtils.sRGBToLinear( image ); + + } + + } else { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } + + } else { + + console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding ); + + } + + } + + return image; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + + } + + function WebGLUtils( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function convert( p, encoding = null ) { + + let extension; + + 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 === 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; + + if ( p === HalfFloatType ) { + + if ( isWebGL2 ) return gl.HALF_FLOAT; + + extension = extensions.get( 'OES_texture_half_float' ); + + if ( extension !== null ) { + + return extension.HALF_FLOAT_OES; + + } else { + + return null; + + } + + } + + if ( p === AlphaFormat ) return gl.ALPHA; + 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 === DepthStencilFormat ) return gl.DEPTH_STENCIL; + + // WebGL 1 sRGB fallback + + if ( p === _SRGBAFormat ) { + + extension = extensions.get( 'EXT_sRGB' ); + + if ( extension !== null ) { + + return extension.SRGB_ALPHA_EXT; + + } else { + + return null; + + } + + } + + // WebGL2 formats. + + if ( p === RedFormat ) return gl.RED; + if ( p === RedIntegerFormat ) return gl.RED_INTEGER; + if ( p === RGFormat ) return gl.RG; + if ( p === RGIntegerFormat ) return gl.RG_INTEGER; + if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( encoding === sRGBEncoding ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + 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; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + 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; + + } else { + + return null; + + } + + } + + // ETC1 + + if ( p === RGB_ETC1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + + if ( extension !== null ) { + + return extension.COMPRESSED_RGB_ETC1_WEBGL; + + } else { + + return null; + + } + + } + + // ETC2 + + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) { + + if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8; + + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { + + return extension.UNSIGNED_INT_24_8_WEBGL; + + } else { + + return null; + + } + + } + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + + } + + class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; + + } + + } + + class Group extends Object3D { + + constructor() { + + super(); + + this.isGroup = true; + + this.type = 'Group'; + + } + + } + + const _moveEvent = { type: 'move' }; + + class WebXRController { + + constructor() { + + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + + } + + return this._hand; + + } + + getTargetRaySpace() { + + if ( this._targetRay === null ) { + + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + + } + + return this._targetRay; + + } + + getGripSpace() { + + if ( this._grip === null ) { + + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + + } + + return this._grip; + + } + + dispatchEvent( event ) { + + if ( this._targetRay !== null ) { + + this._targetRay.dispatchEvent( event ); + + } + + if ( this._grip !== null ) { + + this._grip.dispatchEvent( event ); + + } + + if ( this._hand !== null ) { + + this._hand.dispatchEvent( event ); + + } + + return this; + + } + + connect( inputSource ) { + + if ( inputSource && inputSource.hand ) { + + const hand = this._hand; + + if ( hand ) { + + for ( const inputjoint of inputSource.hand.values() ) { + + // Initialize hand with joints when connected + this._getHandJoint( hand, inputjoint ); + + } + + } + + } + + this.dispatchEvent( { type: 'connected', data: inputSource } ); + + return this; + + } + + disconnect( inputSource ) { + + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + + if ( this._targetRay !== null ) { + + this._targetRay.visible = false; + + } + + if ( this._grip !== null ) { + + this._grip.visible = false; + + } + + if ( this._hand !== null ) { + + this._hand.visible = false; + + } + + return this; + + } + + update( inputSource, frame, referenceSpace ) { + + let inputPose = null; + let gripPose = null; + let handPose = null; + + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + + if ( hand && inputSource.hand ) { + + handPose = true; + + for ( const inputjoint of inputSource.hand.values() ) { + + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + + // The transform of this joint will be updated with the joint pose on each frame + const joint = this._getHandJoint( hand, inputjoint ); + + if ( jointPose !== null ) { + + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.jointRadius = jointPose.radius; + + } + + joint.visible = jointPose !== null; + + } + + // Custom events + + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); + + const distanceToPinch = 0.02; + const threshold = 0.005; + + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); + + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); + + } + + } else { + + if ( grip !== null && inputSource.gripSpace ) { + + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + + if ( gripPose !== null ) { + + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + + if ( gripPose.linearVelocity ) { + + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); + + } else { + + grip.hasLinearVelocity = false; + + } + + if ( gripPose.angularVelocity ) { + + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); + + } else { + + grip.hasAngularVelocity = false; + + } + + } + + } + + } + + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + + } + + if ( targetRay !== null ) { + + targetRay.visible = ( inputPose !== null ); + + } + + if ( grip !== null ) { + + grip.visible = ( gripPose !== null ); + + } + + if ( hand !== null ) { + + hand.visible = ( handPose !== null ); + + } + + return this; + + } + + // private method + + _getHandJoint( hand, inputjoint ) { + + if ( hand.joints[ inputjoint.jointName ] === undefined ) { + + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + + hand.add( joint ); + + } + + return hand.joints[ inputjoint.jointName ]; + + } + + } + + class DepthTexture extends Texture { + + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + + format = format !== undefined ? format : DepthFormat; + + if ( format !== DepthFormat && format !== DepthStencilFormat ) { + + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + + } + + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isDepthTexture = true; + + this.image = { width: width, height: height }; + + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + + this.flipY = false; + this.generateMipmaps = false; + + } + + + } + + class WebXRManager extends EventDispatcher { + + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + const planes = new Set(); + const planesLastChangedTimes = new Map(); + + // + + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + this.cameraAutoUpdate = true; + this.enabled = false; + + this.isPresenting = false; + + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + this.getBinding = function () { + + return glBinding; + + }; + + this.getFrame = function () { + + return xrFrame; + + }; + + this.getSession = function () { + + return session; + + }; + + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { + + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + encoding: renderer.outputEncoding, + stencilBuffer: attributes.stencil + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = new XRWebGLBinding( session, gl ); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + encoding: renderer.outputEncoding, + samples: attributes.antialias ? 4 : 0 + } ); + + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + // Set foveation to maximum. + this.setFoveation( 1.0 ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; + + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); + + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; + + } + + const parent = camera.parent; + const cameras = cameraVR.cameras; + + updateCamera( cameraVR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale ); + + // update user camera and its children + + camera.matrix.copy( cameraVR.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + + const children = camera.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].updateMatrixWorld( true ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraVR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + }; + + this.getCamera = function () { + + return cameraVR; + + }; + + this.getFoveation = function () { + + if ( glProjLayer !== null ) { + + return glProjLayer.fixedFoveation; + + } + + if ( glBaseLayer !== null ) { + + return glBaseLayer.fixedFoveation; + + } + + return undefined; + + }; + + this.setFoveation = function ( foveation ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = foveation; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = foveation; + + } + + }; + + this.getPlanes = function () { + + return planes; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraVRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraVR's camera list + + if ( views.length !== cameraVR.cameras.length ) { + + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraVR.matrix.copy( camera.matrix ); + + } + + if ( cameraVRNeedsUpdate === true ) { + + cameraVR.cameras.push( camera ); + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } ); + + let planesToRemove = null; + + for ( const plane of planes ) { + + if ( ! frame.detectedPlanes.has( plane ) ) { + + if ( planesToRemove === null ) { + + planesToRemove = []; + + } + + planesToRemove.push( plane ); + + } + + } + + if ( planesToRemove !== null ) { + + for ( const plane of planesToRemove ) { + + planes.delete( plane ); + planesLastChangedTimes.delete( plane ); + scope.dispatchEvent( { type: 'planeremoved', data: plane } ); + + } + + } + + for ( const plane of frame.detectedPlanes ) { + + if ( ! planes.has( plane ) ) { + + planes.add( plane ); + planesLastChangedTimes.set( plane, frame.lastChangedTime ); + scope.dispatchEvent( { type: 'planeadded', data: plane } ); + + } else { + + const lastKnownTime = planesLastChangedTimes.get( plane ); + + if ( plane.lastChangedTime > lastKnownTime ) { + + planesLastChangedTimes.set( plane, plane.lastChangedTime ); + scope.dispatchEvent( { type: 'planechanged', data: plane } ); + + } + + } + + } + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + + } + + function WebGLMaterials( renderer, properties ) { + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1; + + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. displacementMap map + // 4. normal map + // 5. bump map + // 6. roughnessMap map + // 7. metalnessMap map + // 8. alphaMap map + // 9. emissiveMap map + // 10. clearcoat map + // 11. clearcoat normal map + // 12. clearcoat roughnessMap map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.specularMap ) { + + uvScaleMap = material.specularMap; + + } else if ( material.displacementMap ) { + + uvScaleMap = material.displacementMap; + + } else if ( material.normalMap ) { + + uvScaleMap = material.normalMap; + + } else if ( material.bumpMap ) { + + uvScaleMap = material.bumpMap; + + } else if ( material.roughnessMap ) { + + uvScaleMap = material.roughnessMap; + + } else if ( material.metalnessMap ) { + + uvScaleMap = material.metalnessMap; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } else if ( material.emissiveMap ) { + + uvScaleMap = material.emissiveMap; + + } else if ( material.clearcoatMap ) { + + uvScaleMap = material.clearcoatMap; + + } else if ( material.clearcoatNormalMap ) { + + uvScaleMap = material.clearcoatNormalMap; + + } else if ( material.clearcoatRoughnessMap ) { + + uvScaleMap = material.clearcoatRoughnessMap; + + } else if ( material.iridescenceMap ) { + + uvScaleMap = material.iridescenceMap; + + } else if ( material.iridescenceThicknessMap ) { + + uvScaleMap = material.iridescenceThicknessMap; + + } else if ( material.specularIntensityMap ) { + + uvScaleMap = material.specularIntensityMap; + + } else if ( material.specularColorMap ) { + + uvScaleMap = material.specularColorMap; + + } else if ( material.transmissionMap ) { + + uvScaleMap = material.transmissionMap; + + } else if ( material.thicknessMap ) { + + uvScaleMap = material.thicknessMap; + + } else if ( material.sheenColorMap ) { + + uvScaleMap = material.sheenColorMap; + + } else if ( material.sheenRoughnessMap ) { + + uvScaleMap = material.sheenRoughnessMap; + + } + + if ( uvScaleMap !== undefined ) { + + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { + + uvScaleMap = uvScaleMap.texture; + + } + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map + + let uv2ScaleMap; + + if ( material.aoMap ) { + + uv2ScaleMap = material.aoMap; + + } else if ( material.lightMap ) { + + uv2ScaleMap = material.lightMap; + + } + + if ( uv2ScaleMap !== undefined ) { + + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { + + uv2ScaleMap = uv2ScaleMap.texture; + + } + + if ( uv2ScaleMap.matrixAutoUpdate === true ) { + + uv2ScaleMap.updateMatrix(); + + } + + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + } + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + } + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + + } + + function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + gl.bufferData( gl.UNIFORM_BUFFER, size, usage ); + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniform = uniforms[ i ]; + + // partly update the buffer if necessary + + if ( hasUniformChanged( uniform, i, cache ) === true ) { + + const offset = uniform.__offset; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + let arrayOffset = 0; + + for ( let i = 0; i < values.length; i ++ ) { + + const value = values[ i ]; + + const info = getUniformSize( value ); + + if ( typeof value === 'number' ) { + + uniform.__data[ 0 ] = value; + gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data ); + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + uniform.__data[ 0 ] = value.elements[ 0 ]; + uniform.__data[ 1 ] = value.elements[ 1 ]; + uniform.__data[ 2 ] = value.elements[ 2 ]; + uniform.__data[ 3 ] = value.elements[ 0 ]; + uniform.__data[ 4 ] = value.elements[ 3 ]; + uniform.__data[ 5 ] = value.elements[ 4 ]; + uniform.__data[ 6 ] = value.elements[ 5 ]; + uniform.__data[ 7 ] = value.elements[ 0 ]; + uniform.__data[ 8 ] = value.elements[ 6 ]; + uniform.__data[ 9 ] = value.elements[ 7 ]; + uniform.__data[ 10 ] = value.elements[ 8 ]; + uniform.__data[ 11 ] = value.elements[ 0 ]; + + } else { + + value.toArray( uniform.__data, arrayOffset ); + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data ); + + } + + } + + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + + } + + function hasUniformChanged( uniform, index, cache ) { + + const value = uniform.value; + + if ( cache[ index ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' ) { + + cache[ index ] = value; + + } else { + + const values = Array.isArray( value ) ? value : [ value ]; + + const tempValues = []; + + for ( let i = 0; i < values.length; i ++ ) { + + tempValues.push( values[ i ].clone() ); + + } + + cache[ index ] = tempValues; + + } + + return true; + + } else { + + // compare current value with cached entry + + if ( typeof value === 'number' ) { + + if ( cache[ index ] !== value ) { + + cache[ index ] = value; + return true; + + } + + } else { + + const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ]; + const values = Array.isArray( value ) ? value : [ value ]; + + for ( let i = 0; i < cachedObjects.length; i ++ ) { + + const cachedObject = cachedObjects[ i ]; + + if ( cachedObject.equals( values[ i ] ) === false ) { + + cachedObject.copy( values[ i ] ); + return true; + + } + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniform = uniforms[ i ]; + + const infos = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let j = 0, jl = values.length; j < jl; j ++ ) { + + const value = values[ j ]; + + const info = getUniformSize( value ); + + infos.boundary += info.boundary; + infos.storage += info.storage; + + } + + // the following two properties will be used for partial buffer updates + + uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // + + if ( i > 0 ) { + + chunkOffset = offset % chunkSize; + + const remainingSizeInChunk = chunkSize - chunkOffset; + + // check for chunk overflow + + if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) { + + // add padding and adjust offset + + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; + + } + + } + + offset += infos.storage; + + } + + // ensure correct final padding + + chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' ) { + + // float/int + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + + } + + function createCanvasElement() { + + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; + + } + + function WebGLRenderer( parameters = {} ) { + + this.isWebGLRenderer = true; + + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), + _context = parameters.context !== undefined ? parameters.context : null, + + _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, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + + let _alpha; + + if ( _context !== null ) { + + _alpha = _context.getContextAttributes().alpha; + + } else { + + _alpha = parameters.alpha !== undefined ? parameters.alpha : false; + + } + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // public properties + + this.domElement = _canvas; + + // Debug configuration container + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; + + // clearing + + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + + // scene graph + + this.sortObjects = true; + + // user-defined clipping + + this.clippingPlanes = []; + this.localClippingEnabled = false; + + // physically based shading + + this.outputEncoding = LinearEncoding; + + // physical lights + + this.physicallyCorrectLights = false; + + // tone mapping + + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + + // internal state cache + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + // + + let _width = _canvas.width; + let _height = _canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // transmission + + let _transmissionRenderTarget = null; + + // camera matrices cache + + const _projScreenMatrix = new Matrix4(); + + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = _context; + + function getContext( contextNames, contextAttributes ) { + + for ( let i = 0; i < contextNames.length; i ++ ) { + + const contextName = contextNames[ i ]; + const context = _canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; + + } + + return null; + + } + + try { + + const contextAttributes = { + alpha: true, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + + if ( _this.isWebGL1Renderer === true ) { + + contextNames.shift(); + + } + + _gl = getContext( contextNames, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextNames ) ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'Error creating WebGL context.' ); + + } + + } + + } + + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + + }; + + } + + } catch ( error ) { + + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + + extensions.init( capabilities ); + + utils = new WebGLUtils( _gl, extensions, capabilities ); + + state = new WebGLState( _gl, extensions, capabilities ); + + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + + info.programs = programCache.programs; + + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + + } + + initGLContext(); + + // xr + + const xr = new WebXRManager( _this, _gl ); + + this.xr = xr; + + // API + + this.getContext = function () { + + return _gl; + + }; + + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + this.setSize = function ( width, height, updateStyle ) { + + if ( xr.isPresenting ) { + + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle !== false ) { + + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; + + } + + this.setViewport( 0, 0, width, height ); + + }; + + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissorTest = function () { + + return _scissorTest; + + }; + + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + this.setClearColor = function () { + + background.setClearColor.apply( background, arguments ); + + }; + + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + this.setClearAlpha = function () { + + background.setClearAlpha.apply( background, arguments ); + + }; + + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + + _gl.clear( bits ); + + }; + + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + // + + this.dispose = function () { + + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + if ( _transmissionRenderTarget ) { + + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; + + } + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + console.log( 'THREE.WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + console.log( 'THREE.WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); + + } else { + + renderer.setMode( _gl.TRIANGLES ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( _gl.LINES ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( _gl.LINE_LOOP ); + + } else { + + renderer.setMode( _gl.LINE_STRIP ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( _gl.POINTS ); + + } else if ( object.isSprite ) { + + renderer.setMode( _gl.TRIANGLES ); + + } + + if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + this.compile = function ( scene, camera ) { + + function prepare( material, scene, object ) { + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = TwoPassDoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + scene.traverse( function ( object ) { + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepare( material2, scene, object ); + + } + + } else { + + prepare( material, scene, object ); + + } + + } + + } ); + + renderStateStack.pop(); + currentRenderState = null; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + // + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + if ( this.info.autoReset === true ) this.info.reset(); + + // + + background.render( currentRenderList, scene ); + + // render scene + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + renderScene( currentRenderList, scene, camera ); + + } + + // + + if ( _currentRenderTarget !== null ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( object.isSkinnedMesh ) { + + // update skeleton only once in a frame + + if ( object.skeleton.frame !== info.render.frame ) { + + object.skeleton.update(); + object.skeleton.frame = info.render.frame; + + } + + } + + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, scene, camera ) { + + const isWebGL2 = capabilities.isWebGL2; + + if ( _transmissionRenderTarget === null ) { + + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 + } ); + + } + + _this.getDrawingBufferSize( _vector2 ); + + if ( isWebGL2 ) { + + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); + + } else { + + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); + + } + + // + + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + _this.clear(); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + renderObjects( opaqueObjects, scene, camera ); + + _this.toneMapping = currentToneMapping; + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + _this.setRenderTarget( currentRenderTarget ); + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = TwoPassDoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + material.onBuild( object, parameters, _this ); + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputEncoding = parameters.outputEncoding; + materialProperties.instancing = parameters.instancing; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent; + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const 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, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputEncoding !== encoding ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // 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: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( capabilities.floatVertexTextures ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + + } else { + + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); + + } + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { + + morphtargets.update( object, geometry, material, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { + + m_uniforms.envMap.value = envMap; + + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // 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 + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + if ( capabilities.isWebGL2 ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); + + } + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; + + if ( renderTargetProperties.__hasExternalTextures ) { + + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { + + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; + + } + + } + + } + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + useDefaultFramebuffer = false; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + isCube = true; + + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + framebuffer = __webglFramebuffer; + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + + } + + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings + + }; + + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + try { + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + } + + } + + }; + + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + + textures.setTexture2D( dstTexture, 0 ); + + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + + } else { + + if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + + } else { + + _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image ); + + } + + } + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + + if ( _this.isWebGL1Renderer ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; + + } + + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_3D; + + } else if ( dstTexture.isDataArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D_ARRAY; + + } else { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; + + } + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH ); + const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT ); + const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS ); + const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES ); + + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z ); + + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); + + } else { + + if ( srcTexture.isCompressedArrayTexture ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); + + } + + } + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + + state.unbindTexture(); + + }; + + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + class WebGL1Renderer extends WebGLRenderer {} + + WebGL1Renderer.prototype.isWebGL1Renderer = true; + + class FogExp2 { + + constructor( color, density = 0.00025 ) { + + this.isFogExp2 = true; + + this.name = ''; + + this.color = new Color( color ); + this.density = density; + + } + + clone() { + + return new FogExp2( this.color, this.density ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; + + } + + } + + class Fog { + + constructor( color, near = 1, far = 1000 ) { + + this.isFog = true; + + this.name = ''; + + this.color = new Color( color ); + + this.near = near; + this.far = far; + + } + + clone() { + + return new Fog( this.color, this.near, this.far ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; + + } + + } + + class Scene extends Object3D { + + constructor() { + + super(); + + this.isScene = true; + + this.type = 'Scene'; + + this.background = null; + this.environment = null; + this.fog = null; + + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + + this.overrideMaterial = null; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; + if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + + return data; + + } + + // @deprecated + + get autoUpdate() { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + return this.matrixWorldAutoUpdate; + + } + + set autoUpdate( value ) { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + this.matrixWorldAutoUpdate = value; + + } + + } + + class InterleavedBuffer { + + constructor( array, stride ) { + + this.isInterleavedBuffer = true; + + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + this.uuid = generateUUID(); + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.stride; + index2 *= attribute.stride; + + for ( let i = 0, l = this.stride; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + set( value, offset = 0 ) { + + this.array.set( value, offset ); + + return this; + + } + + clone( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + + } + + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); + + return ib; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + toJSON( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + // generate UUID for array buffer if necessary + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); + + } + + // + + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + + } + + } + + const _vector$6 = /*@__PURE__*/ new Vector3(); + + class InterleavedBufferAttribute { + + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + + this.isInterleavedBufferAttribute = true; + + this.name = ''; + + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + + this.normalized = normalized; + + } + + get count() { + + return this.data.count; + + } + + get array() { + + return this.data.array; + + } + + set needsUpdate( value ) { + + this.data.needsUpdate = value; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.data.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyMatrix4( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.transformDirection( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.data.array[ index * this.data.stride + this.offset ] = x; + + return this; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + + return this; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + + return this; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + + return this; + + } + + getX( index ) { + + let x = this.data.array[ index * this.data.stride + this.offset ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + getY( index ) { + + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + getZ( index ) { + + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + getW( index ) { + + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setXY( index, x, y ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; + + return this; + + } + + clone( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + + } else { + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + + } + + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + + } + + } + + toJSON( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + // de-interleave data and save it as an ordinary buffer attribute for now + + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; + + } else { + + // save as true interleaved attribute + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + + } + + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + + } + + } + + } + + class SpriteMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isSpriteMaterial = true; + + this.type = 'SpriteMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.rotation = 0; + + this.sizeAttenuation = true; + + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.rotation = source.rotation; + + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + + } + + let _geometry; + + const _intersectPoint = /*@__PURE__*/ new Vector3(); + const _worldScale = /*@__PURE__*/ new Vector3(); + const _mvPosition = /*@__PURE__*/ new Vector3(); + + const _alignedPosition = /*@__PURE__*/ new Vector2(); + const _rotatedPosition = /*@__PURE__*/ new Vector2(); + const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + + const _vA = /*@__PURE__*/ new Vector3(); + const _vB = /*@__PURE__*/ new Vector3(); + const _vC = /*@__PURE__*/ new Vector3(); + + const _uvA = /*@__PURE__*/ new Vector2(); + const _uvB = /*@__PURE__*/ new Vector2(); + const _uvC = /*@__PURE__*/ new Vector2(); + + class Sprite extends Object3D { + + constructor( material ) { + + super(); + + this.isSprite = true; + + this.type = 'Sprite'; + + if ( _geometry === undefined ) { + + _geometry = new BufferGeometry(); + + const float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); + + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + + } + + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + + this.center = new Vector2( 0.5, 0.5 ); + + } + + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + + } + + _worldScale.setFromMatrixScale( this.matrixWorld ); + + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + + _worldScale.multiplyScalar( - _mvPosition.z ); + + } + + const rotation = this.material.rotation; + let sin, cos; + + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); + + } + + const center = this.center; + + transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); + + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint ); + + if ( intersect === null ) { + + // check second triangle + transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 1 ); + + intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint ); + if ( intersect === null ) { + + return; + + } + + } + + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.center !== undefined ) this.center.copy( source.center ); + + this.material = source.material; + + return this; + + } + + } + + function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + + // to check if rotation is not zero + if ( sin !== undefined ) { + + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + + } else { + + _rotatedPosition.copy( _alignedPosition ); + + } + + + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); + + } + + const _v1$2 = /*@__PURE__*/ new Vector3(); + const _v2$1 = /*@__PURE__*/ new Vector3(); + + class LOD extends Object3D { + + constructor() { + + super(); + + this._currentLevel = 0; + + this.type = 'LOD'; + + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true, + } + } ); + + this.autoUpdate = true; + + } + + copy( source ) { + + super.copy( source, false ); + + const levels = source.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + this.addLevel( level.object.clone(), level.distance, level.hysteresis ); + + } + + this.autoUpdate = source.autoUpdate; + + return this; + + } + + addLevel( object, distance = 0, hysteresis = 0 ) { + + distance = Math.abs( distance ); + + const levels = this.levels; + + let l; + + for ( l = 0; l < levels.length; l ++ ) { + + if ( distance < levels[ l ].distance ) { + + break; + + } + + } + + levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } ); + + this.add( object ); + + return this; + + } + + getCurrentLevel() { + + return this._currentLevel; + + } + + + + getObjectForDistance( distance ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance < levelDistance ) { + + break; + + } + + } + + return levels[ i - 1 ].object; + + } + + return null; + + } + + raycast( raycaster, intersects ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + _v1$2.setFromMatrixPosition( this.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); + + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + + } + + } + + update( camera ) { + + const levels = this.levels; + + if ( levels.length > 1 ) { + + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); + + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; + + levels[ 0 ].object.visible = true; + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance >= levelDistance ) { + + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; + + } else { + + break; + + } + + } + + this._currentLevel = i - 1; + + for ( ; i < l; i ++ ) { + + levels[ i ].object.visible = false; + + } + + } + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.autoUpdate === false ) data.object.autoUpdate = false; + + data.object.levels = []; + + const levels = this.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + } ); + + } + + return data; + + } + + } + + const _basePosition = /*@__PURE__*/ new Vector3(); + + const _skinIndex = /*@__PURE__*/ new Vector4(); + const _skinWeight = /*@__PURE__*/ new Vector4(); + + const _vector$5 = /*@__PURE__*/ new Vector3(); + const _matrix = /*@__PURE__*/ new Matrix4(); + + class SkinnedMesh extends Mesh { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isSkinnedMesh = true; + + this.type = 'SkinnedMesh'; + + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); + + this.skeleton = source.skeleton; + + return this; + + } + + bind( skeleton, bindMatrix ) { + + this.skeleton = skeleton; + + if ( bindMatrix === undefined ) { + + this.updateMatrixWorld( true ); + + this.skeleton.calculateInverses(); + + bindMatrix = this.matrixWorld; + + } + + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); + + } + + pose() { + + this.skeleton.pose(); + + } + + normalizeSkinWeights() { + + const vector = new Vector4(); + + const skinWeight = this.geometry.attributes.skinWeight; + + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + + vector.fromBufferAttribute( skinWeight, i ); + + const scale = 1.0 / vector.manhattanLength(); + + if ( scale !== Infinity ) { + + vector.multiplyScalar( scale ); + + } else { + + vector.set( 1, 0, 0, 0 ); // do something reasonable + + } + + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + + } + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.bindMode === 'attached' ) { + + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + + } else if ( this.bindMode === 'detached' ) { + + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + + } else { + + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + + } + + } + + boneTransform( index, target ) { + + const skeleton = this.skeleton; + const geometry = this.geometry; + + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + + _basePosition.copy( target ).applyMatrix4( this.bindMatrix ); + + target.set( 0, 0, 0 ); + + for ( let i = 0; i < 4; i ++ ) { + + const weight = _skinWeight.getComponent( i ); + + if ( weight !== 0 ) { + + const boneIndex = _skinIndex.getComponent( i ); + + _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + + target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight ); + + } + + } + + return target.applyMatrix4( this.bindMatrixInverse ); + + } + + } + + class Bone extends Object3D { + + constructor() { + + super(); + + this.isBone = true; + + this.type = 'Bone'; + + } + + } + + class DataTexture extends Texture { + + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isDataTexture = true; + + this.image = { data: data, width: width, height: height }; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + + } + + const _offsetMatrix = /*@__PURE__*/ new Matrix4(); + const _identityMatrix = /*@__PURE__*/ new Matrix4(); + + class Skeleton { + + constructor( bones = [], boneInverses = [] ) { + + this.uuid = generateUUID(); + + this.bones = bones.slice( 0 ); + this.boneInverses = boneInverses; + this.boneMatrices = null; + + this.boneTexture = null; + this.boneTextureSize = 0; + + this.frame = - 1; + + this.init(); + + } + + init() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + + this.boneMatrices = new Float32Array( bones.length * 16 ); + + // calculate inverse bone matrices if necessary + + if ( boneInverses.length === 0 ) { + + this.calculateInverses(); + + } else { + + // handle special case + + if ( bones.length !== boneInverses.length ) { + + console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + + this.boneInverses = []; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + this.boneInverses.push( new Matrix4() ); + + } + + } + + } + + } + + calculateInverses() { + + this.boneInverses.length = 0; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const inverse = new Matrix4(); + + if ( this.bones[ i ] ) { + + inverse.copy( this.bones[ i ].matrixWorld ).invert(); + + } + + this.boneInverses.push( inverse ); + + } + + } + + pose() { + + // recover the bind-time world matrices + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + + } + + } + + // compute the local matrices, positions, rotations and scales + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + if ( bone.parent && bone.parent.isBone ) { + + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); + + } else { + + bone.matrix.copy( bone.matrixWorld ); + + } + + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + + } + + } + + } + + update() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + + // flatten bone matrices to array + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + // compute the offset between the current and the original transform + + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); + + } + + if ( boneTexture !== null ) { + + boneTexture.needsUpdate = true; + + } + + } + + clone() { + + return new Skeleton( this.bones, this.boneInverses ); + + } + + computeBoneTexture() { + + // 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) + + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); + + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values + + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; + + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + this.boneTextureSize = size; + + return this; + + } + + getBoneByName( name ) { + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone.name === name ) { + + return bone; + + } + + } + + return undefined; + + } + + dispose( ) { + + if ( this.boneTexture !== null ) { + + this.boneTexture.dispose(); + + this.boneTexture = null; + + } + + } + + fromJSON( json, bones ) { + + this.uuid = json.uuid; + + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; + + if ( bone === undefined ) { + + console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); + + } + + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + + } + + this.init(); + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; + + data.uuid = this.uuid; + + const bones = this.bones; + const boneInverses = this.boneInverses; + + for ( let i = 0, l = bones.length; i < l; i ++ ) { + + const bone = bones[ i ]; + data.bones.push( bone.uuid ); + + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); + + } + + return data; + + } + + } + + class InstancedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { + + super( array, itemSize, normalized ); + + this.isInstancedBufferAttribute = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.meshPerAttribute = this.meshPerAttribute; + + data.isInstancedBufferAttribute = true; + + return data; + + } + + } + + const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); + const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); + + const _instanceIntersects = []; + + const _identity = /*@__PURE__*/ new Matrix4(); + const _mesh = /*@__PURE__*/ new Mesh(); + + class InstancedMesh extends Mesh { + + constructor( geometry, material, count ) { + + super( geometry, material ); + + this.isInstancedMesh = true; + + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; + + this.count = count; + + this.frustumCulled = false; + + for ( let i = 0; i < count; i ++ ) { + + this.setMatrixAt( i, _identity ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.instanceMatrix.copy( source.instanceMatrix ); + + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + + this.count = source.count; + + return this; + + } + + getColorAt( index, color ) { + + color.fromArray( this.instanceColor.array, index * 3 ); + + } + + getMatrixAt( index, matrix ) { + + matrix.fromArray( this.instanceMatrix.array, index * 16 ); + + } + + raycast( raycaster, intersects ) { + + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + + _mesh.geometry = this.geometry; + _mesh.material = this.material; + + if ( _mesh.material === undefined ) return; + + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + + // calculate the world matrix for each instance + + this.getMatrixAt( instanceId, _instanceLocalMatrix ); + + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + + // the mesh represents this single instance + + _mesh.matrixWorld = _instanceWorldMatrix; + + _mesh.raycast( raycaster, _instanceIntersects ); + + // process the result of raycast + + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); + + } + + _instanceIntersects.length = 0; + + } + + } + + setColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); + + } + + color.toArray( this.instanceColor.array, index * 3 ); + + } + + setMatrixAt( index, matrix ) { + + matrix.toArray( this.instanceMatrix.array, index * 16 ); + + } + + updateMorphTargets() { + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + } + + class LineBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isLineBasicMaterial = true; + + this.type = 'LineBasicMaterial'; + + this.color = new Color( 0xffffff ); + + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + + this.fog = source.fog; + + return this; + + } + + } + + const _start$1 = /*@__PURE__*/ new Vector3(); + const _end$1 = /*@__PURE__*/ new Vector3(); + const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); + const _ray$1 = /*@__PURE__*/ new Ray(); + const _sphere$1 = /*@__PURE__*/ new Sphere(); + + class Line extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + + super(); + + this.isLine = true; + + this.type = 'Line'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; + + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; + + // + + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + } + + const _start = /*@__PURE__*/ new Vector3(); + const _end = /*@__PURE__*/ new Vector3(); + + class LineSegments extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineSegments = true; + + this.type = 'LineSegments'; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); + + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + } + + class LineLoop extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineLoop = true; + + this.type = 'LineLoop'; + + } + + } + + class PointsMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isPointsMaterial = true; + + this.type = 'PointsMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.size = 1; + this.sizeAttenuation = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + + } + + const _inverseMatrix = /*@__PURE__*/ new Matrix4(); + const _ray = /*@__PURE__*/ new Ray(); + const _sphere = /*@__PURE__*/ new Sphere(); + const _position$2 = /*@__PURE__*/ new Vector3(); + + class Points extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + + super(); + + this.isPoints = true; + + this.type = 'Points'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i ++ ) { + + const a = index.getX( i ); + + _position$2.fromBufferAttribute( positionAttribute, a ); + + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end; i < l; i ++ ) { + + _position$2.fromBufferAttribute( positionAttribute, i ); + + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + } + + function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); + + if ( rayPointDistanceSq < localThresholdSq ) { + + const intersectPoint = new Vector3(); + + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object + + } ); + + } + + } + + class VideoTexture extends Texture { + + constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isVideoTexture = true; + + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + + this.generateMipmaps = false; + + const scope = this; + + function updateVideo() { + + scope.needsUpdate = true; + video.requestVideoFrameCallback( updateVideo ); + + } + + if ( 'requestVideoFrameCallback' in video ) { + + video.requestVideoFrameCallback( updateVideo ); + + } + + } + + clone() { + + return new this.constructor( this.image ).copy( this ); + + } + + update() { + + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; + + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + + this.needsUpdate = true; + + } + + } + + } + + class FramebufferTexture extends Texture { + + constructor( width, height, format ) { + + super( { width, height } ); + + this.isFramebufferTexture = true; + + this.format = format; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.generateMipmaps = false; + + this.needsUpdate = true; + + } + + } + + class CompressedTexture extends Texture { + + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCompressedTexture = true; + + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; + + // 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; + + } + + } + + class CompressedArrayTexture extends CompressedTexture { + + constructor( mipmaps, width, height, depth, format, type ) { + + super( mipmaps, width, height, format, type ); + + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + + } + + } + + class CanvasTexture extends Texture { + + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isCanvasTexture = true; + + this.needsUpdate = true; + + } + + } + + /** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ + + class Curve { + + constructor() { + + this.type = 'Curve'; + + this.arcLengthDivisions = 200; + + } + + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + + getPoint( /* t, optionalTarget */ ) { + + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; + + } + + // Get point at relative position in curve according to arc length + // - u [0 .. 1] + + getPointAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); + + } + + // Get sequence of points using getPoint( t ) + + getPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPoint( d / divisions ) ); + + } + + return points; + + } + + // Get sequence of points using getPointAt( u ) + + getSpacedPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); + + } + + return points; + + } + + // Get total curve arc length + + getLength() { + + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; + + } + + // Get list of cumulative segment lengths + + getLengths( divisions = this.arcLengthDivisions ) { + + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; + + } + + this.needsUpdate = false; + + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; + + cache.push( 0 ); + + for ( let 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() { + + this.needsUpdate = true; + this.getLengths(); + + } + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + getUtoTmapping( u, distance ) { + + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if ( distance ) { + + targetArcLength = distance; + + } else { + + targetArcLength = u * arcLengths[ il - 1 ]; + + } + + // binary search for the index with largest value smaller than target u distance + + let 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; + + if ( arcLengths[ i ] === targetArcLength ) { + + return i / ( il - 1 ); + + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + + // add that fractional amount to t + + const 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( t, optionalTarget ) { + + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + + // Capping in case of danger + + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); + + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); + + return tangent; + + } + + getTangentAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); + + } + + computeFrenetFrames( segments, closed ) { + + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + + const normal = new Vector3(); + + const tangents = []; + const normals = []; + const binormals = []; + + const vec = new Vector3(); + const mat = new Matrix4(); + + // compute the tangent vectors for each segment on the curve + + for ( let i = 0; i <= segments; i ++ ) { + + const u = i / segments; + + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + + } + + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component + + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); + + if ( tx <= min ) { + + min = tx; + normal.set( 1, 0, 0 ); + + } + + if ( ty <= min ) { + + min = ty; + normal.set( 0, 1, 0 ); + + } + + if ( tz <= min ) { + + normal.set( 0, 0, 1 ); + + } + + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + + + // compute the slowly-varying normal and binormal vectors for each segment on the curve + + for ( let i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( let i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + } + + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; + + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + + return data; + + } + + fromJSON( json ) { + + this.arcLengthDivisions = json.arcLengthDivisions; + + return this; + + } + + } + + class EllipseCurve extends Curve { + + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + + super(); + + this.isEllipseCurve = true; + + this.type = 'EllipseCurve'; + + this.aX = aX; + this.aY = aY; + + this.xRadius = xRadius; + this.yRadius = yRadius; + + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + + this.aClockwise = aClockwise; + + this.aRotation = aRotation; + + } + + getPoint( t, optionalTarget ) { + + const point = optionalTarget || new Vector2(); + + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + + if ( deltaAngle < Number.EPSILON ) { + + if ( samePoints ) { + + deltaAngle = 0; + + } else { + + deltaAngle = twoPi; + + } + + } + + if ( this.aClockwise === true && ! samePoints ) { + + if ( deltaAngle === twoPi ) { + + deltaAngle = - twoPi; + + } else { + + deltaAngle = deltaAngle - twoPi; + + } + + } + + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); + + if ( this.aRotation !== 0 ) { + + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); + + const tx = x - this.aX; + const 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 point.set( x, y ); + + } + + copy( source ) { + + super.copy( source ); + + this.aX = source.aX; + this.aY = source.aY; + + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + + this.aClockwise = source.aClockwise; + + this.aRotation = source.aRotation; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.aX = this.aX; + data.aY = this.aY; + + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + + data.aClockwise = this.aClockwise; + + data.aRotation = this.aRotation; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.aX = json.aX; + this.aY = json.aY; + + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + + this.aClockwise = json.aClockwise; + + this.aRotation = json.aRotation; + + return this; + + } + + } + + class ArcCurve extends EllipseCurve { + + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + this.isArcCurve = true; + + this.type = 'ArcCurve'; + + } + + } + + /** + * 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 + */ + + + /* + 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. + */ + + function CubicPoly() { + + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * 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. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + + } + + return { + + initCatmullRom: function ( x0, x1, x2, x3, tension ) { + + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + + }, + + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; + + init( x1, x2, t1, t2 ); + + }, + + calc: function ( t ) { + + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + + } + + }; + + } + + // + + const tmp = /*@__PURE__*/ new Vector3(); + const px = /*@__PURE__*/ new CubicPoly(); + const py = /*@__PURE__*/ new CubicPoly(); + const pz = /*@__PURE__*/ new CubicPoly(); + + class CatmullRomCurve3 extends Curve { + + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + + super(); + + this.isCatmullRomCurve3 = true; + + this.type = 'CatmullRomCurve3'; + + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const points = this.points; + const l = points.length; + + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; + + if ( this.closed ) { + + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + + } else if ( weight === 0 && intPoint === l - 1 ) { + + intPoint = l - 2; + weight = 1; + + } + + let p0, p3; // 4 points (p1 & p2 defined below) + + if ( this.closed || intPoint > 0 ) { + + p0 = points[ ( intPoint - 1 ) % l ]; + + } else { + + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; + + } + + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; + + if ( this.closed || intPoint + 2 < l ) { + + p3 = points[ ( intPoint + 2 ) % l ]; + + } else { + + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; + + } + + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; + + 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.curveType === 'catmullrom' ) { + + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + + } + + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); + + } + + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + + return this; + + } + + } + + /** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ + + function CatmullRom( t, p0, p1, p2, p3 ) { + + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + + } + + // + + function QuadraticBezierP0( t, p ) { + + const k = 1 - t; + return k * k * p; + + } + + function QuadraticBezierP1( t, p ) { + + return 2 * ( 1 - t ) * t * p; + + } + + function QuadraticBezierP2( t, p ) { + + return t * t * p; + + } + + function QuadraticBezier( t, p0, p1, p2 ) { + + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); + + } + + // + + function CubicBezierP0( t, p ) { + + const k = 1 - t; + return k * k * k * p; + + } + + function CubicBezierP1( t, p ) { + + const k = 1 - t; + return 3 * k * k * t * p; + + } + + function CubicBezierP2( t, p ) { + + return 3 * ( 1 - t ) * t * t * p; + + } + + function CubicBezierP3( t, p ) { + + return t * t * t * p; + + } + + function CubicBezier( t, p0, p1, p2, p3 ) { + + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); + + } + + class CubicBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + + super(); + + this.isCubicBezierCurve = true; + + this.type = 'CubicBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + + } + + class CubicBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + + super(); + + this.isCubicBezierCurve3 = true; + + this.type = 'CubicBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + + } + + class LineCurve extends Curve { + + constructor( v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isLineCurve = true; + + this.type = 'LineCurve'; + + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget ) { + + const tangent = optionalTarget || new Vector2(); + + tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + + return tangent; + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + + } + + class LineCurve3 extends Curve { + + constructor( v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isLineCurve3 = true; + + this.type = 'LineCurve3'; + + this.v1 = v1; + this.v2 = v2; + + } + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + + } + + class QuadraticBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isQuadraticBezierCurve = true; + + this.type = 'QuadraticBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + + } + + class QuadraticBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isQuadraticBezierCurve3 = true; + + this.type = 'QuadraticBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + + } + + class SplineCurve extends Curve { + + constructor( points = [] ) { + + super(); + + this.isSplineCurve = true; + + this.type = 'SplineCurve'; + + this.points = points; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const points = this.points; + const p = ( points.length - 1 ) * t; + + const intPoint = Math.floor( p ); + const weight = p - intPoint; + + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); + + } + + return this; + + } + + } + + var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve + }); + + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ + + class CurvePath extends Curve { + + constructor() { + + super(); + + this.type = 'CurvePath'; + + this.curves = []; + this.autoClose = false; // Automatically closes the path + + } + + add( curve ) { + + this.curves.push( curve ); + + } + + closePath() { + + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + + if ( ! startPoint.equals( endPoint ) ) { + + this.curves.push( new LineCurve( endPoint, startPoint ) ); + + } + + } + + // 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( t, optionalTarget ) { + + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + + // To think about boundaries points. + + while ( i < curveLengths.length ) { + + if ( curveLengths[ i ] >= d ) { + + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; + + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt( u, optionalTarget ); + + } + + 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; + + } + + copy( source ) { + + super.copy( source ); + + this.curves = []; + + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + + const curve = source.curves[ i ]; + + this.curves.push( curve.clone() ); + + } + + this.autoClose = source.autoClose; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.autoClose = this.autoClose; + data.curves = []; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.autoClose = json.autoClose; + this.curves = []; + + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + + } + + return this; + + } + + } + + class Path extends CurvePath { + + constructor( points ) { + + super(); + + this.type = 'Path'; + + this.currentPoint = new Vector2(); + + if ( points ) { + + this.setFromPoints( points ); + + } + + } + + setFromPoints( points ) { + + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } + + return this; + + } + + moveTo( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + return this; + + } + + lineTo( x, y ) { + + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + const 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 ); + + return this; + + } + + splineThru( pts /*Array of Vector*/ ) { + + const npts = [ this.currentPoint.clone() ].concat( pts ); + + const curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + return this; + + } + + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + return this; + + } + + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const 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 + const firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; + + } + + copy( source ) { + + super.copy( source ); + + this.currentPoint.copy( source.currentPoint ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; + + } + + } + + class LatheGeometry extends BufferGeometry { + + constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + + super(); + + this.type = 'LatheGeometry'; + + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + segments = Math.floor( segments ); + + // clamp phiLength so it's in range of [ 0, 2PI ] + + phiLength = clamp( phiLength, 0, Math.PI * 2 ); + + // buffers + + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + + // helper variables + + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + + // pre-compute normals for initial "meridian" + + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + + switch ( j ) { + + case 0: // special handling for 1st vertex on path + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + prevNormal.copy( normal ); + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + break; + + case ( points.length - 1 ): // special handling for last Vertex on path + + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); + + break; + + default: // default handling for all vertices in between + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + curNormal.copy( normal ); + + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + prevNormal.copy( curNormal ); + + } + + } + + // generate vertices, uvs and normals + + for ( let i = 0; i <= segments; i ++ ) { + + const phi = phiStart + i * inverseSegments * phiLength; + + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); + + for ( let 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.push( vertex.x, vertex.y, vertex.z ); + + // uv + + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + + uvs.push( uv.x, uv.y ); + + // normal + + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; + + normals.push( x, y, z ); + + } + + } + + // indices + + for ( let i = 0; i < segments; i ++ ) { + + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + + const base = j + i * points.length; + + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + + // faces + + indices.push( a, b, d ); + indices.push( c, d, b ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + + } + + static fromJSON( data ) { + + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); + + } + + } + + class CapsuleGeometry extends LatheGeometry { + + constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { + + const path = new Path(); + path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); + path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); + + super( path.getPoints( capSegments ), radialSegments ); + + this.type = 'CapsuleGeometry'; + + this.parameters = { + radius: radius, + height: length, + capSegments: capSegments, + radialSegments: radialSegments, + }; + + } + + static fromJSON( data ) { + + return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments ); + + } + + } + + class CircleGeometry extends BufferGeometry { + + constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CircleGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + segments = Math.max( 3, segments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + const segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( let i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); + + } + + } + + class CylinderGeometry extends BufferGeometry { + + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CylinderGeometry'; + + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + const scope = this; + + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + + // generate geometry + + generateTorso(); + + if ( openEnded === false ) { + + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generateTorso() { + + const normal = new Vector3(); + const vertex = new Vector3(); + + let groupCount = 0; + + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; + + // generate vertices, normals and uvs + + for ( let y = 0; y <= heightSegments; y ++ ) { + + const indexRow = []; + + const v = y / heightSegments; + + // calculate the radius of the current row + + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + + const theta = u * thetaLength + thetaStart; + + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, 1 - v ); + + // save index of vertex in respective row + + indexRow.push( index ++ ); + + } + + // now save vertices of the row in our index array + + indexArray.push( indexRow ); + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + for ( let y = 0; y < heightSegments; y ++ ) { + + // we use the index array to access the correct indices + + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // update group counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, 0 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + function generateCap( top ) { + + // save the index of the first center vertex + const centerIndexStart = index; + + const uv = new Vector2(); + const vertex = new Vector3(); + + let groupCount = 0; + + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : - 1; + + // 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 + + for ( let x = 1; x <= radialSegments; x ++ ) { + + // vertex + + vertices.push( 0, halfHeight * sign, 0 ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uvs.push( 0.5, 0.5 ); + + // increase index + + index ++; + + } + + // save the index of the last center vertex + const centerIndexEnd = index; + + // now we generate the surrounding vertices, normals and uvs + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); + + // increase index + + index ++; + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + + if ( top === true ) { + + // face top + + indices.push( i, i + 1, c ); + + } else { + + // face bottom + + indices.push( i + 1, i, c ); + + } + + groupCount += 3; + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + } + + static fromJSON( data ) { + + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + + } + + class ConeGeometry extends CylinderGeometry { + + constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super( 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 + }; + + } + + static fromJSON( data ) { + + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + + } + + class PolyhedronGeometry extends BufferGeometry { + + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { + + super(); + + this.type = 'PolyhedronGeometry'; + + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; + + // default buffer data + + const vertexBuffer = []; + const uvBuffer = []; + + // the subdivision creates the vertex buffer data + + subdivide( detail ); + + // all vertices should lie on a conceptual sphere with a given radius + + applyRadius( radius ); + + // finally, create the uv data + + generateUVs(); + + // build non-indexed geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + + if ( detail === 0 ) { + + this.computeVertexNormals(); // flat normals + + } else { + + this.normalizeNormals(); // smooth normals + + } + + // helper functions + + function subdivide( detail ) { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + // iterate over all faces and apply a subdivision with the given detail value + + for ( let i = 0; i < indices.length; i += 3 ) { + + // get the vertices of the face + + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); + + // perform subdivision + + subdivideFace( a, b, c, detail ); + + } + + } + + function subdivideFace( a, b, c, detail ) { + + const cols = detail + 1; + + // we use this multidimensional array as a data structure for creating the subdivision + + const v = []; + + // construct all of the vertices for this subdivision + + for ( let i = 0; i <= cols; i ++ ) { + + v[ i ] = []; + + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); + + const rows = cols - i; + + for ( let j = 0; j <= rows; j ++ ) { + + if ( j === 0 && i === cols ) { + + v[ i ][ j ] = aj; + + } else { + + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + + } + + } + + } + + // construct all of the faces + + for ( let i = 0; i < cols; i ++ ) { + + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + + const k = Math.floor( j / 2 ); + + if ( j % 2 === 0 ) { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); + + } else { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + + } + + } + + } + + } + + function applyRadius( radius ) { + + const vertex = new Vector3(); + + // iterate over the entire buffer and apply the radius to each vertex + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + vertex.normalize().multiplyScalar( radius ); + + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; + + } + + } + + function generateUVs() { + + const vertex = new Vector3(); + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); + + } + + correctUVs(); + + correctSeam(); + + } + + function correctSeam() { + + // handle case when face straddles the seam, see #3269 + + for ( let i = 0; i < uvBuffer.length; i += 6 ) { + + // uv data of a single face + + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; + + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); + + // 0.9 is somewhat arbitrary + + if ( max > 0.9 && min < 0.1 ) { + + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + + } + + } + + } + + function pushVertex( vertex ) { + + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + + } + + function getVertexByIndex( index, vertex ) { + + const stride = index * 3; + + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; + + } + + function correctUVs() { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + const centroid = new Vector3(); + + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { + + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + + const azi = azimuth( centroid ); + + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); + + } + + } + + function correctUV( uv, stride, vector, azimuth ) { + + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + + uvBuffer[ stride ] = uv.x - 1; + + } + + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + + } + + } + + // Angle around the Y axis, counter-clockwise when looking from above. + + function azimuth( vector ) { + + return Math.atan2( vector.z, - vector.x ); + + } + + + // Angle above the XZ plane. + + function inclination( vector ) { + + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + + } + + } + + static fromJSON( data ) { + + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details ); + + } + + } + + class DodecahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'DodecahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new DodecahedronGeometry( data.radius, data.detail ); + + } + + } + + const _v0 = /*@__PURE__*/ new Vector3(); + const _v1$1 = /*@__PURE__*/ new Vector3(); + const _normal = /*@__PURE__*/ new Vector3(); + const _triangle = /*@__PURE__*/ new Triangle(); + + class EdgesGeometry extends BufferGeometry { + + constructor( geometry = null, thresholdAngle = 1 ) { + + super(); + + this.type = 'EdgesGeometry'; + + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; + + if ( geometry !== null ) { + + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); + + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); + + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { + + if ( indexAttr ) { + + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); + + } else { + + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; + + } + + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); + + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + + continue; + + } + + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { + + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; + + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); + + } + + edgeData[ reverseHash ] = null; + + } else if ( ! ( hash in edgeData ) ) { + + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { + + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), + + }; + + } + + } + + } + + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { + + if ( edgeData[ key ] ) { + + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); + + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); + + } + + } + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + + } + + class Shape extends Path { + + constructor( points ) { + + super( points ); + + this.uuid = generateUUID(); + + this.type = 'Shape'; + + this.holes = []; + + } + + getPointsHoles( divisions ) { + + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + + } + + return holesPts; + + } + + // get points of shape and holes (keypoints based on segments parameter) + + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; + + } + + copy( source ) { + + super.copy( source ); + + this.holes = []; + + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + + const hole = source.holes[ i ]; + + this.holes.push( hole.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.uuid = this.uuid; + data.holes = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.uuid = json.uuid; + this.holes = []; + + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); + + } + + return this; + + } + + } + + /** + * Port from https://github.com/mapbox/earcut (v2.2.4) + */ + + const Earcut = { + + triangulate: function ( data, holeIndices, dim = 2 ) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 32767 / invSize : 0; + + } + + earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 ); + + return triangles; + + } + + }; + + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList( data, start, end, dim, clockwise ) { + + let i, last; + + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } else { + + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } + + if ( last && equals( last, last.next ) ) { + + removeNode( last ); + last = last.next; + + } + + return last; + + } + + // eliminate colinear or duplicate points + function filterPoints( start, end ) { + + if ( ! start ) return start; + if ( ! end ) end = start; + + let p = start, + again; + do { + + again = false; + + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; + + } else { + + p = p.next; + + } + + } while ( again || p !== end ); + + return end; + + } + + // main ear slicing loop which triangulates a polygon (given as a linked list) + function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + + if ( ! ear ) return; + + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + + let stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { + + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim | 0 ); + triangles.push( ear.i / dim | 0 ); + triangles.push( next.i / dim | 0 ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { + + // try filtering points and slicing again + if ( ! pass ) { + + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); + + // if this didn't work, try curing all small self-intersections locally + + } else if ( pass === 1 ) { + + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); + + // as a last resort, try splitting the remaining polygon into two + + } else if ( pass === 2 ) { + + splitEarcut( ear, triangles, dim, minX, minY, invSize ); + + } + + break; + + } + + } + + } + + // check whether a polygon node forms a valid ear with adjacent nodes + function isEar( ear ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + let p = c.next; + while ( p !== a ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; + + } + + return true; + + } + + function isEarHashed( ear, minX, minY, invSize ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + // z-order range for the current triangle bbox; + const minZ = zOrder( x0, y0, minX, minY, invSize ), + maxZ = zOrder( x1, y1, minX, minY, invSize ); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + } + + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + return true; + + } + + // go through all polygon nodes and cure small local self-intersections + function cureLocalIntersections( start, triangles, dim ) { + + let p = start; + do { + + const a = p.prev, + b = p.next.next; + + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + + triangles.push( a.i / dim | 0 ); + triangles.push( p.i / dim | 0 ); + triangles.push( b.i / dim | 0 ); + + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); + + p = start = b; + + } + + p = p.next; + + } while ( p !== start ); + + return filterPoints( p ); + + } + + // try splitting polygon into two and triangulate them independently + function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + + let b = a.next.next; + while ( b !== a.prev ) { + + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); + + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); + + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize, 0 ); + earcutLinked( c, triangles, dim, minX, minY, invSize, 0 ); + return; + + } + + b = b.next; + + } + + a = a.next; + + } while ( a !== start ); + + } + + // link every hole into the outer loop, producing a single-ring polygon without holes + function eliminateHoles( data, holeIndices, outerNode, dim ) { + + const queue = []; + let i, len, start, end, list; + + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); + + } + + queue.sort( compareX ); + + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { + + outerNode = eliminateHole( queue[ i ], outerNode ); + + } + + return outerNode; + + } + + function compareX( a, b ) { + + return a.x - b.x; + + } + + // find a bridge between vertices that connects hole with an outer ring and link it + function eliminateHole( hole, outerNode ) { + + const bridge = findHoleBridge( hole, outerNode ); + if ( ! bridge ) { + + return outerNode; + + } + + const bridgeReverse = splitPolygon( bridge, hole ); + + // filter collinear points around the cuts + filterPoints( bridgeReverse, bridgeReverse.next ); + return filterPoints( bridge, bridge.next ); + + } + + // David Eberly's algorithm for finding a bridge between hole and outer polygon + function findHoleBridge( hole, outerNode ) { + + let p = outerNode, + qx = - Infinity, + m; + + const hx = hole.x, hy = hole.y; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { + + qx = x; + m = p.x < p.next.x ? p : p.next; + if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint + + } + + } + + p = p.next; + + } while ( p !== outerNode ); + + if ( ! m ) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; + + p = m; + + do { + + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + + m = p; + tanMin = tan; + + } + + } + + p = p.next; + + } while ( p !== stop ); + + return m; + + } + + // whether sector in vertex m contains sector in vertex p in the same coordinates + function sectorContainsSector( m, p ) { + + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + + } + + // interlink polygon nodes in z-order + function indexCurve( start, minX, minY, invSize ) { + + let p = start; + do { + + if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + + } while ( p !== start ); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked( p ); + + } + + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + function sortLinked( list ) { + + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + + p = list; + list = null; + tail = null; + numMerges = 0; + + while ( p ) { + + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { + + pSize ++; + q = q.nextZ; + if ( ! q ) break; + + } + + qSize = inSize; + + while ( pSize > 0 || ( qSize > 0 && q ) ) { + + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + + e = p; + p = p.nextZ; + pSize --; + + } else { + + e = q; + q = q.nextZ; + qSize --; + + } + + if ( tail ) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + + } + + p = q; + + } + + tail.nextZ = null; + inSize *= 2; + + } while ( numMerges > 1 ); + + return list; + + } + + // z-order of a point given coords and inverse of the longer side of data bbox + function zOrder( x, y, minX, minY, invSize ) { + + // coords are transformed into non-negative 15-bit integer range + x = ( x - minX ) * invSize | 0; + y = ( y - minY ) * invSize | 0; + + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; + + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; + + return x | ( y << 1 ); + + } + + // find the leftmost node of a polygon ring + function getLeftmost( start ) { + + let p = start, + leftmost = start; + do { + + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; + + } while ( p !== start ); + + return leftmost; + + } + + // check if a point lies within a convex triangle + function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + + return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) && + ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) && + ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py ); + + } + + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) + function isValidDiagonal( a, b ) { + + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + + } + + // signed area of a triangle + function area( p, q, r ) { + + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + + } + + // check if two points are equal + function equals( p1, p2 ) { + + return p1.x === p2.x && p1.y === p2.y; + + } + + // check if two segments intersect + function intersects( p1, q1, p2, q2 ) { + + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); + + if ( o1 !== o2 && o3 !== o4 ) return true; // general case + + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + + } + + // for collinear points p, q, r, check if point q lies on segment pr + function onSegment( p, q, r ) { + + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + + } + + function sign( num ) { + + return num > 0 ? 1 : num < 0 ? - 1 : 0; + + } + + // check if a polygon diagonal intersects any polygon segments + function intersectsPolygon( a, b ) { + + let p = a; + do { + + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; + + } while ( p !== a ); + + return false; + + } + + // check if a polygon diagonal is locally inside the polygon + function locallyInside( a, b ) { + + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + + } + + // check if the middle point of a polygon diagonal is inside the polygon + function middleInside( a, b ) { + + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { + + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; + + } while ( p !== a ); + + return inside; + + } + + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring + function splitPolygon( a, b ) { + + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + + } + + // create a node and optionally link it with previous one (in a circular doubly linked list) + function insertNode( i, x, y, last ) { + + const p = new Node( i, x, y ); + + if ( ! last ) { + + p.prev = p; + p.next = p; + + } else { + + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + + } + + return p; + + } + + function removeNode( p ) { + + p.next.prev = p.prev; + p.prev.next = p.next; + + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + + } + + function Node( i, x, y ) { + + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + + } + + function signedArea( data, start, end, dim ) { + + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { + + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; + + } + + return sum; + + } + + class ShapeUtils { + + // calculate area of the contour polygon + + static area( contour ) { + + const n = contour.length; + let a = 0.0; + + for ( let 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; + + } + + static isClockWise( pts ) { + + return ShapeUtils.area( pts ) < 0; + + } + + static triangulateShape( contour, holes ) { + + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + + removeDupEndPts( contour ); + addContour( vertices, contour ); + + // + + let holeIndex = contour.length; + + holes.forEach( removeDupEndPts ); + + for ( let i = 0; i < holes.length; i ++ ) { + + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); + + } + + // + + const triangles = Earcut.triangulate( vertices, holeIndices ); + + // + + for ( let i = 0; i < triangles.length; i += 3 ) { + + faces.push( triangles.slice( i, i + 3 ) ); + + } + + return faces; + + } + + } + + function removeDupEndPts( points ) { + + const l = points.length; + + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + + points.pop(); + + } + + } + + function addContour( vertices, contour ) { + + for ( let i = 0; i < contour.length; i ++ ) { + + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); + + } + + } + + /** + * 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 + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ + + class ExtrudeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { + + super(); + + this.type = 'ExtrudeGeometry'; + + this.parameters = { + shapes: shapes, + options: options + }; + + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + + const scope = this; + + const verticesArray = []; + const uvArray = []; + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + addShape( shape ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + this.computeVertexNormals(); + + // functions + + function addShape( shape ) { + + const placeholder = []; + + // options + + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + + const extrudePath = options.extrudePath; + + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + + // + + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + + if ( extrudePath ) { + + extrudePts = extrudePath.getSpacedPoints( steps ); + + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion + + // SETUP TNB variables + + // TODO1 - have a .isClosed in spline? + + splineTube = extrudePath.computeFrenetFrames( steps, false ); + + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } + + // Safeguards if bevels are not enabled + + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + + } + + // Variables initialization + + const shapePoints = shape.extractPoints( curveSegments ); + + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + + const reverse = ! ShapeUtils.isClockWise( vertices ); + + if ( reverse ) { + + vertices = vertices.reverse(); + + // Maybe we should also check if holes are in the opposite direction, just to be safe ... + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + if ( ShapeUtils.isClockWise( ahole ) ) { + + holes[ h ] = ahole.reverse(); + + } + + } + + } + + + const faces = ShapeUtils.triangulateShape( vertices, holes ); + + /* Vertices */ + + const contour = vertices; // vertices has all points but contour has only points of circumference + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + vertices = vertices.concat( ahole ); + + } + + + function scalePt2( pt, vec, size ) { + + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + + return vec.clone().multiplyScalar( size ).add( pt ); + + } + + const vlen = vertices.length, flen = faces.length; + + + // Find directions for point movement + + + 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. + + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html + + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; + + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + + // not collinear + + // length of vectors for normalizing + + const v_prev_len = Math.sqrt( v_prev_lensq ); + const 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 + + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + const 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 ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } + + } else { + + // handle special case of collinear edges + + let direction_eq = false; // assumes: opposite + + if ( v_prev_x > Number.EPSILON ) { + + if ( v_next_x > Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( v_prev_x < - Number.EPSILON ) { + + if ( v_next_x < - Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + + direction_eq = true; + + } + + } + + } + + 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 ); + + } 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 ); + + } + + } + + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + + } + + + const contourMovements = []; + + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) + + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + + } + + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + oneHoleMovements = []; + + for ( let 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; + + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + + } + + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); + + } + + + // Loop bevelSegments, 1 for the front, 1 for the back + + for ( let b = 0; b < bevelSegments; b ++ ) { + + //for ( b = bevelSegments; b > 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + } + + } + + const bs = bevelSize + bevelOffset; + + // Back facing vertices + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, 0 ); + + } else { + + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + // Add stepped vertices... + // Including front facing vertices + + for ( let s = 1; s <= steps; s ++ ) { + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth / steps * s ); + + } else { + + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + } + + + // Add bevel segments planes + + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } + + } + + /* Faces */ + + // Top and bottom faces + + buildLidFaces(); + + // Sides faces + + buildSideFaces(); + + + ///// Internal functions + + function buildLidFaces() { + + const start = verticesArray.length / 3; + + if ( bevelEnabled ) { + + let layer = 0; // steps + 1 + let offset = vlen * layer; + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + + } + + layer = steps + bevelSegments * 2; + offset = vlen * layer; + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + + } + + } else { + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + + } + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + + } + + } + + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; + + } + + + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + + + } + + function sidewalls( contour, layeroffset ) { + + let i = contour.length; + + while ( -- i >= 0 ) { + + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; + + //console.log('b', i,j, i-1, k,vertices.length); + + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); + + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } + + } + + } + + function v( x, y, z ) { + + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); + + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + + } + + function f4( a, b, c, d ) { + + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + const options = this.parameters.options; + + return toJSON$1( shapes, options, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + const extrudePath = data.options.extrudePath; + + if ( extrudePath !== undefined ) { + + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + + } + + return new ExtrudeGeometry( geometryShapes, data.options ); + + } + + } + + const WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + + }, + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { + + 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 ) + ]; + + } else { + + 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 ) + ]; + + } + + } + + }; + + function toJSON$1( shapes, options, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + data.options = Object.assign( {}, options ); + + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + + return data; + + } + + class IcosahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'IcosahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new IcosahedronGeometry( data.radius, data.detail ); + + } + + } + + class OctahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'OctahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new OctahedronGeometry( data.radius, data.detail ); + + } + + } + + class RingGeometry extends BufferGeometry { + + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'RingGeometry'; + + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // some helper variables + + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= phiSegments; j ++ ) { + + for ( let i = 0; i <= thetaSegments; i ++ ) { + + // values are generate from the inside of the ring to the outside + + const segment = thetaStart + i / thetaSegments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uv + + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // increase the radius for next row of vertices + + radius += radiusStep; + + } + + // indices + + for ( let j = 0; j < phiSegments; j ++ ) { + + const thetaSegmentLevel = j * ( thetaSegments + 1 ); + + for ( let i = 0; i < thetaSegments; i ++ ) { + + const segment = i + thetaSegmentLevel; + + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); + + } + + } + + class ShapeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) { + + super(); + + this.type = 'ShapeGeometry'; + + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let groupStart = 0; + let groupCount = 0; + + // allow single and array values for "shapes" parameter + + if ( Array.isArray( shapes ) === false ) { + + addShape( shapes ); + + } else { + + for ( let i = 0; i < shapes.length; i ++ ) { + + addShape( shapes[ i ] ); + + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + + groupStart += groupCount; + groupCount = 0; + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + + // helper functions + + function addShape( shape ) { + + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); + + let shapeVertices = points.shape; + const shapeHoles = points.holes; + + // check direction of vertices + + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + + shapeVertices = shapeVertices.reverse(); + + } + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + + shapeHoles[ i ] = shapeHole.reverse(); + + } + + } + + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + + // join vertices of inner and outer paths to a single array + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); + + } + + // vertices, normals, uvs + + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + + const vertex = shapeVertices[ i ]; + + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs + + } + + // indices + + for ( let i = 0, l = faces.length; i < l; i ++ ) { + + const face = faces[ i ]; + + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; + + indices.push( a, b, c ); + groupCount += 3; + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + return new ShapeGeometry( geometryShapes, data.curveSegments ); + + } + + } + + function toJSON( shapes, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + return data; + + } + + class SphereGeometry extends BufferGeometry { + + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + + super(); + + this.type = 'SphereGeometry'; + + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + + let index = 0; + const grid = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // generate vertices, normals and uvs + + for ( let iy = 0; iy <= heightSegments; iy ++ ) { + + const verticesRow = []; + + const v = iy / heightSegments; + + // special case for the poles + + let uOffset = 0; + + if ( iy == 0 && thetaStart == 0 ) { + + uOffset = 0.5 / widthSegments; + + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + + uOffset = - 0.5 / widthSegments; + + } + + for ( let ix = 0; ix <= widthSegments; ix ++ ) { + + const u = ix / widthSegments; + + // vertex + + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, 1 - v ); + + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); + + } + + // indices + + for ( let iy = 0; iy < heightSegments; iy ++ ) { + + for ( let ix = 0; ix < widthSegments; ix ++ ) { + + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); + + } + + } + + class TetrahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; + + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'TetrahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new TetrahedronGeometry( data.radius, data.detail ); + + } + + } + + class TorusGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) { + + super(); + + this.type = 'TorusGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; + + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= radialSegments; j ++ ) { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + + // 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= radialSegments; j ++ ) { + + for ( let i = 1; i <= tubularSegments; i ++ ) { + + // indices + + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); + + } + + } + + class TorusKnotGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + + super(); + + this.type = 'TorusKnotGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; + + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + + const P1 = new Vector3(); + const P2 = new Vector3(); + + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); + + // generate vertices, normals and uvs + + for ( let i = 0; i <= tubularSegments; ++ i ) { + + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment + + const u = i / tubularSegments * p * Math.PI * 2; + + // 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 ); + + // calculate orthonormal basis + + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); + + // normalize B, N. T can be ignored, we don't use it + + B.normalize(); + N.normalize(); + + for ( let j = 0; j <= radialSegments; ++ j ) { + + // 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. + + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); + + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve + + 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // 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.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + // indices + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // this function calculates the current position on the torus curve + + function calculatePositionOnCurve( u, p, q, radius, position ) { + + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const 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; + + } + + } + + static fromJSON( data ) { + + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); + + } + + } + + class TubeGeometry extends BufferGeometry { + + constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + + super(); + + this.type = 'TubeGeometry'; + + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; + + const frames = path.computeFrenetFrames( tubularSegments, closed ); + + // expose internals + + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + + // buffer + + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + + // create buffer data + + generateBufferData(); + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // functions + + function generateBufferData() { + + for ( let i = 0; i < tubularSegments; i ++ ) { + + generateSegment( i ); + + } + + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + + generateSegment( ( closed === false ) ? tubularSegments : 0 ); + + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries + + generateUVs(); + + // finally create faces + + generateIndices(); + + } + + function generateSegment( i ) { + + // we use getPointAt to sample evenly distributed points from the given path + + P = path.getPointAt( i / tubularSegments, P ); + + // retrieve corresponding normal and binormal + + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; + + // generate normals and vertices for the current segment + + for ( let j = 0; j <= radialSegments; j ++ ) { + + const v = j / radialSegments * Math.PI * 2; + + const sin = Math.sin( v ); + const cos = - Math.cos( v ); + + // normal + + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // vertex + + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + } + + } + + function generateIndices() { + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + } + + function generateUVs() { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + for ( let j = 0; j <= radialSegments; j ++ ) { + + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + + uvs.push( uv.x, uv.y ); + + } + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + data.path = this.parameters.path.toJSON(); + + return data; + + } + + static fromJSON( data ) { + + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + + } + + } + + class WireframeGeometry extends BufferGeometry { + + constructor( geometry = null ) { + + super(); + + this.type = 'WireframeGeometry'; + + this.parameters = { + geometry: geometry + }; + + if ( geometry !== null ) { + + // buffer + + const vertices = []; + const edges = new Set(); + + // helper variables + + const start = new Vector3(); + const end = new Vector3(); + + if ( geometry.index !== null ) { + + // indexed BufferGeometry + + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + + if ( groups.length === 0 ) { + + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + + } + + // create a data structure that contains all edges without duplicates + + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + + const group = groups[ o ]; + + const groupStart = group.start; + const groupCount = group.count; + + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { + + for ( let j = 0; j < 3; j ++ ) { + + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + } else { + + // non-indexed BufferGeometry + + const position = geometry.attributes.position; + + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + + for ( let j = 0; j < 3; j ++ ) { + + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + + } + + function isUniqueEdge( start, end, edges ) { + + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge + + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { + + return false; + + } else { + + edges.add( hash1 ); + edges.add( hash2 ); + return true; + + } + + } + + var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry + }); + + class ShadowMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShadowMaterial = true; + + this.type = 'ShadowMaterial'; + + this.color = new Color( 0x000000 ); + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.fog = source.fog; + + return this; + + } + + } + + class RawShaderMaterial extends ShaderMaterial { + + constructor( parameters ) { + + super( parameters ); + + this.isRawShaderMaterial = true; + + this.type = 'RawShaderMaterial'; + + } + + } + + class MeshStandardMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshStandardMaterial = true; + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 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.0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + 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; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + + } + + class MeshPhysicalMaterial extends MeshStandardMaterial { + + constructor( parameters ) { + + super(); + + this.isMeshPhysicalMaterial = true; + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.type = 'MeshPhysicalMaterial'; + + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; + + this.ior = 1.5; + + Object.defineProperty( this, 'reflectivity', { + get: function () { + + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); + + }, + set: function ( reflectivity ) { + + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); + + } + } ); + + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; + + this.transmissionMap = null; + + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color( 1, 1, 1 ); + + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; + + this._sheen = 0.0; + this._clearcoat = 0; + this._iridescence = 0; + this._transmission = 0; + + this.setValues( parameters ); + + } + + get sheen() { + + return this._sheen; + + } + + set sheen( value ) { + + if ( this._sheen > 0 !== value > 0 ) { + + this.version ++; + + } + + this._sheen = value; + + } + + get clearcoat() { + + return this._clearcoat; + + } + + set clearcoat( value ) { + + if ( this._clearcoat > 0 !== value > 0 ) { + + this.version ++; + + } + + this._clearcoat = value; + + } + + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + + get transmission() { + + return this._transmission; + + } + + set transmission( value ) { + + if ( this._transmission > 0 !== value > 0 ) { + + this.version ++; + + } + + this._transmission = value; + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.ior = source.ior; + + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); + + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; + + return this; + + } + + } + + class MeshPhongMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshPhongMaterial = true; + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + + } + + class MeshToonMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshToonMaterial = true; + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + this.gradientMap = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + this.gradientMap = source.gradientMap; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + + } + + class MeshNormalMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshNormalMaterial = true; + + this.type = 'MeshNormalMaterial'; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.flatShading = false; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + return this; + + } + + } + + class MeshLambertMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshLambertMaterial = true; + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + + } + + class MeshMatcapMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshMatcapMaterial = true; + + this.defines = { 'MATCAP': '' }; + + this.type = 'MeshMatcapMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.matcap = null; + + this.map = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.defines = { 'MATCAP': '' }; + + this.color.copy( source.color ); + + this.matcap = source.matcap; + + this.map = source.map; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + + } + + class LineDashedMaterial extends LineBasicMaterial { + + constructor( parameters ) { + + super(); + + this.isLineDashedMaterial = true; + + this.type = 'LineDashedMaterial'; + + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + } + + } + + // same as Array.prototype.slice, but also works on typed arrays + function arraySlice( array, from, to ) { + + if ( isTypedArray( array ) ) { + + // in ios9 array.subarray(from, undefined) will return empty array + // but array.subarray(from) or array.subarray(from, len) is correct + return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + + } + + return array.slice( from, to ); + + } + + // converts an array to a specific type + function convertArray( array, type, forceClone ) { + + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; + + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + + return new type( array ); // create typed array + + } + + return Array.prototype.slice.call( array ); // create Array + + } + + function isTypedArray( object ) { + + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); + + } + + // returns an array by which times and values can be sorted + function getKeyframeOrder( times ) { + + function compareTime( i, j ) { + + return times[ i ] - times[ j ]; + + } + + const n = times.length; + const result = new Array( n ); + for ( let i = 0; i !== n; ++ i ) result[ i ] = i; + + result.sort( compareTime ); + + return result; + + } + + // uses the array previously returned by 'getKeyframeOrder' to sort data + function sortedArray( values, stride, order ) { + + const nValues = values.length; + const result = new values.constructor( nValues ); + + for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + + const srcOffset = order[ i ] * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + result[ dstOffset ++ ] = values[ srcOffset + j ]; + + } + + } + + return result; + + } + + // function for parsing AOS keyframe formats + function flattenJSON( jsonKeys, times, values, valuePropertyName ) { + + let i = 1, key = jsonKeys[ 0 ]; + + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + + key = jsonKeys[ i ++ ]; + + } + + if ( key === undefined ) return; // no data + + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data + + if ( Array.isArray( value ) ) { + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push.apply( values, value ); // push all elements + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else if ( value.toArray !== undefined ) { + + // ...assume THREE.Math-ish + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + value.toArray( values, values.length ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else { + + // otherwise push as-is + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push( value ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } + + } + + function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { + + const clip = sourceClip.clone(); + + clip.name = name; + + const tracks = []; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); + + const times = []; + const values = []; + + for ( let j = 0; j < track.times.length; ++ j ) { + + const frame = track.times[ j ] * fps; + + if ( frame < startFrame || frame >= endFrame ) continue; + + times.push( track.times[ j ] ); + + for ( let k = 0; k < valueSize; ++ k ) { + + values.push( track.values[ j * valueSize + k ] ); + + } + + } + + if ( times.length === 0 ) continue; + + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); + + } + + clip.tracks = tracks; + + // find minimum .times value across all tracks in the trimmed clip + + let minStartTime = Infinity; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + + minStartTime = clip.tracks[ i ].times[ 0 ]; + + } + + } + + // shift all tracks such that clip begins at t=0 + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + clip.tracks[ i ].shift( - 1 * minStartTime ); + + } + + clip.resetDuration(); + + return clip; + + } + + function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + + if ( fps <= 0 ) fps = 30; + + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { + + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; + + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { + + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; + + } ); + + if ( targetTrack === undefined ) continue; + + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + referenceOffset = referenceValueSize / 3; + + } + + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + targetOffset = targetValueSize / 3; + + } + + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { + + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else { + + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex ); + + } + + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { + + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); + + } + + // Subtract the reference value from all of the track values + + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { + + const valueStart = j * targetValueSize + targetOffset; + + if ( referenceTrackType === 'quaternion' ) { + + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + + } else { + + const valueEnd = targetValueSize - targetOffset * 2; + + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { + + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + + } + + } + + } + + } + + targetClip.blendMode = AdditiveAnimationBlendMode; + + return targetClip; + + } + + var AnimationUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arraySlice: arraySlice, + convertArray: convertArray, + flattenJSON: flattenJSON, + getKeyframeOrder: getKeyframeOrder, + isTypedArray: isTypedArray, + makeClipAdditive: makeClipAdditive, + sortedArray: sortedArray, + subclip: subclip + }); + + /** + * 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 + * + */ + + class Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + + this.settings = null; + this.DefaultSettings_ = {}; + + } + + evaluate( t ) { + + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; + + validate_interval: { + + seek: { + + let right; + + linear_scan: { + + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { + + for ( let giveUpAt = i1 + 2; ; ) { + + if ( t1 === undefined ) { + + if ( t < t0 ) break forward_scan; + + // after end + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t0 = t1; + t1 = pp[ ++ i1 ]; + + if ( t < t1 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // 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? + + const t1global = pp[ 1 ]; + + if ( t < t1global ) { + + i1 = 2; // + 1, using the scan for the details + t0 = t1global; + + } + + // linear reverse scan + + for ( let giveUpAt = i1 - 2; ; ) { + + if ( t0 === undefined ) { + + // before start + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t1 = t0; + t0 = pp[ -- i1 - 1 ]; + + if ( t >= t0 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; + + } + + // the interval is valid + + break validate_interval; + + } // linear scan + + // binary search + + while ( i1 < right ) { + + const mid = ( i1 + right ) >>> 1; + + if ( t < pp[ mid ] ) { + + right = mid; + + } else { + + i1 = mid + 1; + + } + + } + + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; + + // check boundary cases, again + + if ( t0 === undefined ) { + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( t1 === undefined ) { + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + } // seek + + this._cachedIndex = i1; + + this.intervalChanged_( i1, t0, t1 ); + + } // validate_interval + + return this.interpolate_( i1, t0, t, t1 ); + + } + + getSettings_() { + + return this.settings || this.DefaultSettings_; + + } + + copySampleValue_( index ) { + + // copies a sample value to the result buffer + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = values[ offset + i ]; + + } + + return result; + + } + + // Template methods for derived classes: + + interpolate_( /* i1, t0, t, t1 */ ) { + + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer + + } + + intervalChanged_( /* i1, t0, t1 */ ) { + + // empty + + } + + } + + /** + * 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. + */ + + class CubicInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; + + this.DefaultSettings_ = { + + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + + }; + + } + + intervalChanged_( i1, t0, t1 ) { + + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, + + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; + + if ( tPrev === undefined ) { + + switch ( this.getSettings_().endingStart ) { + + case ZeroSlopeEnding: + + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; + + } + + } + + if ( tNext === undefined ) { + + switch ( this.getSettings_().endingEnd ) { + + case ZeroSlopeEnding: + + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; + + } + + } + + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; + + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + + } + + interpolate_( i1, t0, t, t1 ) { + + const 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; + + // evaluate polynomials + + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + + // combine data linearly + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; + + } + + return result; + + } + + } + + class LinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + offset1 = i1 * stride, + offset0 = offset1 - stride, + + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; + + } + + return result; + + } + + } + + /** + * + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + */ + + class DiscreteInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1 /*, t0, t, t1 */ ) { + + return this.copySampleValue_( i1 - 1 ); + + } + + } + + class KeyframeTrack { + + constructor( name, times, values, interpolation ) { + + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + + this.name = name; + + this.times = convertArray( times, this.TimeBufferType ); + this.values = convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + } + + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): + + static toJSON( track ) { + + const trackType = track.constructor; + + let json; + + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { + + json = trackType.toJSON( track ); + + } else { + + // by default, we assume the data can be serialized as-is + json = { + + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) + + }; + + const interpolation = track.getInterpolation(); + + if ( interpolation !== track.DefaultInterpolation ) { + + json.interpolation = interpolation; + + } + + } + + json.type = track.ValueTypeName; // mandatory + + return json; + + } + + InterpolantFactoryMethodDiscrete( result ) { + + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodLinear( result ) { + + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + setInterpolation( interpolation ) { + + let factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + } + + if ( factoryMethod === undefined ) { + + const 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( 'THREE.KeyframeTrack:', message ); + return this; + + } + + this.createInterpolant = factoryMethod; + + return this; + + } + + getInterpolation() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + } + + } + + getValueSize() { + + return this.values.length / this.times.length; + + } + + // move all keyframes either forwards or backwards in time + shift( timeOffset ) { + + if ( timeOffset !== 0.0 ) { + + const times = this.times; + + for ( let 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( timeScale ) { + + if ( timeScale !== 1.0 ) { + + const times = this.times; + + for ( let 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( startTime, endTime ) { + + const times = this.times, + nKeys = times.length; + + let 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; + + } + + const stride = this.getValueSize(); + this.times = arraySlice( times, from, to ); + this.values = 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() { + + let valid = true; + + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; + + } + + const times = this.times, + values = this.values, + + nKeys = times.length; + + if ( nKeys === 0 ) { + + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; + + } + + let prevTime = null; + + for ( let i = 0; i !== nKeys; i ++ ) { + + const currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; + + } + + if ( prevTime !== null && prevTime > currTime ) { + + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( isTypedArray( values ) ) { + + for ( let i = 0, n = values.length; i !== n; ++ i ) { + + const value = values[ i ]; + + if ( isNaN( value ) ) { + + console.error( 'THREE.KeyframeTrack: 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() { + + // times or values may be shared with other tracks, so overwriting is unsafe + const times = arraySlice( this.times ), + values = arraySlice( this.values ), + stride = this.getValueSize(), + + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + + lastIndex = times.length - 1; + + let writeIndex = 1; + + for ( let i = 1; i < lastIndex; ++ i ) { + + let keep = false; + + const time = times[ i ]; + const timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + + if ( ! smoothInterpolation ) { + + // remove unnecessary keyframes same as their neighbors + + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( let j = 0; j !== stride; ++ j ) { + + const value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } else { + + keep = true; + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + const readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + } + + ++ writeIndex; + + } + + } + + // flush last keyframe (compaction looks ahead) + + if ( lastIndex > 0 ) { + + times[ writeIndex ] = times[ lastIndex ]; + + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + ++ writeIndex; + + } + + if ( writeIndex !== times.length ) { + + this.times = arraySlice( times, 0, writeIndex ); + this.values = arraySlice( values, 0, writeIndex * stride ); + + } else { + + this.times = times; + this.values = values; + + } + + return this; + + } + + clone() { + + const times = arraySlice( this.times, 0 ); + const values = arraySlice( this.values, 0 ); + + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); + + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; + + return track; + + } + + } + + KeyframeTrack.prototype.TimeBufferType = Float32Array; + KeyframeTrack.prototype.ValueBufferType = Float32Array; + KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + + /** + * A Track of Boolean keyframe values. + */ + class BooleanKeyframeTrack extends KeyframeTrack {} + + BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; + BooleanKeyframeTrack.prototype.ValueBufferType = Array; + BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + + /** + * A Track of keyframe values that represent color. + */ + class ColorKeyframeTrack extends KeyframeTrack {} + + ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + + /** + * A Track of numeric keyframe values. + */ + class NumberKeyframeTrack extends KeyframeTrack {} + + NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + + /** + * Spherical linear unit quaternion interpolant. + */ + + class QuaternionLinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + alpha = ( t - t0 ) / ( t1 - t0 ); + + let offset = i1 * stride; + + for ( let end = offset + stride; offset !== end; offset += 4 ) { + + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); + + } + + return result; + + } + + } + + /** + * A Track of quaternion keyframe values. + */ + class QuaternionKeyframeTrack extends KeyframeTrack { + + InterpolantFactoryMethodLinear( result ) { + + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + } + + QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; + // ValueBufferType is inherited + QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + + /** + * A Track that interpolates Strings + */ + class StringKeyframeTrack extends KeyframeTrack {} + + StringKeyframeTrack.prototype.ValueTypeName = 'string'; + StringKeyframeTrack.prototype.ValueBufferType = Array; + StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; + StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + + /** + * A Track of vectored keyframe values. + */ + class VectorKeyframeTrack extends KeyframeTrack {} + + VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + + class AnimationClip { + + constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { + + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + + this.uuid = generateUUID(); + + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { + + this.resetDuration(); + + } + + } + + + static parse( json ) { + + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); + + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + + } + + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; + + return clip; + + } + + static toJSON( clip ) { + + const tracks = [], + clipTracks = clip.tracks; + + const json = { + + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode + + }; + + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + + } + + return json; + + } + + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + + for ( let i = 0; i < numMorphTargets; i ++ ) { + + let times = []; + let values = []; + + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); + + values.push( 0, 1, 0 ); + + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); + + // 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 ] ); + + } + + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + + } + + return new this( name, - 1, tracks ); + + } + + static findByName( objectOrClipArray, name ) { + + let clipArray = objectOrClipArray; + + if ( ! Array.isArray( objectOrClipArray ) ) { + + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + + } + + for ( let i = 0; i < clipArray.length; i ++ ) { + + if ( clipArray[ i ].name === name ) { + + return clipArray[ i ]; + + } + + } + + return null; + + } + + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + + const animationToMorphTargets = {}; + + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; + + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); + + if ( parts && parts.length > 1 ) { + + const name = parts[ 1 ]; + + let animationMorphTargets = animationToMorphTargets[ name ]; + + if ( ! animationMorphTargets ) { + + animationToMorphTargets[ name ] = animationMorphTargets = []; + + } + + animationMorphTargets.push( morphTarget ); + + } + + } + + const clips = []; + + for ( const name in animationToMorphTargets ) { + + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + + } + + return clips; + + } + + // parse the animation.hierarchy format + static parseAnimation( animation, bones ) { + + if ( ! animation ) { + + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; + + } + + const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { + + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { + + const times = []; + const values = []; + + flattenJSON( animationKeys, times, values, propertyName ); + + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { + + destTracks.push( new trackType( trackName, times, values ) ); + + } + + } + + }; + + const tracks = []; + + const clipName = animation.name || 'default'; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + + // automatic length determination in AnimationClip. + let duration = animation.length || - 1; + + const hierarchyTracks = animation.hierarchy || []; + + for ( let h = 0; h < hierarchyTracks.length; h ++ ) { + + const animationKeys = hierarchyTracks[ h ].keys; + + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; + + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { + + // figure out all morph targets used in this track + const morphTargetNames = {}; + + let k; + + for ( k = 0; k < animationKeys.length; k ++ ) { + + if ( animationKeys[ k ].morphTargets ) { + + for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + + } + + } + + } + + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( const morphTargetName in morphTargetNames ) { + + const times = []; + const values = []; + + for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { + + const animationKey = animationKeys[ k ]; + + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + + } + + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + + } + + duration = morphTargetNames.length * fps; + + } else { + + // ...assume skeletal animation + + const boneName = '.bones[' + bones[ h ].name + ']'; + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); + + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); + + } + + } + + if ( tracks.length === 0 ) { + + return null; + + } + + const clip = new this( clipName, duration, tracks, blendMode ); + + return clip; + + } + + resetDuration() { + + const tracks = this.tracks; + let duration = 0; + + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { + + const track = this.tracks[ i ]; + + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + + } + + this.duration = duration; + + return this; + + } + + trim() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].trim( 0, this.duration ); + + } + + return this; + + } + + validate() { + + let valid = true; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + valid = valid && this.tracks[ i ].validate(); + + } + + return valid; + + } + + optimize() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].optimize(); + + } + + return this; + + } + + clone() { + + const tracks = []; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + tracks.push( this.tracks[ i ].clone() ); + + } + + return new this.constructor( this.name, this.duration, tracks, this.blendMode ); + + } + + toJSON() { + + return this.constructor.toJSON( this ); + + } + + } + + function getTrackTypeForValueTypeName( typeName ) { + + switch ( typeName.toLowerCase() ) { + + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': + + return NumberKeyframeTrack; + + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': + + return VectorKeyframeTrack; + + case 'color': + + return ColorKeyframeTrack; + + case 'quaternion': + + return QuaternionKeyframeTrack; + + case 'bool': + case 'boolean': + + return BooleanKeyframeTrack; + + case 'string': + + return StringKeyframeTrack; + + } + + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); + + } + + function parseKeyframeTrack( json ) { + + if ( json.type === undefined ) { + + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + + } + + const trackType = getTrackTypeForValueTypeName( json.type ); + + if ( json.times === undefined ) { + + const times = [], values = []; + + 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 { + + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); + + } + + } + + const Cache = { + + enabled: false, + + files: {}, + + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + get: function ( key ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + clear: function () { + + this.files = {}; + + } + + }; + + class LoadingManager { + + constructor( onLoad, onProgress, onError ) { + + const scope = this; + + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor + + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } + + } + + isLoading = true; + + }; + + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); + + } + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + + } + + }; + + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + + } + + }; + + this.resolveURL = function ( url ) { + + if ( urlModifier ) { + + return urlModifier( url ); + + } + + return url; + + }; + + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + + return this; + + }; + + this.addHandler = function ( regex, loader ) { + + handlers.push( regex, loader ); + + return this; + + }; + + this.removeHandler = function ( regex ) { + + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); + + } + + return this; + + }; + + this.getHandler = function ( file ) { + + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; + + if ( regex.global ) regex.lastIndex = 0; // see #17920 + + if ( regex.test( file ) ) { + + return loader; + + } + + } + + return null; + + }; + + } + + } + + const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + + class Loader { + + constructor( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; + + } + + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.load( url, resolve, onProgress, reject ); + + } ); + + } + + parse( /* data */ ) {} + + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + setWithCredentials( value ) { + + this.withCredentials = value; + return this; + + } + + setPath( path ) { + + this.path = path; + return this; + + } + + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + setRequestHeader( requestHeader ) { + + this.requestHeader = requestHeader; + return this; + + } + + } + + const loading = {}; + + class HttpError extends Error { + + constructor( message, response ) { + + super( message ); + this.response = response; + + } + + } + + class FileLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + this.manager.itemStart( url ); + + setTimeout( () => { + + if ( onLoad ) onLoad( cached ); + + this.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + // Check if request is duplicate + + if ( loading[ url ] !== undefined ) { + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + return; + + } + + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, + } ); + + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + // An abort controller could be added within a future PR + } ); + + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; + + // start the fetch + fetch( req ) + .then( response => { + + if ( response.status === 200 || response.status === 0 ) { + + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. + + if ( response.status === 0 ) { + + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); + + } + + // Workaround: Checking if response.body === undefined for Alipay browser #23548 + + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { + + return response; + + } + + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + + // Nginx needs X-File-Size check + // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content + const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { + + readData(); + + function readData() { + + reader.read().then( ( { done, value } ) => { + + if ( done ) { + + controller.close(); + + } else { + + loaded += value.byteLength; + + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); + + } + + controller.enqueue( value ); + readData(); + + } + + } ); + + } + + } + + } ); + + return new Response( stream ); + + } else { + + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); + + } + + } ) + .then( response => { + + switch ( responseType ) { + + case 'arraybuffer': + + return response.arrayBuffer(); + + case 'blob': + + return response.blob(); + + case 'document': + + return response.text() + .then( text => { + + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); + + } ); + + case 'json': + + return response.json(); + + default: + + if ( mimeType === undefined ) { + + return response.text(); + + } else { + + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); + + } + + } + + } ) + .then( data => { + + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, data ); + + const callbacks = loading[ url ]; + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); + + } + + } ) + .catch( err => { + + // Abort errors and other errors are handled the same + + const callbacks = loading[ url ]; + + if ( callbacks === undefined ) { + + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; + + } + + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); + + } + + this.manager.itemError( url ); + + } ) + .finally( () => { + + this.manager.itemEnd( url ); + + } ); + + this.manager.itemStart( url ); + + } + + setResponseType( value ) { + + this.responseType = value; + return this; + + } + + setMimeType( value ) { + + this.mimeType = value; + return this; + + } + + } + + class AnimationLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const animations = []; + + for ( let i = 0; i < json.length; i ++ ) { + + const clip = AnimationClip.parse( json[ i ] ); + + animations.push( clip ); + + } + + return animations; + + } + + } + + /** + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + + class CompressedTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const images = []; + + const texture = new CompressedTexture(); + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( url[ i ], function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + + loaded += 1; + + if ( loaded === 6 ) { + + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; + + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, onProgress, onError ); + + } + + if ( Array.isArray( url ) ) { + + for ( let i = 0, il = url.length; i < il; ++ i ) { + + loadTexture( i ); + + } + + } else { + + // compressed cubemap texture stored in a single DDS file + + loader.load( url, function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + if ( texDatas.isCubemap ) { + + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + + for ( let f = 0; f < faces; f ++ ) { + + images[ f ] = { mipmaps: [] }; + + for ( let 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; + + } + + } + + texture.image = images; + + } else { + + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + + } + + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + }, onProgress, onError ); + + } + + return texture; + + } + + } + + class ImageLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const image = createElementNS( 'img' ); + + function onImageLoad() { + + removeEventListeners(); + + Cache.add( url, this ); + + if ( onLoad ) onLoad( this ); + + scope.manager.itemEnd( url ); + + } + + function onImageError( event ) { + + removeEventListeners(); + + if ( onError ) onError( event ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } + + function removeEventListeners() { + + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); + + } + + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); + + if ( url.slice( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + + } + + scope.manager.itemStart( url ); + + image.src = url; + + return image; + + } + + } + + class CubeTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( urls, onLoad, onProgress, onError ) { + + const texture = new CubeTexture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( urls[ i ], function ( image ) { + + texture.images[ i ] = image; + + loaded ++; + + if ( loaded === 6 ) { + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, undefined, onError ); + + } + + for ( let i = 0; i < urls.length; ++ i ) { + + loadTexture( i ); + + } + + return texture; + + } + + } + + /** + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + + class DataTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const texture = new DataTexture(); + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { + + const texData = scope.parse( buffer ); + + if ( ! texData ) return; + + if ( texData.image !== undefined ) { + + texture.image = texData.image; + + } else if ( texData.data !== undefined ) { + + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + + } + + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + + if ( texData.encoding !== undefined ) { + + texture.encoding = texData.encoding; + + } + + if ( texData.flipY !== undefined ) { + + texture.flipY = texData.flipY; + + } + + if ( texData.format !== undefined ) { + + texture.format = texData.format; + + } + + if ( texData.type !== undefined ) { + + texture.type = texData.type; + + } + + if ( texData.mipmaps !== undefined ) { + + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... + + } + + if ( texData.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + if ( texData.generateMipmaps !== undefined ) { + + texture.generateMipmaps = texData.generateMipmaps; + + } + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture, texData ); + + }, onProgress, onError ); + + + return texture; + + } + + } + + class TextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const texture = new Texture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + loader.load( url, function ( image ) { + + texture.image = image; + texture.needsUpdate = true; + + if ( onLoad !== undefined ) { + + onLoad( texture ); + + } + + }, onProgress, onError ); + + return texture; + + } + + } + + class Light extends Object3D { + + constructor( color, intensity = 1 ) { + + super(); + + this.isLight = true; + + this.type = 'Light'; + + this.color = new Color( color ); + this.intensity = intensity; + + } + + dispose() { + + // Empty here in base class; some subclasses override. + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.color.copy( source.color ); + this.intensity = source.intensity; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + + 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; + + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + + return data; + + } + + } + + class HemisphereLight extends Light { + + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.groundColor = new Color( groundColor ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; + + } + + } + + const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); + const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); + const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + + class LightShadow { + + constructor( camera ) { + + this.camera = camera; + + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + + this.mapSize = new Vector2( 512, 512 ); + + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + + this.autoUpdate = true; + this.needsUpdate = false; + + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); + + this._viewportCount = 1; + + this._viewports = [ + + new Vector4( 0, 0, 1, 1 ) + + ]; + + } + + getViewportCount() { + + return this._viewportCount; + + } + + getFrustum() { + + return this._frustum; + + } + + updateMatrices( light ) { + + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); + + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); + + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + + 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( _projScreenMatrix$1 ); + + } + + getViewport( viewportIndex ) { + + return this._viewports[ viewportIndex ]; + + } + + getFrameExtents() { + + return this._frameExtents; + + } + + dispose() { + + if ( this.map ) { + + this.map.dispose(); + + } + + if ( this.mapPass ) { + + this.mapPass.dispose(); + + } + + } + + copy( source ) { + + this.camera = source.camera.clone(); + + this.bias = source.bias; + this.radius = source.radius; + + this.mapSize.copy( source.mapSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + toJSON() { + + const object = {}; + + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; + + return object; + + } + + } + + class SpotLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + + this.isSpotLightShadow = true; + + this.focus = 1; + + } + + updateMatrices( light ) { + + const camera = this.camera; + + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); + + } + + super.updateMatrices( light ); + + } + + copy( source ) { + + super.copy( source ); + + this.focus = source.focus; + + return this; + + } + + } + + class SpotLight extends Light { + + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) { + + super( color, intensity ); + + this.isSpotLight = true; + + this.type = 'SpotLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + + this.map = null; + + this.shadow = new SpotLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + + this.target = source.target.clone(); + + this.shadow = source.shadow.clone(); + + return this; + + } + + } + + const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); + const _lightPositionWorld = /*@__PURE__*/ new Vector3(); + const _lookTarget = /*@__PURE__*/ new Vector3(); + + class PointLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + + this.isPointLightShadow = true; + + this._frameExtents = new Vector2( 4, 2 ); + + this._viewportCount = 6; + + this._viewports = [ + // 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 + + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; + + this._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 ) + ]; + + this._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 ) + ]; + + } + + updateMatrices( light, viewportIndex = 0 ) { + + const camera = this.camera; + const shadowMatrix = this.matrix; + + const far = light.distance || camera.far; + + if ( far !== camera.far ) { + + camera.far = far; + camera.updateProjectionMatrix(); + + } + + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); + + _lookTarget.copy( camera.position ); + _lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); + + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix ); + + } + + } + + class PointLight extends Light { + + constructor( color, intensity, distance = 0, decay = 2 ) { + + super( color, intensity ); + + this.isPointLight = true; + + this.type = 'PointLight'; + + this.distance = distance; + this.decay = decay; + + this.shadow = new PointLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.decay = source.decay; + + this.shadow = source.shadow.clone(); + + return this; + + } + + } + + class DirectionalLightShadow extends LightShadow { + + constructor() { + + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + + this.isDirectionalLightShadow = true; + + } + + } + + class DirectionalLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isDirectionalLight = true; + + this.type = 'DirectionalLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.shadow = new DirectionalLightShadow(); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + + return this; + + } + + } + + class AmbientLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isAmbientLight = true; + + this.type = 'AmbientLight'; + + } + + } + + class RectAreaLight extends Light { + + constructor( color, intensity, width = 10, height = 10 ) { + + super( color, intensity ); + + this.isRectAreaLight = true; + + this.type = 'RectAreaLight'; + + this.width = width; + this.height = height; + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); + + } + + copy( source ) { + + super.copy( source ); + + this.width = source.width; + this.height = source.height; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.width = this.width; + data.object.height = this.height; + + return data; + + } + + } + + /** + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ + + // 3-band SH defined by 9 coefficients + + class SphericalHarmonics3 { + + constructor() { + + this.isSphericalHarmonics3 = true; + + this.coefficients = []; + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients.push( new Vector3() ); + + } + + } + + set( coefficients ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].copy( coefficients[ i ] ); + + } + + return this; + + } + + zero() { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].set( 0, 0, 0 ); + + } + + return this; + + } + + // get the radiance in the direction of the normal + // target is a Vector3 + getAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; + + } + + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + + return target; + + } + + add( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].add( sh.coefficients[ i ] ); + + } + + return this; + + } + + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + + } + + return this; + + } + + scale( s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; + + } + + lerp( sh, alpha ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + + } + + return this; + + } + + equals( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { + + return false; + + } + + } + + return true; + + } + + copy( sh ) { + + return this.set( sh.coefficients ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + fromArray( array, offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); + + } + + return array; + + } + + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt( normal, shBasis ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + // band 0 + shBasis[ 0 ] = 0.282095; + + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; + + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); + + } + + } + + class LightProbe extends Light { + + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + + super( undefined, intensity ); + + this.isLightProbe = true; + + this.sh = sh; + + } + + copy( source ) { + + super.copy( source ); + + this.sh.copy( source.sh ); + + return this; + + } + + fromJSON( json ) { + + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.sh = this.sh.toArray(); + + return data; + + } + + } + + class MaterialLoader extends Loader { + + constructor( manager ) { + + super( manager ); + this.textures = {}; + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const textures = this.textures; + + function getTexture( name ) { + + if ( textures[ name ] === undefined ) { + + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + + } + + return textures[ name ]; + + } + + const material = MaterialLoader.createMaterialFromType( json.type ); + + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = json.sheen; + if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) material.transmission = json.transmission; + if ( json.thickness !== undefined ) material.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor ); + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide; + 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.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; + + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + + if ( json.rotation !== undefined ) material.rotation = json.rotation; + + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; + + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; + + if ( json.dithering !== undefined ) material.dithering = json.dithering; + + if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha; + + if ( json.visible !== undefined ) material.visible = json.visible; + + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; + + if ( json.userData !== undefined ) material.userData = json.userData; + + if ( json.vertexColors !== undefined ) { + + if ( typeof json.vertexColors === 'number' ) { + + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; + + } else { + + material.vertexColors = json.vertexColors; + + } + + } + + // Shader Material + + if ( json.uniforms !== undefined ) { + + for ( const name in json.uniforms ) { + + const uniform = json.uniforms[ name ]; + + material.uniforms[ name ] = {}; + + switch ( uniform.type ) { + + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; + + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; + + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; + + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; + + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; + + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; + + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; + + default: + material.uniforms[ name ].value = uniform.value; + + } + + } + + } + + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; + + if ( json.extensions !== undefined ) { + + for ( const key in json.extensions ) { + + material.extensions[ key ] = json.extensions[ key ]; + + } + + } + + // 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 = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); + + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); + + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { + + let normalScale = json.normalScale; + + if ( Array.isArray( normalScale ) === false ) { + + // Blender exporter used to export a scalar. See #7459 + + normalScale = [ normalScale, normalScale ]; + + } + + material.normalScale = new Vector2().fromArray( normalScale ); + + } + + if ( json.displacementMap !== undefined ) material.displacementMap = 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 = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap ); + if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); + + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; + + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; + + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); + + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); + + if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap ); + if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap ); + + return material; + + } + + setTextures( value ) { + + this.textures = value; + return this; + + } + + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + + return new materialLib[ type ](); + + } + + } + + class LoaderUtils { + + static decodeText( array ) { + + if ( typeof TextDecoder !== 'undefined' ) { + + return new TextDecoder().decode( array ); + + } + + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. + + let s = ''; + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); + + } + + try { + + // merges multi-byte utf-8 characters. + + return decodeURIComponent( escape( s ) ); + + } catch ( e ) { // see #16358 + + return s; + + } + + } + + static extractUrlBase( url ) { + + const index = url.lastIndexOf( '/' ); + + if ( index === - 1 ) return './'; + + return url.slice( 0, index + 1 ); + + } + + static resolveURL( url, path ) { + + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; + + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); + + } + + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; + + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; + + } + + } + + class InstancedBufferGeometry extends BufferGeometry { + + constructor() { + + super(); + + this.isInstancedBufferGeometry = true; + + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; + + } + + copy( source ) { + + super.copy( source ); + + this.instanceCount = source.instanceCount; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.instanceCount = this.instanceCount; + + data.isInstancedBufferGeometry = true; + + return data; + + } + + } + + class BufferGeometryLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + + function getInterleavedBuffer( json, uuid ) { + + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; + + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; + + interleavedBufferMap[ uuid ] = ib; + + return ib; + + } + + function getArrayBuffer( json, uuid ) { + + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; + + const ab = new Uint32Array( arrayBuffer ).buffer; + + arrayBufferMap[ uuid ] = ab; + + return ab; + + } + + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + + const index = json.data.index; + + if ( index !== undefined ) { + + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + + } + + const attributes = json.data.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); + + if ( attribute.updateRange !== undefined ) { + + bufferAttribute.updateRange.offset = attribute.updateRange.offset; + bufferAttribute.updateRange.count = attribute.updateRange.count; + + } + + geometry.setAttribute( key, bufferAttribute ); + + } + + const morphAttributes = json.data.morphAttributes; + + if ( morphAttributes ) { + + for ( const key in morphAttributes ) { + + const attributeArray = morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); + + } + + geometry.morphAttributes[ key ] = array; + + } + + } + + const morphTargetsRelative = json.data.morphTargetsRelative; + + if ( morphTargetsRelative ) { + + geometry.morphTargetsRelative = true; + + } + + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + + if ( groups !== undefined ) { + + for ( let i = 0, n = groups.length; i !== n; ++ i ) { + + const group = groups[ i ]; + + geometry.addGroup( group.start, group.count, group.materialIndex ); + + } + + } + + const boundingSphere = json.data.boundingSphere; + + if ( boundingSphere !== undefined ) { + + const center = new Vector3(); + + if ( boundingSphere.center !== undefined ) { + + center.fromArray( boundingSphere.center ); + + } + + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + + } + + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; + + return geometry; + + } + + } + + class ObjectLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + let json = null; + + try { + + json = JSON.parse( text ); + + } catch ( error ) { + + if ( onError !== undefined ) onError( error ); + + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + + return; + + } + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) ); + + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; + + } + + scope.parse( json, onLoad ); + + }, onProgress, onError ); + + } + + async loadAsync( url, onProgress ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + + const text = await loader.loadAsync( url, onProgress ); + + const json = JSON.parse( text ); + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); + + } + + return await scope.parseAsync( json ); + + } + + parse( json, onLoad ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = this.parseImages( json.images, function () { + + if ( onLoad !== undefined ) onLoad( object ); + + } ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + // + + if ( onLoad !== undefined ) { + + let hasImages = false; + + for ( const uuid in images ) { + + if ( images[ uuid ].data instanceof HTMLImageElement ) { + + hasImages = true; + break; + + } + + } + + if ( hasImages === false ) onLoad( object ); + + } + + return object; + + } + + async parseAsync( json ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = await this.parseImagesAsync( json.images ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + return object; + + } + + parseShapes( json ) { + + const shapes = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const shape = new Shape().fromJSON( json[ i ] ); + + shapes[ shape.uuid ] = shape; + + } + + } + + return shapes; + + } + + parseSkeletons( json, object ) { + + const skeletons = {}; + const bones = {}; + + // generate bone lookup table + + object.traverse( function ( child ) { + + if ( child.isBone ) bones[ child.uuid ] = child; + + } ); + + // create skeletons + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + + skeletons[ skeleton.uuid ] = skeleton; + + } + + } + + return skeletons; + + } + + parseGeometries( json, shapes ) { + + const geometries = {}; + + if ( json !== undefined ) { + + const bufferGeometryLoader = new BufferGeometryLoader(); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + let geometry; + const data = json[ i ]; + + switch ( data.type ) { + + case 'BufferGeometry': + case 'InstancedBufferGeometry': + + geometry = bufferGeometryLoader.parse( data ); + break; + + default: + + if ( data.type in Geometries ) { + + geometry = Geometries[ data.type ].fromJSON( data, shapes ); + + } else { + + console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` ); + + } + + } + + geometry.uuid = data.uuid; + + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; + + geometries[ data.uuid ] = geometry; + + } + + } + + return geometries; + + } + + parseMaterials( json, textures ) { + + const cache = {}; // MultiMaterial + const materials = {}; + + if ( json !== undefined ) { + + const loader = new MaterialLoader(); + loader.setTextures( textures ); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( cache[ data.uuid ] === undefined ) { + + cache[ data.uuid ] = loader.parse( data ); + + } + + materials[ data.uuid ] = cache[ data.uuid ]; + + } + + } + + return materials; + + } + + parseAnimations( json ) { + + const animations = {}; + + if ( json !== undefined ) { + + for ( let i = 0; i < json.length; i ++ ) { + + const data = json[ i ]; + + const clip = AnimationClip.parse( data ); + + animations[ clip.uuid ] = clip; + + } + + } + + return animations; + + } + + parseImages( json, onLoad ) { + + const scope = this; + const images = {}; + + let loader; + + function loadImage( url ) { + + scope.manager.itemStart( url ); + + return loader.load( url, function () { + + scope.manager.itemEnd( url ); + + }, undefined, function () { + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + } + + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return loadImage( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + const manager = new LoadingManager( onLoad ); + + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + + } + + } + + } + + return images; + + } + + async parseImagesAsync( json ) { + + const scope = this; + const images = {}; + + let loader; + + async function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return await loader.loadAsync( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = await deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + } + + } + + } + + return images; + + } + + parseTextures( json, images ) { + + function parseConstant( value, type ) { + + if ( typeof value === 'number' ) return value; + + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; + + } + + const textures = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( data.image === undefined ) { + + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + + } + + if ( images[ data.image ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + + } + + const source = images[ data.image ]; + const image = source.data; + + let texture; + + if ( Array.isArray( image ) ) { + + texture = new CubeTexture(); + + if ( image.length === 6 ) texture.needsUpdate = true; + + } else { + + if ( image && image.data ) { + + texture = new DataTexture(); + + } else { + + texture = new Texture(); + + } + + if ( image ) texture.needsUpdate = true; // textures can have undefined image data + + } + + texture.source = source; + + texture.uuid = data.uuid; + + if ( data.name !== undefined ) texture.name = data.name; + + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; + + if ( data.wrap !== undefined ) { + + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + + } + + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; + + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + + if ( data.flipY !== undefined ) texture.flipY = data.flipY; + + if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps; + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + + if ( data.userData !== undefined ) texture.userData = data.userData; + + textures[ data.uuid ] = texture; + + } + + } + + return textures; + + } + + parseObject( data, geometries, materials, textures, animations ) { + + let object; + + function getGeometry( name ) { + + if ( geometries[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + + } + + return geometries[ name ]; + + } + + function getMaterial( name ) { + + if ( name === undefined ) return undefined; + + if ( Array.isArray( name ) ) { + + const array = []; + + for ( let i = 0, l = name.length; i < l; i ++ ) { + + const uuid = name[ i ]; + + if ( materials[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + + } + + array.push( materials[ uuid ] ); + + } + + return array; + + } + + if ( materials[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', name ); + + } + + return materials[ name ]; + + } + + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined texture', uuid ); + + } + + return textures[ uuid ]; + + } + + let geometry, material; + + switch ( data.type ) { + + case 'Scene': + + object = new Scene(); + + if ( data.background !== undefined ) { + + if ( Number.isInteger( data.background ) ) { + + object.background = new Color( data.background ); + + } else { + + object.background = getTexture( data.background ); + + } + + } + + if ( data.environment !== undefined ) { + + object.environment = getTexture( data.environment ); + + } + + if ( data.fog !== undefined ) { + + if ( data.fog.type === 'Fog' ) { + + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + + } else if ( data.fog.type === 'FogExp2' ) { + + object.fog = new FogExp2( data.fog.color, data.fog.density ); + + } + + } + + if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; + if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + + break; + + case 'PerspectiveCamera': + + 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 ); + + break; + + case 'OrthographicCamera': + + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + + break; + + case 'AmbientLight': + + object = new AmbientLight( data.color, data.intensity ); + + break; + + case 'DirectionalLight': + + object = new DirectionalLight( data.color, data.intensity ); + + break; + + case 'PointLight': + + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + + break; + + case 'RectAreaLight': + + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + + break; + + case 'SpotLight': + + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + + break; + + case 'HemisphereLight': + + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + + break; + + case 'LightProbe': + + object = new LightProbe().fromJSON( data ); + + break; + + case 'SkinnedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new SkinnedMesh( geometry, material ); + + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + + break; + + case 'Mesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new Mesh( geometry, material ); + + break; + + case 'InstancedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); + + break; + + case 'LOD': + + object = new LOD(); + + break; + + case 'Line': + + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineLoop': + + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineSegments': + + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'PointCloud': + case 'Points': + + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'Sprite': + + object = new Sprite( getMaterial( data.material ) ); + + break; + + case 'Group': + + object = new Group(); + + break; + + case 'Bone': + + object = new Bone(); + + break; + + default: + + object = new Object3D(); + + } + + object.uuid = data.uuid; + + if ( data.name !== undefined ) object.name = data.name; + + if ( data.matrix !== undefined ) { + + object.matrix.fromArray( data.matrix ); + + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.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.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + 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; + + if ( data.shadow ) { + + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + + } + + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; + + if ( data.children !== undefined ) { + + const children = data.children; + + for ( let i = 0; i < children.length; i ++ ) { + + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); + + } + + } + + if ( data.animations !== undefined ) { + + const objectAnimations = data.animations; + + for ( let i = 0; i < objectAnimations.length; i ++ ) { + + const uuid = objectAnimations[ i ]; + + object.animations.push( animations[ uuid ] ); + + } + + } + + if ( data.type === 'LOD' ) { + + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + + const levels = data.levels; + + for ( let l = 0; l < levels.length; l ++ ) { + + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); + + if ( child !== undefined ) { + + object.addLevel( child, level.distance, level.hysteresis ); + + } + + } + + } + + return object; + + } + + bindSkeletons( object, skeletons ) { + + if ( Object.keys( skeletons ).length === 0 ) return; + + object.traverse( function ( child ) { + + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + + const skeleton = skeletons[ child.skeleton ]; + + if ( skeleton === undefined ) { + + console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); + + } else { + + child.bind( skeleton, child.bindMatrix ); + + } + + } + + } ); + + } + + } + + const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping + }; + + const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping + }; + + const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter + }; + + class ImageBitmapLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + this.isImageBitmapLoader = true; + + if ( typeof createImageBitmap === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + + } + + if ( typeof fetch === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + + } + + this.options = { premultiplyAlpha: 'none' }; + + } + + setOptions( options ) { + + this.options = options; + + return this; + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; + + fetch( url, fetchOptions ).then( function ( res ) { + + return res.blob(); + + } ).then( function ( blob ) { + + return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); + + } ).then( function ( imageBitmap ) { + + Cache.add( url, imageBitmap ); + + if ( onLoad ) onLoad( imageBitmap ); + + scope.manager.itemEnd( url ); + + } ).catch( function ( e ) { + + if ( onError ) onError( e ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + scope.manager.itemStart( url ); + + } + + } + + let _context; + + class AudioContext { + + static getContext() { + + if ( _context === undefined ) { + + _context = new ( window.AudioContext || window.webkitAudioContext )(); + + } + + return _context; + + } + + static setContext( value ) { + + _context = value; + + } + + } + + class AudioLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { + + try { + + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); + + const context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { + + onLoad( audioBuffer ); + + } ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + } + + class HemisphereLightProbe extends LightProbe { + + constructor( skyColor, groundColor, intensity = 1 ) { + + super( undefined, intensity ); + + this.isHemisphereLightProbe = true; + + const color1 = new Color().set( skyColor ); + const color2 = new Color().set( groundColor ); + + const sky = new Vector3( color1.r, color1.g, color1.b ); + const ground = new Vector3( color2.r, color2.g, color2.b ); + + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + const c0 = Math.sqrt( Math.PI ); + const c1 = c0 * Math.sqrt( 0.75 ); + + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + + } + + } + + class AmbientLightProbe extends LightProbe { + + constructor( color, intensity = 1 ) { + + super( undefined, intensity ); + + this.isAmbientLightProbe = true; + + const color1 = new Color().set( color ); + + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + + } + + } + + const _eyeRight = /*@__PURE__*/ new Matrix4(); + const _eyeLeft = /*@__PURE__*/ new Matrix4(); + const _projectionMatrix = /*@__PURE__*/ new Matrix4(); + + class StereoCamera { + + constructor() { + + this.type = 'StereoCamera'; + + this.aspect = 1; + + this.eyeSep = 0.064; + + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; + + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; + + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + + } + + update( camera ) { + + const cache = this._cache; + + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + + if ( needsUpdate ) { + + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ + + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; + + // translate xOffset + + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; + + // for left eye + + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraL.projectionMatrix.copy( _projectionMatrix ); + + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + + } + + } + + class Clock { + + constructor( autoStart = true ) { + + this.autoStart = autoStart; + + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + + this.running = false; + + } + + start() { + + this.startTime = now(); + + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + + } + + stop() { + + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + + } + + getElapsedTime() { + + this.getDelta(); + return this.elapsedTime; + + } + + getDelta() { + + let diff = 0; + + if ( this.autoStart && ! this.running ) { + + this.start(); + return 0; + + } + + if ( this.running ) { + + const newTime = now(); + + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; + + this.elapsedTime += diff; + + } + + return diff; + + } + + } + + function now() { + + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + + } + + const _position$1 = /*@__PURE__*/ new Vector3(); + const _quaternion$1 = /*@__PURE__*/ new Quaternion(); + const _scale$1 = /*@__PURE__*/ new Vector3(); + const _orientation$1 = /*@__PURE__*/ new Vector3(); + + class AudioListener extends Object3D { + + constructor() { + + super(); + + this.type = 'AudioListener'; + + this.context = AudioContext.getContext(); + + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); + + this.filter = null; + + this.timeDelta = 0; + + // private + + this._clock = new Clock(); + + } + + getInput() { + + return this.gain; + + } + + removeFilter() { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; + + } + + return this; + + } + + getFilter() { + + return this.filter; + + } + + setFilter( value ) { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + + } else { + + this.gain.disconnect( this.context.destination ); + + } + + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); + + return this; + + } + + getMasterVolume() { + + return this.gain.gain.value; + + } + + setMasterVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + const listener = this.context.listener; + const up = this.up; + + this.timeDelta = this._clock.getDelta(); + + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); + + _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 ); + + if ( listener.positionX ) { + + // code path for Chrome (see #14393) + + const endTime = this.context.currentTime + this.timeDelta; + + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); + + } else { + + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z ); + + } + + } + + } + + class Audio extends Object3D { + + constructor( listener ) { + + super(); + + this.type = 'Audio'; + + this.listener = listener; + this.context = listener.context; + + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); + + this.autoplay = false; + + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = 'empty'; + + this._startedAt = 0; + this._progress = 0; + this._connected = false; + + this.filters = []; + + } + + getOutput() { + + return this.gain; + + } + + setNodeSource( audioNode ) { + + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; + + } + + setMediaElementSource( mediaElement ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); + + return this; + + } + + setMediaStreamSource( mediaStream ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); + + return this; + + } + + setBuffer( audioBuffer ) { + + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; + + } + + play( delay = 0 ) { + + if ( this.isPlaying === true ) { + + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; + + } + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._startedAt = this.context.currentTime + delay; + + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); + + this.isPlaying = true; + + this.source = source; + + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); + + return this.connect(); + + } + + pause() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + if ( this.isPlaying === true ) { + + // update current progress + + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + + if ( this.loop === true ) { + + // ensure _progress does not exceed duration with looped audios + + this._progress = this._progress % ( this.duration || this.buffer.duration ); + + } + + this.source.stop(); + this.source.onended = null; + + this.isPlaying = false; + + } + + return this; + + } + + stop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._progress = 0; + + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + + return this; + + } + + connect() { + + if ( this.filters.length > 0 ) { + + this.source.connect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].connect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + + } else { + + this.source.connect( this.getOutput() ); + + } + + this._connected = true; + + return this; + + } + + disconnect() { + + if ( this.filters.length > 0 ) { + + this.source.disconnect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + + } else { + + this.source.disconnect( this.getOutput() ); + + } + + this._connected = false; + + return this; + + } + + getFilters() { + + return this.filters; + + } + + setFilters( value ) { + + if ( ! value ) value = []; + + if ( this._connected === true ) { + + this.disconnect(); + this.filters = value.slice(); + this.connect(); + + } else { + + this.filters = value.slice(); + + } + + return this; + + } + + setDetune( value ) { + + this.detune = value; + + if ( this.source.detune === undefined ) return; // only set detune when available + + if ( this.isPlaying === true ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getDetune() { + + return this.detune; + + } + + getFilter() { + + return this.getFilters()[ 0 ]; + + } + + setFilter( filter ) { + + return this.setFilters( filter ? [ filter ] : [] ); + + } + + setPlaybackRate( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.playbackRate = value; + + if ( this.isPlaying === true ) { + + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getPlaybackRate() { + + return this.playbackRate; + + } + + onEnded() { + + this.isPlaying = false; + + } + + getLoop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; + + } + + return this.loop; + + } + + setLoop( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.loop = value; + + if ( this.isPlaying === true ) { + + this.source.loop = this.loop; + + } + + return this; + + } + + setLoopStart( value ) { + + this.loopStart = value; + + return this; + + } + + setLoopEnd( value ) { + + this.loopEnd = value; + + return this; + + } + + getVolume() { + + return this.gain.gain.value; + + } + + setVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + } + + const _position = /*@__PURE__*/ new Vector3(); + const _quaternion = /*@__PURE__*/ new Quaternion(); + const _scale = /*@__PURE__*/ new Vector3(); + const _orientation = /*@__PURE__*/ new Vector3(); + + class PositionalAudio extends Audio { + + constructor( listener ) { + + super( listener ); + + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); + + } + + disconnect() { + + super.disconnect(); + + this.panner.disconnect( this.gain ); + + } + + getOutput() { + + return this.panner; + + } + + getRefDistance() { + + return this.panner.refDistance; + + } + + setRefDistance( value ) { + + this.panner.refDistance = value; + + return this; + + } + + getRolloffFactor() { + + return this.panner.rolloffFactor; + + } + + setRolloffFactor( value ) { + + this.panner.rolloffFactor = value; + + return this; + + } + + getDistanceModel() { + + return this.panner.distanceModel; + + } + + setDistanceModel( value ) { + + this.panner.distanceModel = value; + + return this; + + } + + getMaxDistance() { + + return this.panner.maxDistance; + + } + + setMaxDistance( value ) { + + this.panner.maxDistance = value; + + return this; + + } + + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + + this.matrixWorld.decompose( _position, _quaternion, _scale ); + + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); + + const panner = this.panner; + + if ( panner.positionX ) { + + // code path for Chrome and Firefox (see #14393) + + const endTime = this.context.currentTime + this.listener.timeDelta; + + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); + + } else { + + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); + + } + + } + + } + + class AudioAnalyser { + + constructor( audio, fftSize = 2048 ) { + + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); + + } + + + getFrequencyData() { + + this.analyser.getByteFrequencyData( this.data ); + + return this.data; + + } + + getAverageFrequency() { + + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; + + } + + return value / data.length; + + } + + } + + class PropertyMixer { + + constructor( binding, typeName, valueSize ) { + + this.binding = binding; + this.valueSize = valueSize; + + let mixFunction, + mixFunctionAdditive, + setIdentity; + + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // 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 + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results + + switch ( typeName ) { + + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; + + case 'string': + case 'bool': + mixFunction = this._select; + + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; + + setIdentity = this._setAdditiveIdentityOther; + + this.buffer = new Array( valueSize * 5 ); + break; + + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + + this.buffer = new Float64Array( valueSize * 5 ); + + } + + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + this.useCount = 0; + this.referenceCount = 0; + + } + + // accumulate data in the 'incoming' region into 'accu' + accumulate( 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 + + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; + + let currentWeight = this.cumulativeWeight; + + if ( currentWeight === 0 ) { + + // accuN := incoming * weight + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ offset + i ] = buffer[ i ]; + + } + + currentWeight = weight; + + } else { + + // accuN := accuN + incoming * weight + + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); + + } + + this.cumulativeWeight = currentWeight; + + } + + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive( weight ) { + + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; + + if ( this.cumulativeWeightAdditive === 0 ) { + + // add = identity + + this._setIdentity(); + + } + + // add := add + incoming * weight + + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; + + } + + // apply the state of 'accu' to the binding when accus differ + apply( accuIndex ) { + + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, + + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, + + binding = this.binding; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + if ( weight < 1 ) { + + // accuN := accuN + original * ( 1 - cumulativeWeight ) + + const originalValueOffset = stride * this._origIndex; + + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); + + } + + if ( weightAdditive > 0 ) { + + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + + } + + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + + if ( buffer[ i ] !== buffer[ i + stride ] ) { + + // value has changed -> update scene graph + + binding.setValue( buffer, offset ); + break; + + } + + } + + } + + // remember the state of the bound property and copy it to both accus + saveOriginalState() { + + const binding = this.binding; + + const buffer = this.buffer, + stride = this.valueSize, + + originalValueOffset = stride * this._origIndex; + + binding.getValue( buffer, originalValueOffset ); + + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + + } + + // Add to identity for additive + this._setIdentity(); + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + } + + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { + + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); + + } + + _setAdditiveIdentityNumeric() { + + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + + for ( let i = startIndex; i < endIndex; i ++ ) { + + this.buffer[ i ] = 0; + + } + + } + + _setAdditiveIdentityQuaternion() { + + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + + } + + _setAdditiveIdentityOther() { + + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + + for ( let i = 0; i < this.valueSize; i ++ ) { + + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + + } + + } + + + // mix functions + + _select( buffer, dstOffset, srcOffset, t, stride ) { + + if ( t >= 0.5 ) { + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } + + } + + } + + _slerp( buffer, dstOffset, srcOffset, t ) { + + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + + } + + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + const workOffset = this._workIndex * stride; + + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + + } + + _lerp( buffer, dstOffset, srcOffset, t, stride ) { + + const s = 1 - t; + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + + } + + } + + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + + } + + } + + } + + // Characters [].:/ are reserved for track binding syntax. + const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; + const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + + // Attempts to allow node names from any language. ES5's `\w` regexp matches + // only latin characters, and the unicode \p{L} is not yet supported. So + // instead, we exclude reserved characters and match everything else. + const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; + const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + + // Parent directories, delimited by '/' or ':'. Currently unused, but must + // be matched to parse the rest of the track name. + const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + + // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. + const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + + // Object on target node, and accessor. May not contain reserved + // characters. Accessor may contain any character except closing bracket. + const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + + // Property and accessor. May not contain reserved characters. Accessor may + // contain any non-bracket characters. + const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + + const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' + ); + + const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; + + class Composite { + + constructor( targetGroup, path, optionalParsedPath ) { + + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); + + } + + getValue( array, offset ) { + + this.bind(); // bind all binding + + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); + + } + + setValue( array, offset ) { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].setValue( array, offset ); + + } + + } + + bind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].bind(); + + } + + } + + unbind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].unbind(); + + } + + } + + } + + // 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. + class PropertyBinding { + + constructor( rootNode, path, parsedPath ) { + + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + + this.rootNode = rootNode; + + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + + } + + + static create( root, path, parsedPath ) { + + if ( ! ( root && root.isAnimationObjectGroup ) ) { + + return new PropertyBinding( root, path, parsedPath ); + + } else { + + return new PropertyBinding.Composite( root, path, parsedPath ); + + } + + } + + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName( name ) { + + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + + } + + static parseTrackName( trackName ) { + + const matches = _trackRe.exec( trackName ); + + if ( matches === null ) { + + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + + } + + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; + + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + + if ( lastDot !== undefined && lastDot !== - 1 ) { + + const objectName = results.nodeName.substring( lastDot + 1 ); + + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; + + } + + } + + if ( results.propertyName === null || results.propertyName.length === 0 ) { + + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + + } + + return results; + + } + + static findNode( root, nodeName ) { + + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + + return root; + + } + + // search into skeleton bones. + if ( root.skeleton ) { + + const bone = root.skeleton.getBoneByName( nodeName ); + + if ( bone !== undefined ) { + + return bone; + + } + + } + + // search into node subtree. + if ( root.children ) { + + const searchNodeSubtree = function ( children ) { + + for ( let i = 0; i < children.length; i ++ ) { + + const childNode = children[ i ]; + + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + + return childNode; + + } + + const result = searchNodeSubtree( childNode.children ); + + if ( result ) return result; + + } + + return null; + + }; + + const subTreeNode = searchNodeSubtree( root.children ); + + if ( subTreeNode ) { + + return subTreeNode; + + } + + } + + return null; + + } + + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} + + // Getters + + _getValue_direct( buffer, offset ) { + + buffer[ offset ] = this.targetObject[ this.propertyName ]; + + } + + _getValue_array( buffer, offset ) { + + const source = this.resolvedProperty; + + for ( let i = 0, n = source.length; i !== n; ++ i ) { + + buffer[ offset ++ ] = source[ i ]; + + } + + } + + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + + } + + _getValue_toArray( buffer, offset ) { + + this.resolvedProperty.toArray( buffer, offset ); + + } + + // Direct + + _setValue_direct( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + + } + + _setValue_direct_setNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // EntireArray + + _setValue_array( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + } + + _setValue_array_setNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.needsUpdate = true; + + } + + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // ArrayElement + + _setValue_arrayElement( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + + } + + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // HasToFromArray + + _setValue_fromArray( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + + } + + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; + + } + + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + _getValue_unbound( targetArray, offset ) { + + this.bind(); + this.getValue( targetArray, offset ); + + } + + _setValue_unbound( sourceArray, offset ) { + + this.bind(); + this.setValue( sourceArray, offset ); + + } + + // create getter / setter pair for a property in the scene graph + bind() { + + let targetObject = this.node; + const parsedPath = this.parsedPath; + + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + + if ( ! targetObject ) { + + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + + this.node = targetObject; + + } + + // 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 ) { + + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; + + } + + if ( objectName ) { + + let objectIndex = parsedPath.objectIndex; + + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { + + case 'materials': + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.materials ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; + + } + + targetObject = targetObject.material.materials; + + break; + + case 'bones': + + if ( ! targetObject.skeleton ) { + + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; + + } + + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. + + targetObject = targetObject.skeleton.bones; + + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { + + if ( targetObject[ i ].name === objectIndex ) { + + objectIndex = i; + break; + + } + + } + + break; + + case 'map': + + if ( 'map' in targetObject ) { + + targetObject = targetObject.map; + break; + + } + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.map ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; + + } + + targetObject = targetObject.material.map; + break; + + default: + + if ( targetObject[ objectName ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; + + } + + targetObject = targetObject[ objectName ]; + + } + + + if ( objectIndex !== undefined ) { + + if ( targetObject[ objectIndex ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; + + } + + targetObject = targetObject[ objectIndex ]; + + } + + } + + // resolve property + const nodeProperty = targetObject[ propertyName ]; + + if ( nodeProperty === undefined ) { + + const nodeName = parsedPath.nodeName; + + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; + + } + + // determine versioning scheme + let versioning = this.Versioning.None; + + this.targetObject = targetObject; + + if ( targetObject.needsUpdate !== undefined ) { // material + + versioning = this.Versioning.NeedsUpdate; + + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + + versioning = this.Versioning.MatrixWorldNeedsUpdate; + + } + + // determine how the property gets bound + let 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. + + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; + + } + + if ( ! targetObject.geometry.morphAttributes ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + + } + + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + + } + + } + + bindingType = this.BindingType.ArrayElement; + + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + + // must use copy for Object3D.Euler/Quaternion + + bindingType = this.BindingType.HasFromToArray; + + this.resolvedProperty = nodeProperty; + + } else if ( Array.isArray( nodeProperty ) ) { + + bindingType = this.BindingType.EntireArray; + + this.resolvedProperty = nodeProperty; + + } else { + + this.propertyName = propertyName; + + } + + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + + } + + unbind() { + + this.node = null; + + // 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; + + } + + } + + PropertyBinding.Composite = Composite; + + PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + + PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + + PropertyBinding.prototype.GetterByBindingType = [ + + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, + + ]; + + PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, + + ], [ + + // EntireArray + + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, + + ], [ + + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, + + ], [ + + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, + + ] + + ]; + + /** + * + * 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. + */ + + class AnimationObjectGroup { + + constructor() { + + this.isAnimationObjectGroup = true; + + this.uuid = generateUUID(); + + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); + + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite + + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + indices[ arguments[ i ].uuid ] = 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 + + const scope = this; + + this.stats = { + + objects: { + get total() { + + return scope._objects.length; + + }, + get inUse() { + + return this.total - scope.nCachedObjects_; + + } + }, + get bindingsPerObject() { + + return scope._bindings.length; + + } + + }; + + } + + add() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; + + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; + + if ( index === undefined ) { + + // unknown object -> add it to the ACTIVE region + + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + + } + + } else if ( index < nCachedObjects ) { + + knownObject = objects[ index ]; + + // move existing object to the ACTIVE region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; + + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; + + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; + + let binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = lastCached; + + if ( binding === undefined ) { + + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist + + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + + } + + bindingsForPath[ firstActiveIndex ] = binding; + + } + + } else if ( objects[ index ] !== knownObject ) { + + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); + + } // else the object is already where we want it to be + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + remove() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined && index >= nCachedObjects ) { + + // move existing object into the CACHED region + + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; + + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; + + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; + + } + + } + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // remove & forget + uncache() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined ) { + + delete indicesByUUID[ uuid ]; + + if ( index < nCachedObjects ) { + + // object is cached, shrink the CACHED region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + // 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(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; + + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); + + } + + } else { + + // object is active, just swap with the last and pop + + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + if ( lastIndex > 0 ) { + + indicesByUUID[ lastObject.uuid ] = index; + + } + + objects[ index ] = lastObject; + objects.pop(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ]; + + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); + + } + + } // cached or active + + } // if object is known + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // Internal interface used by befriended PropertyBinding.Composite: + + subscribe_( path, parsedPath ) { + + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group + + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; + + if ( index !== undefined ) return bindings[ index ]; + + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); + + index = bindings.length; + + indicesByPath[ path ] = index; + + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); + + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + + } + + return bindingsForPath; + + } + + unsubscribe_( path ) { + + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' + + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; + + if ( index !== undefined ) { + + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; + + indicesByPath[ lastBindingsPath ] = index; + + bindings[ index ] = lastBindings; + bindings.pop(); + + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); + + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); + + } + + } + + } + + class AnimationAction { + + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); + + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + + for ( let i = 0; i !== nTracks; ++ i ) { + + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; + + } + + this._interpolantSettings = interpolantSettings; + + this._interpolants = interpolants; // bound by the mixer + + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); + + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager + + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + + this.loop = LoopRepeat; + this._loopCount = - 1; + + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; + + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; + + this.timeScale = 1; + this._effectiveTimeScale = 1; + + this.weight = 1; + this._effectiveWeight = 1; + + this.repetitions = Infinity; // no. of repetitions when looping + + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight + + this.clampWhenFinished = false;// keep feeding the last frame? + + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end + + } + + // State & Scheduling + + play() { + + this._mixer._activateAction( this ); + + return this; + + } + + stop() { + + this._mixer._deactivateAction( this ); + + return this.reset(); + + } + + reset() { + + 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(); + + } + + isRunning() { + + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); + + } + + // return true when play has been called + isScheduled() { + + return this._mixer._isActiveAction( this ); + + } + + startAt( time ) { + + this._startTime = time; + + return this; + + } + + setLoop( mode, repetitions ) { + + this.loop = mode; + this.repetitions = repetitions; + + return this; + + } + + // Weight + + // 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( weight ) { + + this.weight = weight; + + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; + + return this.stopFading(); + + } + + // return the weight considering fading and .enabled + getEffectiveWeight() { + + return this._effectiveWeight; + + } + + fadeIn( duration ) { + + return this._scheduleFading( duration, 0, 1 ); + + } + + fadeOut( duration ) { + + return this._scheduleFading( duration, 1, 0 ); + + } + + crossFadeFrom( fadeOutAction, duration, warp ) { + + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); + + if ( warp ) { + + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, + + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; + + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); + + } + + return this; + + } + + crossFadeTo( fadeInAction, duration, warp ) { + + return fadeInAction.crossFadeFrom( this, duration, warp ); + + } + + stopFading() { + + const weightInterpolant = this._weightInterpolant; + + if ( weightInterpolant !== null ) { + + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); + + } + + return this; + + } + + // Time Scale Control + + // set the time scale 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( timeScale ) { + + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + + return this.stopWarping(); + + } + + // return the time scale considering warping and .paused + getEffectiveTimeScale() { + + return this._effectiveTimeScale; + + } + + setDuration( duration ) { + + this.timeScale = this._clip.duration / duration; + + return this.stopWarping(); + + } + + syncWith( action ) { + + this.time = action.time; + this.timeScale = action.timeScale; + + return this.stopWarping(); + + } + + halt( duration ) { + + return this.warp( this._effectiveTimeScale, 0, duration ); + + } + + warp( startTimeScale, endTimeScale, duration ) { + + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; + + let interpolant = this._timeScaleInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + times[ 1 ] = now + duration; + + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; + + return this; + + } + + stopWarping() { + + const timeScaleInterpolant = this._timeScaleInterpolant; + + if ( timeScaleInterpolant !== null ) { + + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + + } + + return this; + + } + + // Object Accessors + + getMixer() { + + return this._mixer; + + } + + getClip() { + + return this._clip; + + } + + getRoot() { + + return this._localRoot || this._mixer._root; + + } + + // Interna + + _update( time, deltaTime, timeDirection, accuIndex ) { + + // called by the mixer + + if ( ! this.enabled ) { + + // call ._updateWeight() to update ._effectiveWeight + + this._updateWeight( time ); + return; + + } + + const startTime = this._startTime; + + if ( startTime !== null ) { + + // check for scheduled start of action + + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { + + deltaTime = 0; + + } else { + + + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; + + } + + } + + // apply time scale and advance time + + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); + + // note: _updateTime may disable the action resulting in + // an effective weight of 0 + + const weight = this._updateWeight( time ); + + if ( weight > 0 ) { + + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + + switch ( this.blendMode ) { + + case AdditiveAnimationBlendMode: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); + + } + + break; + + case NormalAnimationBlendMode: + default: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); + + } + + } + + } + + } + + _updateWeight( time ) { + + let weight = 0; + + if ( this.enabled ) { + + weight = this.weight; + const interpolant = this._weightInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + weight *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopFading(); + + if ( interpolantValue === 0 ) { + + // faded out, disable + this.enabled = false; + + } + + } + + } + + } + + this._effectiveWeight = weight; + return weight; + + } + + _updateTimeScale( time ) { + + let timeScale = 0; + + if ( ! this.paused ) { + + timeScale = this.timeScale; + + const interpolant = this._timeScaleInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + timeScale *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopWarping(); + + if ( timeScale === 0 ) { + + // motion has halted, pause + this.paused = true; + + } else { + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + } + + } + + } + + this._effectiveTimeScale = timeScale; + return timeScale; + + } + + _updateTime( deltaTime ) { + + const duration = this._clip.duration; + const loop = this.loop; + + let time = this.time + deltaTime; + let loopCount = this._loopCount; + + const pingPong = ( loop === LoopPingPong ); + + if ( deltaTime === 0 ) { + + if ( loopCount === - 1 ) return time; + + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + + } + + if ( loop === LoopOnce ) { + + if ( loopCount === - 1 ) { + + // just started + + this._loopCount = 0; + this._setEndings( true, true, false ); + + } + + handle_stop: { + + if ( time >= duration ) { + + time = duration; + + } else if ( time < 0 ) { + + time = 0; + + } else { + + this.time = time; + + break handle_stop; + + } + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); + + } + + } else { // repetitive Repeat or PingPong + + if ( loopCount === - 1 ) { + + // just started + + if ( deltaTime >= 0 ) { + + loopCount = 0; + + this._setEndings( true, this.repetitions === 0, pingPong ); + + } else { + + // 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 ( time >= duration || time < 0 ) { + + // wrap around + + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; + + loopCount += Math.abs( loopDelta ); + + const pending = this.repetitions - loopCount; + + if ( pending <= 0 ) { + + // have to stop (switch state, clamp time, fire event) + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + time = deltaTime > 0 ? duration : 0; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); + + } else { + + // keep running + + if ( pending === 1 ) { + + // entering the last round + + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); + + } else { + + this._setEndings( false, false, pingPong ); + + } + + this._loopCount = loopCount; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); + + } + + } else { + + this.time = time; + + } + + if ( pingPong && ( loopCount & 1 ) === 1 ) { + + // invert time for the "pong round" + + return duration - time; + + } + + } + + return time; + + } + + _setEndings( atStart, atEnd, pingPong ) { + + const settings = this._interpolantSettings; + + if ( pingPong ) { + + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + + } else { + + // assuming for LoopOnce atStart == atEnd == true + + if ( atStart ) { + + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingStart = WrapAroundEnding; + + } + + if ( atEnd ) { + + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingEnd = WrapAroundEnding; + + } + + } + + } + + _scheduleFading( duration, weightNow, weightThen ) { + + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; + + return this; + + } + + } + + const _controlInterpolantsResultBuffer = new Float32Array( 1 ); + + + class AnimationMixer extends EventDispatcher { + + constructor( root ) { + + super(); + + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1.0; + + } + + _bindAction( action, prototypeAction ) { + + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; + + let bindingsByName = bindingsByRoot[ rootUuid ]; + + if ( bindingsByName === undefined ) { + + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; + + } + + for ( let i = 0; i !== nTracks; ++ i ) { + + const track = tracks[ i ], + trackName = track.name; + + let binding = bindingsByName[ trackName ]; + + if ( binding !== undefined ) { + + ++ binding.referenceCount; + bindings[ i ] = binding; + + } else { + + binding = bindings[ i ]; + + if ( binding !== undefined ) { + + // existing binding, make sure the cache knows + + if ( binding._cacheIndex === null ) { + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + } + + continue; + + } + + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; + + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + bindings[ i ] = binding; + + } + + interpolants[ i ].resultBuffer = binding.buffer; + + } + + } + + _activateAction( action ) { + + if ( ! this._isActiveAction( action ) ) { + + if ( action._cacheIndex === null ) { + + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind + + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; + + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); + + this._addInactiveAction( action, clipUuid, rootUuid ); + + } + + const bindings = action._propertyBindings; + + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( binding.useCount ++ === 0 ) { + + this._lendBinding( binding ); + binding.saveOriginalState(); + + } + + } + + this._lendAction( action ); + + } + + } + + _deactivateAction( action ) { + + if ( this._isActiveAction( action ) ) { + + const bindings = action._propertyBindings; + + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.useCount === 0 ) { + + binding.restoreOriginalState(); + this._takeBackBinding( binding ); + + } + + } + + this._takeBackAction( action ); + + } + + } + + // Memory manager + + _initMemoryManager() { + + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; + + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } + + + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; + + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + + + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; + + const scope = this; + + this.stats = { + + 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; + + } + } + + }; + + } + + // Memory management for AnimationAction objects + + _isActiveAction( action ) { + + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + + } + + _addInactiveAction( action, clipUuid, rootUuid ) { + + const actions = this._actions, + actionsByClip = this._actionsByClip; + + let actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip === undefined ) { + + actionsForClip = { + + knownActions: [ action ], + actionByRoot: {} + + }; + + action._byClipCacheIndex = 0; + + actionsByClip[ clipUuid ] = actionsForClip; + + } else { + + const knownActions = actionsForClip.knownActions; + + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); + + } + + action._cacheIndex = actions.length; + actions.push( action ); + + actionsForClip.actionByRoot[ rootUuid ] = action; + + } + + _removeInactiveAction( action ) { + + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + action._cacheIndex = null; + + + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, + + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], + + byClipCacheIndex = action._byClipCacheIndex; + + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); + + action._byClipCacheIndex = null; + + + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; + + delete actionByRoot[ rootUuid ]; + + if ( knownActionsForClip.length === 0 ) { + + delete actionsByClip[ clipUuid ]; + + } + + this._removeInactiveBindingsForAction( action ); + + } + + _removeInactiveBindingsForAction( action ) { + + const bindings = action._propertyBindings; + + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.referenceCount === 0 ) { + + this._removeInactiveBinding( binding ); + + } + + } + + } + + _lendAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s + + const actions = this._actions, + prevIndex = action._cacheIndex, + + lastActiveIndex = this._nActiveActions ++, + + firstInactiveAction = actions[ lastActiveIndex ]; + + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; + + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; + + } + + _takeBackAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a + + const actions = this._actions, + prevIndex = action._cacheIndex, + + firstInactiveIndex = -- this._nActiveActions, + + lastActiveAction = actions[ firstInactiveIndex ]; + + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; + + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; + + } + + // Memory management for PropertyMixer objects + + _addInactiveBinding( binding, rootUuid, trackName ) { + + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; + + let bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName === undefined ) { + + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; + + } + + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); + + } + + _removeInactiveBinding( binding ) { + + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], + + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; + + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); + + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { + + delete bindingsByRoot[ rootUuid ]; + + } + + } + + _lendBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + lastActiveIndex = this._nActiveBindings ++, + + firstInactiveBinding = bindings[ lastActiveIndex ]; + + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; + + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; + + } + + _takeBackBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + firstInactiveIndex = -- this._nActiveBindings, + + lastActiveBinding = bindings[ firstInactiveIndex ]; + + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; + + } + + + // Memory management of Interpolants for weight and time scale + + _lendControlInterpolant() { + + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; + + let interpolant = interpolants[ lastActiveIndex ]; + + if ( interpolant === undefined ) { + + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); + + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; + + } + + return interpolant; + + } + + _takeBackControlInterpolant( interpolant ) { + + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, + + firstInactiveIndex = -- this._nActiveControlInterpolants, + + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; + + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; + + } + + // 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( clip, optionalRoot, blendMode ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid; + + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; + + if ( blendMode === undefined ) { + + if ( clipObject !== null ) { + + blendMode = clipObject.blendMode; + + } else { + + blendMode = NormalAnimationBlendMode; + + } + + } + + if ( actionsForClip !== undefined ) { + + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + + return existingAction; + + } + + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; + + // 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 + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); + + this._bindAction( newAction, prototypeAction ); + + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); + + return newAction; + + } + + // get an existing action + existingAction( clip, optionalRoot ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid, + + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, + + clipUuid = clipObject ? clipObject.uuid : clip, + + actionsForClip = this._actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + return actionsForClip.actionByRoot[ rootUuid ] || null; + + } + + return null; + + } + + // deactivates all previously scheduled actions + stopAllAction() { + + const actions = this._actions, + nActions = this._nActiveActions; + + for ( let i = nActions - 1; i >= 0; -- i ) { + + actions[ i ].stop(); + + } + + return this; + + } + + // advance the time and update apply the animation + update( deltaTime ) { + + deltaTime *= this.timeScale; + + const actions = this._actions, + nActions = this._nActiveActions, + + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), + + accuIndex = this._accuIndex ^= 1; + + // run active actions + + for ( let i = 0; i !== nActions; ++ i ) { + + const action = actions[ i ]; + + action._update( time, deltaTime, timeDirection, accuIndex ); + + } + + // update scene graph + + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { + + bindings[ i ].apply( accuIndex ); + + } + + return this; + + } + + // Allows you to seek to a specific time in an animation. + setTime( timeInSeconds ) { + + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { + + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. + + } + + // return this mixer's root target object + getRoot() { + + return this._root; + + } + + // free all resources specific to a particular clip + uncacheClip( clip ) { + + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away + + const actionsToRemove = actionsForClip.knownActions; + + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + + const action = actionsToRemove[ i ]; + + this._deactivateAction( action ); + + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; + + action._cacheIndex = null; + action._byClipCacheIndex = null; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + this._removeInactiveBindingsForAction( action ); + + } + + delete actionsByClip[ clipUuid ]; + + } + + } + + // free all resources specific to a particular root target object + uncacheRoot( root ) { + + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; + + for ( const clipUuid in actionsByClip ) { + + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; + + if ( action !== undefined ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName !== undefined ) { + + for ( const trackName in bindingByName ) { + + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); + + } + + } + + } + + // remove a targeted clip from the cache + uncacheAction( clip, optionalRoot ) { + + const action = this.existingAction( clip, optionalRoot ); + + if ( action !== null ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + + } + + class Uniform { + + constructor( value ) { + + this.value = value; + + } + + clone() { + + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + + } + + } + + let id = 0; + + class UniformsGroup extends EventDispatcher { + + constructor() { + + super(); + + this.isUniformsGroup = true; + + Object.defineProperty( this, 'id', { value: id ++ } ); + + this.name = ''; + + this.usage = StaticDrawUsage; + this.uniforms = []; + + } + + add( uniform ) { + + this.uniforms.push( uniform ); + + return this; + + } + + remove( uniform ) { + + const index = this.uniforms.indexOf( uniform ); + + if ( index !== - 1 ) this.uniforms.splice( index, 1 ); + + return this; + + } + + setName( name ) { + + this.name = name; + + return this; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.usage = source.usage; + + const uniformsSource = source.uniforms; + + this.uniforms.length = 0; + + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { + + this.uniforms.push( uniformsSource[ i ].clone() ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + class InstancedInterleavedBuffer extends InterleavedBuffer { + + constructor( array, stride, meshPerAttribute = 1 ) { + + super( array, stride ); + + this.isInstancedInterleavedBuffer = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + clone( data ) { + + const ib = super.clone( data ); + + ib.meshPerAttribute = this.meshPerAttribute; + + return ib; + + } + + toJSON( data ) { + + const json = super.toJSON( data ); + + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + + return json; + + } + + } + + class GLBufferAttribute { + + constructor( buffer, type, itemSize, elementSize, count ) { + + this.isGLBufferAttribute = true; + + this.name = ''; + + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setBuffer( buffer ) { + + this.buffer = buffer; + + return this; + + } + + setType( type, elementSize ) { + + this.type = type; + this.elementSize = elementSize; + + return this; + + } + + setItemSize( itemSize ) { + + this.itemSize = itemSize; + + return this; + + } + + setCount( count ) { + + this.count = count; + + return this; + + } + + } + + class Raycaster { + + constructor( origin, direction, near = 0, far = Infinity ) { + + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) + + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } + + set( origin, direction ) { + + // direction is assumed to be normalized (for accurate distance calculations) + + this.ray.set( origin, direction ); + + } + + setFromCamera( coords, camera ) { + + if ( camera.isPerspectiveCamera ) { + + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; + + } else if ( camera.isOrthographicCamera ) { + + 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 ); + this.camera = camera; + + } else { + + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + + } + + } + + intersectObject( object, recursive = true, intersects = [] ) { + + intersectObject( object, this, intersects, recursive ); + + intersects.sort( ascSort ); + + return intersects; + + } + + intersectObjects( objects, recursive = true, intersects = [] ) { + + for ( let i = 0, l = objects.length; i < l; i ++ ) { + + intersectObject( objects[ i ], this, intersects, recursive ); + + } + + intersects.sort( ascSort ); + + return intersects; + + } + + } + + function ascSort( a, b ) { + + return a.distance - b.distance; + + } + + function intersectObject( object, raycaster, intersects, recursive ) { + + if ( object.layers.test( raycaster.layers ) ) { + + object.raycast( raycaster, intersects ); + + } + + if ( recursive === true ) { + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + intersectObject( children[ i ], raycaster, intersects, true ); + + } + + } + + } + + /** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ + + class Spherical { + + constructor( radius = 1, phi = 0, theta = 0 ) { + + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle + + return this; + + } + + set( radius, phi, theta ) { + + this.radius = radius; + this.phi = phi; + this.theta = theta; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + + return this; + + } + + // restrict phi to be between EPS and PI-EPS + makeSafe() { + + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + y * y + z * z ); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + /** + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + */ + + class Cylindrical { + + constructor( radius = 1, theta = 0, y = 0 ) { + + this.radius = radius; // distance from the origin to a point in the x-z plane + this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = y; // height above the x-z plane + + return this; + + } + + set( radius, theta, y ) { + + this.radius = radius; + this.theta = theta; + this.y = y; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + const _vector$4 = /*@__PURE__*/ new Vector2(); + + class Box2 { + + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + + this.isBox2 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + containsPoint( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; + + } + + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + + } + + intersectsBox( box ) { + + // using 4 splitting planes to rule out intersections + + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); + + } + + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + + } + + const _startP = /*@__PURE__*/ new Vector3(); + const _startEnd = /*@__PURE__*/ new Vector3(); + + class Line3 { + + constructor( start = new Vector3(), end = new Vector3() ) { + + this.start = start; + this.end = end; + + } + + set( start, end ) { + + this.start.copy( start ); + this.end.copy( end ); + + return this; + + } + + copy( line ) { + + this.start.copy( line.start ); + this.end.copy( line.end ); + + return this; + + } + + getCenter( target ) { + + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + + } + + delta( target ) { + + return target.subVectors( this.end, this.start ); + + } + + distanceSq() { + + return this.start.distanceToSquared( this.end ); + + } + + distance() { + + return this.start.distanceTo( this.end ); + + } + + at( t, target ) { + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + closestPointToPointParameter( point, clampToLine ) { + + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); + + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); + + let t = startEnd_startP / startEnd2; + + if ( clampToLine ) { + + t = clamp( t, 0, 1 ); + + } + + return t; + + } + + closestPointToPoint( point, clampToLine, target ) { + + const t = this.closestPointToPointParameter( point, clampToLine ); + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + applyMatrix4( matrix ) { + + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); + + return this; + + } + + equals( line ) { + + return line.start.equals( this.start ) && line.end.equals( this.end ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + } + + const _vector$3 = /*@__PURE__*/ new Vector3(); + + class SpotLightHelper extends Object3D { + + constructor( light, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'SpotLightHelper'; + + const geometry = new BufferGeometry(); + + const 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 ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; + + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); + + this.update(); + + } + + dispose() { + + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); + + this.cone.scale.set( coneWidth, coneWidth, coneLength ); + + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); + + this.cone.lookAt( _vector$3 ); + + if ( this.color !== undefined ) { + + this.cone.material.color.set( this.color ); + + } else { + + this.cone.material.color.copy( this.light.color ); + + } + + } + + } + + const _vector$2 = /*@__PURE__*/ new Vector3(); + const _boneMatrix = /*@__PURE__*/ new Matrix4(); + const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + + + class SkeletonHelper extends LineSegments { + + constructor( object ) { + + const bones = getBoneList( object ); + + const geometry = new BufferGeometry(); + + const vertices = []; + const colors = []; + + const color1 = new Color( 0, 0, 1 ); + const color2 = new Color( 0, 1, 0 ); + + for ( let i = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); + + } + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + + super( geometry, material ); + + this.isSkeletonHelper = true; + + this.type = 'SkeletonHelper'; + + this.root = object; + this.bones = bones; + + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + + } + + updateMatrixWorld( force ) { + + const bones = this.bones; + + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); + + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + + for ( let i = 0, j = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); + + j += 2; + + } + + } + + geometry.getAttribute( 'position' ).needsUpdate = true; + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + + function getBoneList( object ) { + + const boneList = []; + + if ( object.isBone === true ) { + + boneList.push( object ); + + } + + for ( let i = 0; i < object.children.length; i ++ ) { + + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + + } + + return boneList; + + } + + class PointLightHelper extends Mesh { + + constructor( light, sphereSize, color ) { + + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + + super( geometry, material ); + + this.light = light; + + this.color = color; + + this.type = 'PointLightHelper'; + + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + + this.update(); + + + /* + // TODO: delete this comment? + const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + + const d = light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.scale.set( d, d, d ); + + } + + this.add( this.lightDistance ); + */ + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ); + + } + + /* + const d = this.light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); + + } + */ + + } + + } + + const _vector$1 = /*@__PURE__*/ new Vector3(); + const _color1 = /*@__PURE__*/ new Color(); + const _color2 = /*@__PURE__*/ new Color(); + + class HemisphereLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'HemisphereLightHelper'; + + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); + + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; + + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); + + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + + this.add( new Mesh( geometry, this.material ) ); + + this.update(); + + } + + dispose() { + + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + + update() { + + const mesh = this.children[ 0 ]; + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + const colors = mesh.geometry.getAttribute( 'color' ); + + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); + + for ( let i = 0, l = colors.count; i < l; i ++ ) { + + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + + colors.setXYZ( i, color.r, color.g, color.b ); + + } + + colors.needsUpdate = true; + + } + + this.light.updateWorldMatrix( true, false ); + + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + + } + + } + + class GridHelper extends LineSegments { + + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + + const vertices = [], colors = []; + + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); + + const color = i === center ? color1 : color2; + + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'GridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + class PolarGridHelper extends LineSegments { + + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const vertices = []; + const colors = []; + + // create the sectors + + if ( sectors > 1 ) { + + for ( let i = 0; i < sectors; i ++ ) { + + const v = ( i / sectors ) * ( Math.PI * 2 ); + + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; + + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); + + const color = ( i & 1 ) ? color1 : color2; + + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); + + } + + } + + // create the rings + + for ( let i = 0; i < rings; i ++ ) { + + const color = ( i & 1 ) ? color1 : color2; + + const r = radius - ( radius / rings * i ); + + for ( let j = 0; j < divisions; j ++ ) { + + // first vertex + + let v = ( j / divisions ) * ( Math.PI * 2 ); + + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + // second vertex + + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + } + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'PolarGridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + const _v1 = /*@__PURE__*/ new Vector3(); + const _v2 = /*@__PURE__*/ new Vector3(); + const _v3 = /*@__PURE__*/ new Vector3(); + + class DirectionalLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'DirectionalLightHelper'; + + if ( size === undefined ) size = 1; + + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); + + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); + + this.update(); + + } + + dispose() { + + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); + + this.lightPlane.lookAt( _v2 ); + + if ( this.color !== undefined ) { + + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); + + } else { + + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); + + } + + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); + + } + + } + + const _vector = /*@__PURE__*/ new Vector3(); + const _camera = /*@__PURE__*/ new Camera(); + + /** + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html + */ + + class CameraHelper extends LineSegments { + + constructor( camera ) { + + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + + const vertices = []; + const colors = []; + + const pointMap = {}; + + // near + + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); + + // far + + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); + + // sides + + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); + + // cone + + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); + + // up + + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); + + // target + + addLine( 'c', 't' ); + addLine( 'p', 'c' ); + + // cross + + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); + + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); + + function addLine( a, b ) { + + addPoint( a ); + addPoint( b ); + + } + + function addPoint( id ) { + + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + + if ( pointMap[ id ] === undefined ) { + + pointMap[ id ] = []; + + } + + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + super( geometry, material ); + + this.type = 'CameraHelper'; + + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + + this.pointMap = pointMap; + + this.update(); + + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + + } + + update() { + + const geometry = this.geometry; + const pointMap = this.pointMap; + + const w = 1, h = 1; + + // we need just camera projection matrix inverse + // world matrix must be identity + + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + + // center / target + + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + + // near + + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); + + // far + + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + + // up + + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + + // cross + + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + + geometry.getAttribute( 'position' ).needsUpdate = true; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + + function setPoint( point, pointMap, geometry, camera, x, y, z ) { + + _vector.set( x, y, z ).unproject( camera ); + + const points = pointMap[ point ]; + + if ( points !== undefined ) { + + const position = geometry.getAttribute( 'position' ); + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); + + } + + } + + } + + const _box = /*@__PURE__*/ new Box3(); + + class BoxHelper extends LineSegments { + + constructor( object, color = 0xffff00 ) { + + const 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 ] ); + const positions = new Float32Array( 8 * 3 ); + + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.object = object; + this.type = 'BoxHelper'; + + this.matrixAutoUpdate = false; + + this.update(); + + } + + update( object ) { + + if ( object !== undefined ) { + + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + + } + + if ( this.object !== undefined ) { + + _box.setFromObject( this.object ); + + } + + if ( _box.isEmpty() ) return; + + const min = _box.min; + const max = _box.max; + + /* + 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 + */ + + const position = this.geometry.attributes.position; + const 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; + + position.needsUpdate = true; + + this.geometry.computeBoundingSphere(); + + } + + setFromObject( object ) { + + this.object = object; + this.update(); + + return this; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.object = source.object; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + class Box3Helper extends LineSegments { + + constructor( box, color = 0xffff00 ) { + + const 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 ] ); + + const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + + const geometry = new BufferGeometry(); + + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.box = box; + + this.type = 'Box3Helper'; + + this.geometry.computeBoundingSphere(); + + } + + updateMatrixWorld( force ) { + + const box = this.box; + + if ( box.isEmpty() ) return; + + box.getCenter( this.position ); + + box.getSize( this.scale ); + + this.scale.multiplyScalar( 0.5 ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + class PlaneHelper extends Line { + + constructor( plane, size = 1, hex = 0xffff00 ) { + + const color = hex; + + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.type = 'PlaneHelper'; + + this.plane = plane; + + this.size = size; + + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; + + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + + } + + updateMatrixWorld( force ) { + + this.position.set( 0, 0, 0 ); + + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); + + this.lookAt( this.plane.normal ); + + this.translateZ( - this.plane.constant ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + + } + + const _axis = /*@__PURE__*/ new Vector3(); + let _lineGeometry, _coneGeometry; + + class ArrowHelper extends Object3D { + + // dir is assumed to be normalized + + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + super(); + + this.type = 'ArrowHelper'; + + if ( _lineGeometry === undefined ) { + + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + + _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); + + } + + this.position.copy( origin ); + + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); + + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); + + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); + + } + + setDirection( dir ) { + + // dir is assumed to be normalized + + if ( dir.y > 0.99999 ) { + + this.quaternion.set( 0, 0, 0, 1 ); + + } else if ( dir.y < - 0.99999 ) { + + this.quaternion.set( 1, 0, 0, 0 ); + + } else { + + _axis.set( dir.z, 0, - dir.x ).normalize(); + + const radians = Math.acos( dir.y ); + + this.quaternion.setFromAxisAngle( _axis, radians ); + + } + + } + + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); + + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); + + } + + setColor( color ) { + + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } + + copy( source ) { + + super.copy( source, false ); + + this.line.copy( source.line ); + this.cone.copy( source.cone ); + + return this; + + } + + dispose() { + + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + + } + + class AxesHelper extends LineSegments { + + constructor( size = 1 ) { + + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; + + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'AxesHelper'; + + } + + setColors( xAxisColor, yAxisColor, zAxisColor ) { + + const color = new Color(); + const array = this.geometry.attributes.color.array; + + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); + + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); + + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); + + this.geometry.attributes.color.needsUpdate = true; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + } + + class ShapePath { + + constructor() { + + this.type = 'ShapePath'; + + this.color = new Color(); + + this.subPaths = []; + this.currentPath = null; + + } + + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); + + return this; + + } + + lineTo( x, y ) { + + this.currentPath.lineTo( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + + return this; + + } + + splineThru( pts ) { + + this.currentPath.splineThru( pts ); + + return this; + + } + + toShapes( isCCW ) { + + function toShapesNoHoles( inSubpaths ) { + + const shapes = []; + + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + + const tmpPath = inSubpaths[ i ]; + + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + + shapes.push( tmpShape ); + + } + + return shapes; + + } + + function isPointInsidePolygon( inPt, inPolygon ) { + + const polyLen = inPolygon.length; + + // 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 + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; + + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + + if ( Math.abs( edgeDy ) > Number.EPSILON ) { + + // not parallel + if ( edgeDy < 0 ) { + + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + + } + + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + + 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 { + + const 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 + + } + + } 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; + + } + + } + + return inside; + + } + + const isClockWise = ShapeUtils.isClockWise; + + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; + + let solid, tmpPath, tmpShape; + const shapes = []; + + if ( subPaths.length === 1 ) { + + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; + + } + + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; + + // console.log("Holes first", holesFirst); + + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; + + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { + + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; + + if ( solid ) { + + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; + + //console.log('cw', i); + + } else { + + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + + //console.log('ccw', i); + + } + + } + + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + + + if ( newShapes.length > 1 ) { + + let ambiguous = false; + let toChange = 0; + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + betterShapeHoles[ sIdx ] = []; + + } + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + const sho = newShapeHoles[ sIdx ]; + + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { + + const ho = sho[ hIdx ]; + let hole_unassigned = true; + + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + + if ( sIdx !== s2Idx ) toChange ++; + + if ( hole_unassigned ) { + + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); + + } else { + + ambiguous = true; + + } + + } + + } + + if ( hole_unassigned ) { + + betterShapeHoles[ sIdx ].push( ho ); + + } + + } + + } + + if ( toChange > 0 && ambiguous === false ) { + + newShapeHoles = betterShapeHoles; + + } + + } + + let tmpHoles; + + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; + + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + + tmpShape.holes.push( tmpHoles[ j ].h ); + + } + + } + + //console.log("shape", shapes); + + return shapes; + + } + + } + + // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf + + const _tables = /*@__PURE__*/ _generateTables(); + + function _generateTables() { + + // float32 to float16 helpers + + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); + + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); + + for ( let i = 0; i < 256; ++ i ) { + + const e = i - 127; + + // very small number (0, -0) + + if ( e < - 27 ) { + + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // small number (denorm) + + } else if ( e < - 14 ) { + + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; + + // normal number + + } else if ( e <= 15 ) { + + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + // large number (Infinity, -Infinity) + + } else if ( e < 128 ) { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // stay (NaN, Infinity, -Infinity) + + } else { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + } + + } + + // float16 to float32 helpers + + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); + + for ( let i = 1; i < 1024; ++ i ) { + + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent + + // normalized + while ( ( m & 0x00800000 ) === 0 ) { + + m <<= 1; + e -= 0x00800000; // decrement exponent + + } + + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias + + mantissaTable[ i ] = m | e; + + } + + for ( let i = 1024; i < 2048; ++ i ) { + + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + + } + + for ( let i = 1; i < 31; ++ i ) { + + exponentTable[ i ] = i << 23; + + } + + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; + + for ( let i = 33; i < 63; ++ i ) { + + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + + } + + exponentTable[ 63 ] = 0xc7800000; + + for ( let i = 1; i < 64; ++ i ) { + + if ( i !== 32 ) { + + offsetTable[ i ] = 1024; + + } + + } + + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; + + } + + // float32 to float16 + + function toHalfFloat( val ) { + + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); + + val = clamp( val, - 65504, 65504 ); + + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); + + } + + // float16 to float32 + + function fromHalfFloat( val ) { + + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; + + } + + var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + fromHalfFloat: fromHalfFloat, + toHalfFloat: toHalfFloat + }); + + // r144 + + class BoxBufferGeometry extends BoxGeometry { + + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { + + console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' ); + super( width, height, depth, widthSegments, heightSegments, depthSegments ); + + + } + + } + + // r144 + + class CapsuleBufferGeometry extends CapsuleGeometry { + + constructor( radius, length, capSegments, radialSegments ) { + + console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' ); + super( radius, length, capSegments, radialSegments ); + + } + + } + + // r144 + + class CircleBufferGeometry extends CircleGeometry { + + constructor( radius, segments, thetaStart, thetaLength ) { + + console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' ); + super( radius, segments, thetaStart, thetaLength ); + + } + + } + + // r144 + + class ConeBufferGeometry extends ConeGeometry { + + constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' ); + super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + + } + + // r144 + + class CylinderBufferGeometry extends CylinderGeometry { + + constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' ); + super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + + } + + // r144 + + class DodecahedronBufferGeometry extends DodecahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' ); + super( radius, detail ); + + } + + } + + // r144 + + class ExtrudeBufferGeometry extends ExtrudeGeometry { + + constructor( shapes, options ) { + + console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' ); + super( shapes, options ); + + } + + } + + // r144 + + class IcosahedronBufferGeometry extends IcosahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' ); + super( radius, detail ); + + } + + } + + // r144 + + class LatheBufferGeometry extends LatheGeometry { + + constructor( points, segments, phiStart, phiLength ) { + + console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' ); + super( points, segments, phiStart, phiLength ); + + } + + } + + // r144 + + class OctahedronBufferGeometry extends OctahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' ); + super( radius, detail ); + + } + + } + + // r144 + + class PlaneBufferGeometry extends PlaneGeometry { + + constructor( width, height, widthSegments, heightSegments ) { + + console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' ); + super( width, height, widthSegments, heightSegments ); + + } + + } + + // r144 + + class PolyhedronBufferGeometry extends PolyhedronGeometry { + + constructor( vertices, indices, radius, detail ) { + + console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' ); + super( vertices, indices, radius, detail ); + + } + + } + + // r144 + + class RingBufferGeometry extends RingGeometry { + + constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + + console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' ); + super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ); + + } + + } + + // r144 + + class ShapeBufferGeometry extends ShapeGeometry { + + constructor( shapes, curveSegments ) { + + console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' ); + super( shapes, curveSegments ); + + } + + } + + // r144 + + class SphereBufferGeometry extends SphereGeometry { + + constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + + console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' ); + super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ); + + } + + } + + // r144 + + class TetrahedronBufferGeometry extends TetrahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' ); + super( radius, detail ); + + } + + } + + // r144 + + class TorusBufferGeometry extends TorusGeometry { + + constructor( radius, tube, radialSegments, tubularSegments, arc ) { + + console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' ); + super( radius, tube, radialSegments, tubularSegments, arc ); + + } + + } + + // r144 + + class TorusKnotBufferGeometry extends TorusKnotGeometry { + + constructor( radius, tube, tubularSegments, radialSegments, p, q ) { + + console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' ); + super( radius, tube, tubularSegments, radialSegments, p, q ); + + } + + } + + // r144 + + class TubeBufferGeometry extends TubeGeometry { + + constructor( path, tubularSegments, radius, radialSegments, closed ) { + + console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' ); + super( path, tubularSegments, radius, radialSegments, closed ); + + } + + } + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + + } + + if ( typeof window !== 'undefined' ) { + + if ( window.__THREE__ ) { + + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); + + } else { + + window.__THREE__ = REVISION; + + } + + } + + exports.ACESFilmicToneMapping = ACESFilmicToneMapping; + exports.AddEquation = AddEquation; + exports.AddOperation = AddOperation; + exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode; + exports.AdditiveBlending = AdditiveBlending; + exports.AlphaFormat = AlphaFormat; + exports.AlwaysDepth = AlwaysDepth; + exports.AlwaysStencilFunc = AlwaysStencilFunc; + exports.AmbientLight = AmbientLight; + exports.AmbientLightProbe = AmbientLightProbe; + exports.AnimationClip = AnimationClip; + exports.AnimationLoader = AnimationLoader; + exports.AnimationMixer = AnimationMixer; + exports.AnimationObjectGroup = AnimationObjectGroup; + exports.AnimationUtils = AnimationUtils; + exports.ArcCurve = ArcCurve; + exports.ArrayCamera = ArrayCamera; + exports.ArrowHelper = ArrowHelper; + exports.Audio = Audio; + exports.AudioAnalyser = AudioAnalyser; + exports.AudioContext = AudioContext; + exports.AudioListener = AudioListener; + exports.AudioLoader = AudioLoader; + exports.AxesHelper = AxesHelper; + exports.BackSide = BackSide; + exports.BasicDepthPacking = BasicDepthPacking; + exports.BasicShadowMap = BasicShadowMap; + exports.Bone = Bone; + exports.BooleanKeyframeTrack = BooleanKeyframeTrack; + exports.Box2 = Box2; + exports.Box3 = Box3; + exports.Box3Helper = Box3Helper; + exports.BoxBufferGeometry = BoxBufferGeometry; + exports.BoxGeometry = BoxGeometry; + exports.BoxHelper = BoxHelper; + exports.BufferAttribute = BufferAttribute; + exports.BufferGeometry = BufferGeometry; + exports.BufferGeometryLoader = BufferGeometryLoader; + exports.ByteType = ByteType; + exports.Cache = Cache; + exports.Camera = Camera; + exports.CameraHelper = CameraHelper; + exports.CanvasTexture = CanvasTexture; + exports.CapsuleBufferGeometry = CapsuleBufferGeometry; + exports.CapsuleGeometry = CapsuleGeometry; + exports.CatmullRomCurve3 = CatmullRomCurve3; + exports.CineonToneMapping = CineonToneMapping; + exports.CircleBufferGeometry = CircleBufferGeometry; + exports.CircleGeometry = CircleGeometry; + exports.ClampToEdgeWrapping = ClampToEdgeWrapping; + exports.Clock = Clock; + exports.Color = Color; + exports.ColorKeyframeTrack = ColorKeyframeTrack; + exports.ColorManagement = ColorManagement; + exports.CompressedArrayTexture = CompressedArrayTexture; + exports.CompressedTexture = CompressedTexture; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.ConeBufferGeometry = ConeBufferGeometry; + exports.ConeGeometry = ConeGeometry; + exports.CubeCamera = CubeCamera; + exports.CubeReflectionMapping = CubeReflectionMapping; + exports.CubeRefractionMapping = CubeRefractionMapping; + exports.CubeTexture = CubeTexture; + exports.CubeTextureLoader = CubeTextureLoader; + exports.CubeUVReflectionMapping = CubeUVReflectionMapping; + exports.CubicBezierCurve = CubicBezierCurve; + exports.CubicBezierCurve3 = CubicBezierCurve3; + exports.CubicInterpolant = CubicInterpolant; + exports.CullFaceBack = CullFaceBack; + exports.CullFaceFront = CullFaceFront; + exports.CullFaceFrontBack = CullFaceFrontBack; + exports.CullFaceNone = CullFaceNone; + exports.Curve = Curve; + exports.CurvePath = CurvePath; + exports.CustomBlending = CustomBlending; + exports.CustomToneMapping = CustomToneMapping; + exports.CylinderBufferGeometry = CylinderBufferGeometry; + exports.CylinderGeometry = CylinderGeometry; + exports.Cylindrical = Cylindrical; + exports.Data3DTexture = Data3DTexture; + exports.DataArrayTexture = DataArrayTexture; + exports.DataTexture = DataTexture; + exports.DataTextureLoader = DataTextureLoader; + exports.DataUtils = DataUtils; + exports.DecrementStencilOp = DecrementStencilOp; + exports.DecrementWrapStencilOp = DecrementWrapStencilOp; + exports.DefaultLoadingManager = DefaultLoadingManager; + exports.DepthFormat = DepthFormat; + exports.DepthStencilFormat = DepthStencilFormat; + exports.DepthTexture = DepthTexture; + exports.DirectionalLight = DirectionalLight; + exports.DirectionalLightHelper = DirectionalLightHelper; + exports.DiscreteInterpolant = DiscreteInterpolant; + exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry; + exports.DodecahedronGeometry = DodecahedronGeometry; + exports.DoubleSide = DoubleSide; + exports.DstAlphaFactor = DstAlphaFactor; + exports.DstColorFactor = DstColorFactor; + exports.DynamicCopyUsage = DynamicCopyUsage; + exports.DynamicDrawUsage = DynamicDrawUsage; + exports.DynamicReadUsage = DynamicReadUsage; + exports.EdgesGeometry = EdgesGeometry; + exports.EllipseCurve = EllipseCurve; + exports.EqualDepth = EqualDepth; + exports.EqualStencilFunc = EqualStencilFunc; + exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; + exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; + exports.Euler = Euler; + exports.EventDispatcher = EventDispatcher; + exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry; + exports.ExtrudeGeometry = ExtrudeGeometry; + exports.FileLoader = FileLoader; + exports.Float16BufferAttribute = Float16BufferAttribute; + exports.Float32BufferAttribute = Float32BufferAttribute; + exports.Float64BufferAttribute = Float64BufferAttribute; + exports.FloatType = FloatType; + exports.Fog = Fog; + exports.FogExp2 = FogExp2; + exports.FramebufferTexture = FramebufferTexture; + exports.FrontSide = FrontSide; + exports.Frustum = Frustum; + exports.GLBufferAttribute = GLBufferAttribute; + exports.GLSL1 = GLSL1; + exports.GLSL3 = GLSL3; + exports.GreaterDepth = GreaterDepth; + exports.GreaterEqualDepth = GreaterEqualDepth; + exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc; + exports.GreaterStencilFunc = GreaterStencilFunc; + exports.GridHelper = GridHelper; + exports.Group = Group; + exports.HalfFloatType = HalfFloatType; + exports.HemisphereLight = HemisphereLight; + exports.HemisphereLightHelper = HemisphereLightHelper; + exports.HemisphereLightProbe = HemisphereLightProbe; + exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry; + exports.IcosahedronGeometry = IcosahedronGeometry; + exports.ImageBitmapLoader = ImageBitmapLoader; + exports.ImageLoader = ImageLoader; + exports.ImageUtils = ImageUtils; + exports.IncrementStencilOp = IncrementStencilOp; + exports.IncrementWrapStencilOp = IncrementWrapStencilOp; + exports.InstancedBufferAttribute = InstancedBufferAttribute; + exports.InstancedBufferGeometry = InstancedBufferGeometry; + exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; + exports.InstancedMesh = InstancedMesh; + exports.Int16BufferAttribute = Int16BufferAttribute; + exports.Int32BufferAttribute = Int32BufferAttribute; + exports.Int8BufferAttribute = Int8BufferAttribute; + exports.IntType = IntType; + exports.InterleavedBuffer = InterleavedBuffer; + exports.InterleavedBufferAttribute = InterleavedBufferAttribute; + exports.Interpolant = Interpolant; + exports.InterpolateDiscrete = InterpolateDiscrete; + exports.InterpolateLinear = InterpolateLinear; + exports.InterpolateSmooth = InterpolateSmooth; + exports.InvertStencilOp = InvertStencilOp; + exports.KeepStencilOp = KeepStencilOp; + exports.KeyframeTrack = KeyframeTrack; + exports.LOD = LOD; + exports.LatheBufferGeometry = LatheBufferGeometry; + exports.LatheGeometry = LatheGeometry; + exports.Layers = Layers; + exports.LessDepth = LessDepth; + exports.LessEqualDepth = LessEqualDepth; + exports.LessEqualStencilFunc = LessEqualStencilFunc; + exports.LessStencilFunc = LessStencilFunc; + exports.Light = Light; + exports.LightProbe = LightProbe; + exports.Line = Line; + exports.Line3 = Line3; + exports.LineBasicMaterial = LineBasicMaterial; + exports.LineCurve = LineCurve; + exports.LineCurve3 = LineCurve3; + exports.LineDashedMaterial = LineDashedMaterial; + exports.LineLoop = LineLoop; + exports.LineSegments = LineSegments; + exports.LinearEncoding = LinearEncoding; + exports.LinearFilter = LinearFilter; + exports.LinearInterpolant = LinearInterpolant; + exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; + exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; + exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter; + exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter; + exports.LinearSRGBColorSpace = LinearSRGBColorSpace; + exports.LinearToneMapping = LinearToneMapping; + exports.Loader = Loader; + exports.LoaderUtils = LoaderUtils; + exports.LoadingManager = LoadingManager; + exports.LoopOnce = LoopOnce; + exports.LoopPingPong = LoopPingPong; + exports.LoopRepeat = LoopRepeat; + exports.LuminanceAlphaFormat = LuminanceAlphaFormat; + exports.LuminanceFormat = LuminanceFormat; + exports.MOUSE = MOUSE; + exports.Material = Material; + exports.MaterialLoader = MaterialLoader; + exports.MathUtils = MathUtils; + exports.Matrix3 = Matrix3; + exports.Matrix4 = Matrix4; + exports.MaxEquation = MaxEquation; + exports.Mesh = Mesh; + exports.MeshBasicMaterial = MeshBasicMaterial; + exports.MeshDepthMaterial = MeshDepthMaterial; + exports.MeshDistanceMaterial = MeshDistanceMaterial; + exports.MeshLambertMaterial = MeshLambertMaterial; + exports.MeshMatcapMaterial = MeshMatcapMaterial; + exports.MeshNormalMaterial = MeshNormalMaterial; + exports.MeshPhongMaterial = MeshPhongMaterial; + exports.MeshPhysicalMaterial = MeshPhysicalMaterial; + exports.MeshStandardMaterial = MeshStandardMaterial; + exports.MeshToonMaterial = MeshToonMaterial; + exports.MinEquation = MinEquation; + exports.MirroredRepeatWrapping = MirroredRepeatWrapping; + exports.MixOperation = MixOperation; + exports.MultiplyBlending = MultiplyBlending; + exports.MultiplyOperation = MultiplyOperation; + exports.NearestFilter = NearestFilter; + exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; + exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; + exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; + exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; + exports.NeverDepth = NeverDepth; + exports.NeverStencilFunc = NeverStencilFunc; + exports.NoBlending = NoBlending; + exports.NoColorSpace = NoColorSpace; + exports.NoToneMapping = NoToneMapping; + exports.NormalAnimationBlendMode = NormalAnimationBlendMode; + exports.NormalBlending = NormalBlending; + exports.NotEqualDepth = NotEqualDepth; + exports.NotEqualStencilFunc = NotEqualStencilFunc; + exports.NumberKeyframeTrack = NumberKeyframeTrack; + exports.Object3D = Object3D; + exports.ObjectLoader = ObjectLoader; + exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap; + exports.OctahedronBufferGeometry = OctahedronBufferGeometry; + exports.OctahedronGeometry = OctahedronGeometry; + exports.OneFactor = OneFactor; + exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; + exports.OneMinusDstColorFactor = OneMinusDstColorFactor; + exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; + exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; + exports.OrthographicCamera = OrthographicCamera; + exports.PCFShadowMap = PCFShadowMap; + exports.PCFSoftShadowMap = PCFSoftShadowMap; + exports.PMREMGenerator = PMREMGenerator; + exports.Path = Path; + exports.PerspectiveCamera = PerspectiveCamera; + exports.Plane = Plane; + exports.PlaneBufferGeometry = PlaneBufferGeometry; + exports.PlaneGeometry = PlaneGeometry; + exports.PlaneHelper = PlaneHelper; + exports.PointLight = PointLight; + exports.PointLightHelper = PointLightHelper; + exports.Points = Points; + exports.PointsMaterial = PointsMaterial; + exports.PolarGridHelper = PolarGridHelper; + exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry; + exports.PolyhedronGeometry = PolyhedronGeometry; + exports.PositionalAudio = PositionalAudio; + exports.PropertyBinding = PropertyBinding; + exports.PropertyMixer = PropertyMixer; + exports.QuadraticBezierCurve = QuadraticBezierCurve; + exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; + exports.Quaternion = Quaternion; + exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; + exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; + exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format; + exports.RED_RGTC1_Format = RED_RGTC1_Format; + exports.REVISION = REVISION; + exports.RGBADepthPacking = RGBADepthPacking; + exports.RGBAFormat = RGBAFormat; + exports.RGBAIntegerFormat = RGBAIntegerFormat; + exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; + exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; + exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; + exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; + exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; + exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; + exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; + exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; + exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; + exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; + exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; + exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; + exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; + exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; + exports.RGBA_BPTC_Format = RGBA_BPTC_Format; + exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format; + exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; + exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_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_ETC1_Format = RGB_ETC1_Format; + exports.RGB_ETC2_Format = RGB_ETC2_Format; + exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; + exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; + exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; + exports.RGFormat = RGFormat; + exports.RGIntegerFormat = RGIntegerFormat; + exports.RawShaderMaterial = RawShaderMaterial; + exports.Ray = Ray; + exports.Raycaster = Raycaster; + exports.RectAreaLight = RectAreaLight; + exports.RedFormat = RedFormat; + exports.RedIntegerFormat = RedIntegerFormat; + exports.ReinhardToneMapping = ReinhardToneMapping; + exports.RepeatWrapping = RepeatWrapping; + exports.ReplaceStencilOp = ReplaceStencilOp; + exports.ReverseSubtractEquation = ReverseSubtractEquation; + exports.RingBufferGeometry = RingBufferGeometry; + exports.RingGeometry = RingGeometry; + exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format; + exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format; + exports.SRGBColorSpace = SRGBColorSpace; + exports.Scene = Scene; + exports.ShaderChunk = ShaderChunk; + exports.ShaderLib = ShaderLib; + exports.ShaderMaterial = ShaderMaterial; + exports.ShadowMaterial = ShadowMaterial; + exports.Shape = Shape; + exports.ShapeBufferGeometry = ShapeBufferGeometry; + exports.ShapeGeometry = ShapeGeometry; + exports.ShapePath = ShapePath; + exports.ShapeUtils = ShapeUtils; + exports.ShortType = ShortType; + exports.Skeleton = Skeleton; + exports.SkeletonHelper = SkeletonHelper; + exports.SkinnedMesh = SkinnedMesh; + exports.Source = Source; + exports.Sphere = Sphere; + exports.SphereBufferGeometry = SphereBufferGeometry; + exports.SphereGeometry = SphereGeometry; + exports.Spherical = Spherical; + exports.SphericalHarmonics3 = SphericalHarmonics3; + exports.SplineCurve = SplineCurve; + exports.SpotLight = SpotLight; + exports.SpotLightHelper = SpotLightHelper; + exports.Sprite = Sprite; + exports.SpriteMaterial = SpriteMaterial; + exports.SrcAlphaFactor = SrcAlphaFactor; + exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; + exports.SrcColorFactor = SrcColorFactor; + exports.StaticCopyUsage = StaticCopyUsage; + exports.StaticDrawUsage = StaticDrawUsage; + exports.StaticReadUsage = StaticReadUsage; + exports.StereoCamera = StereoCamera; + exports.StreamCopyUsage = StreamCopyUsage; + exports.StreamDrawUsage = StreamDrawUsage; + exports.StreamReadUsage = StreamReadUsage; + exports.StringKeyframeTrack = StringKeyframeTrack; + exports.SubtractEquation = SubtractEquation; + exports.SubtractiveBlending = SubtractiveBlending; + exports.TOUCH = TOUCH; + exports.TangentSpaceNormalMap = TangentSpaceNormalMap; + exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry; + exports.TetrahedronGeometry = TetrahedronGeometry; + exports.Texture = Texture; + exports.TextureLoader = TextureLoader; + exports.TorusBufferGeometry = TorusBufferGeometry; + exports.TorusGeometry = TorusGeometry; + exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; + exports.TorusKnotGeometry = TorusKnotGeometry; + exports.Triangle = Triangle; + exports.TriangleFanDrawMode = TriangleFanDrawMode; + exports.TriangleStripDrawMode = TriangleStripDrawMode; + exports.TrianglesDrawMode = TrianglesDrawMode; + exports.TubeBufferGeometry = TubeBufferGeometry; + exports.TubeGeometry = TubeGeometry; + exports.TwoPassDoubleSide = TwoPassDoubleSide; + exports.UVMapping = UVMapping; + exports.Uint16BufferAttribute = Uint16BufferAttribute; + exports.Uint32BufferAttribute = Uint32BufferAttribute; + exports.Uint8BufferAttribute = Uint8BufferAttribute; + exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute; + exports.Uniform = Uniform; + exports.UniformsGroup = UniformsGroup; + exports.UniformsLib = UniformsLib; + exports.UniformsUtils = UniformsUtils; + exports.UnsignedByteType = UnsignedByteType; + exports.UnsignedInt248Type = UnsignedInt248Type; + exports.UnsignedIntType = UnsignedIntType; + exports.UnsignedShort4444Type = UnsignedShort4444Type; + exports.UnsignedShort5551Type = UnsignedShort5551Type; + exports.UnsignedShortType = UnsignedShortType; + exports.VSMShadowMap = VSMShadowMap; + exports.Vector2 = Vector2; + exports.Vector3 = Vector3; + exports.Vector4 = Vector4; + exports.VectorKeyframeTrack = VectorKeyframeTrack; + exports.VideoTexture = VideoTexture; + exports.WebGL1Renderer = WebGL1Renderer; + exports.WebGL3DRenderTarget = WebGL3DRenderTarget; + exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget; + exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget; + exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets; + exports.WebGLRenderTarget = WebGLRenderTarget; + exports.WebGLRenderer = WebGLRenderer; + exports.WebGLUtils = WebGLUtils; + exports.WireframeGeometry = WireframeGeometry; + exports.WrapAroundEnding = WrapAroundEnding; + exports.ZeroCurvatureEnding = ZeroCurvatureEnding; + exports.ZeroFactor = ZeroFactor; + exports.ZeroSlopeEnding = ZeroSlopeEnding; + exports.ZeroStencilOp = ZeroStencilOp; + exports._SRGBAFormat = _SRGBAFormat; + exports.sRGBEncoding = sRGBEncoding; + +})); diff --git a/renderer/build/three.min.js b/renderer/build/three.min.js new file mode 100644 index 0000000..ef132e9 --- /dev/null +++ b/renderer/build/three.min.js @@ -0,0 +1,6 @@ +/** + * @license + * Copyright 2010-2023 Three.js Authors + * SPDX-License-Identifier: MIT + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="149dev",i=100,n=300,r=301,s=302,a=303,o=304,l=306,c=1e3,h=1001,u=1002,d=1003,p=1004,m=1005,f=1006,g=1007,v=1008,x=1009,_=1012,y=1014,M=1015,b=1016,S=1020,w=1023,T=1026,A=1027,E=33776,C=33777,L=33778,R=33779,P=35840,I=35841,D=35842,N=35843,O=37492,z=37496,U=37808,B=37809,F=37810,k=37811,G=37812,V=37813,H=37814,W=37815,j=37816,q=37817,X=37818,Y=37819,Z=37820,J=37821,K=36492,$=36284,Q=36285,tt=36286,et=2300,it=2301,nt=2302,rt=2400,st=2401,at=2402,ot=2500,lt=2501,ct=3e3,ht=3001,ut="srgb",dt="srgb-linear",pt=7680,mt=35044,ft="300 es",gt=1035;class vt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const i=this._listeners;return void 0!==i[t]&&-1!==i[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const i=this._listeners[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const i=e.slice(0);for(let e=0,n=i.length;e>8&255]+xt[t>>16&255]+xt[t>>24&255]+"-"+xt[255&e]+xt[e>>8&255]+"-"+xt[e>>16&15|64]+xt[e>>24&255]+"-"+xt[63&i|128]+xt[i>>8&255]+"-"+xt[i>>16&255]+xt[i>>24&255]+xt[255&n]+xt[n>>8&255]+xt[n>>16&255]+xt[n>>24&255]).toLowerCase()}function St(t,e,i){return Math.max(e,Math.min(i,t))}function wt(t,e){return(t%e+e)%e}function Tt(t,e,i){return(1-i)*t+i*e}function At(t){return 0==(t&t-1)&&0!==t}function Et(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function Ct(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function Lt(t,e){switch(e.constructor){case Float32Array:return t;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Rt(t,e){switch(e.constructor){case Float32Array:return t;case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}var Pt=Object.freeze({__proto__:null,DEG2RAD:yt,RAD2DEG:Mt,ceilPowerOfTwo:Et,clamp:St,damp:function(t,e,i,n){return Tt(t,e,1-Math.exp(-i*n))},degToRad:function(t){return t*yt},denormalize:Lt,euclideanModulo:wt,floorPowerOfTwo:Ct,generateUUID:bt,inverseLerp:function(t,e,i){return t!==e?(i-t)/(e-t):0},isPowerOfTwo:At,lerp:Tt,mapLinear:function(t,e,i,n,r){return n+(t-e)*(r-n)/(i-e)},normalize:Rt,pingpong:function(t,e=1){return e-Math.abs(wt(t,2*e)-e)},radToDeg:function(t){return t*Mt},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},seededRandom:function(t){void 0!==t&&(_t=t);let e=_t+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},setQuaternionFromProperEuler:function(t,e,i,n,r){const s=Math.cos,a=Math.sin,o=s(i/2),l=a(i/2),c=s((e+n)/2),h=a((e+n)/2),u=s((e-n)/2),d=a((e-n)/2),p=s((n-e)/2),m=a((n-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},smootherstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*t*(t*(6*t-15)+10)},smoothstep:function(t,e,i){return t<=e?0:t>=i?1:(t=(t-e)/(i-e))*t*(3-2*t)}});class It{constructor(t=0,e=0){It.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(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)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(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(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),n=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*i-s*n+t.x,this.y=r*n+s*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Dt{constructor(){Dt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1]}set(t,e,i,n,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=n,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=i,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const 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}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,r=this.elements,s=i[0],a=i[3],o=i[6],l=i[1],c=i[4],h=i[7],u=i[2],d=i[5],p=i[8],m=n[0],f=n[3],g=n[6],v=n[1],x=n[4],_=n[7],y=n[2],M=n[5],b=n[8];return r[0]=s*m+a*v+o*y,r[3]=s*f+a*x+o*M,r[6]=s*g+a*_+o*b,r[1]=l*m+c*v+h*y,r[4]=l*f+c*x+h*M,r[7]=l*g+c*_+h*b,r[2]=u*m+d*v+p*y,r[5]=u*f+d*x+p*M,r[8]=u*g+d*_+p*b,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],n=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-i*r*c+i*a*o+n*r*l-n*s*o}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+i*u+n*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(n*l-c*i)*m,t[2]=(a*i-n*s)*m,t[3]=u*m,t[4]=(c*e-n*o)*m,t[5]=(n*r-a*e)*m,t[6]=d*m,t[7]=(i*o-l*e)*m,t[8]=(s*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,n,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(i*o,i*l,-i*(o*s+l*a)+s+t,-n*l,n*o,-n*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Nt.makeScale(t,e)),this}rotate(t){return this.premultiply(Nt.makeRotation(-t)),this}translate(t,e){return this.premultiply(Nt.makeTranslation(t,e)),this}makeTranslation(t,e){return this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const Nt=new Dt;function Ot(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const zt={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Ut(t,e){return new zt[t](e)}function Bt(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Ft(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function kt(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}const Gt={[ut]:{[dt]:Ft},[dt]:{[ut]:kt}},Vt={legacyMode:!0,get workingColorSpace(){return dt},set workingColorSpace(t){console.warn("THREE.ColorManagement: .workingColorSpace is readonly.")},convert:function(t,e,i){if(this.legacyMode||e===i||!e||!i)return t;if(Gt[e]&&void 0!==Gt[e][i]){const n=Gt[e][i];return t.r=n(t.r),t.g=n(t.g),t.b=n(t.b),t}throw new Error("Unsupported color space conversion.")},fromWorkingColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this.workingColorSpace)}},Ht={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Wt={r:0,g:0,b:0},jt={h:0,s:0,l:0},qt={h:0,s:0,l:0};function Xt(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}function Yt(t,e){return e.r=t.r,e.g=t.g,e.b=t.b,e}class Zt{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,void 0===e&&void 0===i?this.set(t):this.setRGB(t,e,i)}set(t){return t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=ut){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,Vt.toWorkingColorSpace(this,e),this}setRGB(t,e,i,n=Vt.workingColorSpace){return this.r=t,this.g=e,this.b=i,Vt.toWorkingColorSpace(this,n),this}setHSL(t,e,i,n=Vt.workingColorSpace){if(t=wt(t,1),e=St(e,0,1),i=St(i,0,1),0===e)this.r=this.g=this.b=i;else{const n=i<=.5?i*(1+e):i+e-i*e,r=2*i-n;this.r=Xt(r,n,t+1/3),this.g=Xt(r,n,t),this.b=Xt(r,n,t-1/3)}return Vt.toWorkingColorSpace(this,n),this}setStyle(t,e=ut){function i(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(t)){let t;const r=n[1],s=n[2];switch(r){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return this.r=Math.min(255,parseInt(t[1],10))/255,this.g=Math.min(255,parseInt(t[2],10))/255,this.b=Math.min(255,parseInt(t[3],10))/255,Vt.toWorkingColorSpace(this,e),i(t[4]),this;if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return this.r=Math.min(100,parseInt(t[1],10))/100,this.g=Math.min(100,parseInt(t[2],10))/100,this.b=Math.min(100,parseInt(t[3],10))/100,Vt.toWorkingColorSpace(this,e),i(t[4]),this;break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s)){const n=parseFloat(t[1])/360,r=parseFloat(t[2])/100,s=parseFloat(t[3])/100;return i(t[4]),this.setHSL(n,r,s,e)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=n[1],i=t.length;if(3===i)return this.r=parseInt(t.charAt(0)+t.charAt(0),16)/255,this.g=parseInt(t.charAt(1)+t.charAt(1),16)/255,this.b=parseInt(t.charAt(2)+t.charAt(2),16)/255,Vt.toWorkingColorSpace(this,e),this;if(6===i)return this.r=parseInt(t.charAt(0)+t.charAt(1),16)/255,this.g=parseInt(t.charAt(2)+t.charAt(3),16)/255,this.b=parseInt(t.charAt(4)+t.charAt(5),16)/255,Vt.toWorkingColorSpace(this,e),this}return t&&t.length>0?this.setColorName(t,e):this}setColorName(t,e=ut){const i=Ht[t.toLowerCase()];return void 0!==i?this.setHex(i,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Ft(t.r),this.g=Ft(t.g),this.b=Ft(t.b),this}copyLinearToSRGB(t){return this.r=kt(t.r),this.g=kt(t.g),this.b=kt(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=ut){return Vt.fromWorkingColorSpace(Yt(this,Wt),t),St(255*Wt.r,0,255)<<16^St(255*Wt.g,0,255)<<8^St(255*Wt.b,0,255)<<0}getHexString(t=ut){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Vt.workingColorSpace){Vt.fromWorkingColorSpace(Yt(this,Wt),e);const i=Wt.r,n=Wt.g,r=Wt.b,s=Math.max(i,n,r),a=Math.min(i,n,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case i:o=(n-r)/t+(n2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=Bt("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const n=i.getImageData(0,0,t.width,t.height),r=n.data;for(let t=0;t0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==n)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case c:t.x=t.x-Math.floor(t.x);break;case h:t.x=t.x<0?0:1;break;case u: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 c:t.y=t.y-Math.floor(t.y);break;case h:t.y=t.y<0?0:1;break;case u:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}}ee.DEFAULT_IMAGE=null,ee.DEFAULT_MAPPING=n,ee.DEFAULT_ANISOTROPY=1;class ie{constructor(t=0,e=0,i=0,n=1){ie.prototype.isVector4=!0,this.x=t,this.y=e,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){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: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*i+s[8]*n+s[12]*r,this.y=s[1]*e+s[5]*i+s[9]*n+s[13]*r,this.z=s[2]*e+s[6]*i+s[10]*n+s[14]*r,this.w=s[3]*e+s[7]*i+s[11]*n+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,n,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,n=1-e*e;if(n>Number.EPSILON){const r=Math.sqrt(n),s=Math.atan2(r,e*i);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*i;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,i,n,r,s){const a=i[n],o=i[n+1],l=i[n+2],c=i[n+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,n){return this._x=t,this._y=e,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e){const i=t._x,n=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(i/2),c=a(n/2),h=a(r/2),u=o(i/2),d=o(n/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!1!==e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,n=Math.sin(i);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],n=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=i+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-n)*t}else if(i>a&&i>h){const t=2*Math.sqrt(1+i-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(n+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-i-h);this._w=(r-l)/t,this._x=(n+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-i-a);this._w=(s-n)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return iMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(St(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const n=Math.min(1,e/i);return this.slerp(t,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let 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(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,n=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=i*c+s*a+n*l-r*o,this._y=n*c+s*o+r*a-i*l,this._z=r*c+s*l+i*o-n*a,this._w=s*c-i*a-n*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,n=this._y,r=this._z,s=this._w;let a=s*t._w+i*t._x+n*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=i,this._y=n,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*i+e*this._x,this._y=t*n+e*this._y,this._z=t*r+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=i*h+this._x*u,this._y=n*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=Math.random(),e=Math.sqrt(1-t),i=Math.sqrt(t),n=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(e*Math.cos(n),i*Math.sin(r),i*Math.cos(r),e*Math.sin(n))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class oe{constructor(t=0,e=0,i=0){oe.prototype.isVector3=!0,this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(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)}return this}getComponent(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(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(ce.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ce.setFromAxisAngle(t,e))}applyMatrix3(t){const 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}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,r=t.elements,s=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])*s,this.y=(r[1]*e+r[5]*i+r[9]*n+r[13])*s,this.z=(r[2]*e+r[6]*i+r[10]*n+r[14])*s,this}applyQuaternion(t){const e=this.x,i=this.y,n=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=o*e+s*n-a*i,c=o*i+a*e-r*n,h=o*n+r*i-s*e,u=-r*e-s*i-a*n;return this.x=l*o+u*-r+c*-a-h*-s,this.y=c*o+u*-s+h*-r-l*-a,this.z=h*o+u*-a+l*-s-c*-r,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const 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(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(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(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(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(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){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(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(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(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,n=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=n*o-r*a,this.y=r*s-i*o,this.z=i*a-n*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return le.copy(this).projectOnVector(t),this.sub(le)}reflect(t){return this.sub(le.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(St(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const n=Math.sin(e)*t;return this.x=n*Math.sin(i),this.y=Math.cos(e)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const 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(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=2*(Math.random()-.5),e=Math.random()*Math.PI*2,i=Math.sqrt(1-t**2);return this.x=i*Math.cos(e),this.y=i*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const le=new oe,ce=new ae;class he{constructor(t=new oe(1/0,1/0,1/0),e=new oe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){let e=1/0,i=1/0,n=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.length;or&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,i,n),this.max.set(r,s,a),this}setFromBufferAttribute(t){let e=1/0,i=1/0,n=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.count;or&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,i,n),this.max.set(r,s,a),this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)}containsBox(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(t,e){return e.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(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)}intersectsSphere(t){return this.clampPoint(t.center,de),de.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let 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}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(ye),Me.subVectors(this.max,ye),me.subVectors(t.a,ye),fe.subVectors(t.b,ye),ge.subVectors(t.c,ye),ve.subVectors(fe,me),xe.subVectors(ge,fe),_e.subVectors(me,ge);let e=[0,-ve.z,ve.y,0,-xe.z,xe.y,0,-_e.z,_e.y,ve.z,0,-ve.x,xe.z,0,-xe.x,_e.z,0,-_e.x,-ve.y,ve.x,0,-xe.y,xe.x,0,-_e.y,_e.x,0];return!!we(e,me,fe,ge,Me)&&(e=[1,0,0,0,1,0,0,0,1],!!we(e,me,fe,ge,Me)&&(be.crossVectors(ve,xe),e=[be.x,be.y,be.z],we(e,me,fe,ge,Me)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return de.copy(t).clamp(this.min,this.max).sub(t).length()}getBoundingSphere(t){return this.getCenter(t.center),t.radius=.5*this.getSize(de).length(),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(ue[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),ue[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),ue[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),ue[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),ue[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),ue[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),ue[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),ue[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(ue)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const ue=[new oe,new oe,new oe,new oe,new oe,new oe,new oe,new oe],de=new oe,pe=new he,me=new oe,fe=new oe,ge=new oe,ve=new oe,xe=new oe,_e=new oe,ye=new oe,Me=new oe,be=new oe,Se=new oe;function we(t,e,i,n,r){for(let s=0,a=t.length-3;s<=a;s+=3){Se.fromArray(t,s);const a=r.x*Math.abs(Se.x)+r.y*Math.abs(Se.y)+r.z*Math.abs(Se.z),o=e.dot(Se),l=i.dot(Se),c=n.dot(Se);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Te=new he,Ae=new oe,Ee=new oe;class Ce{constructor(t=new oe,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;void 0!==e?i.copy(e):Te.setFromPoints(t).getCenter(i);let n=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Ae.subVectors(t,this.center);const e=Ae.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(Ae,i/t),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(Ee.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Ae.copy(t.center).add(Ee)),this.expandByPoint(Ae.copy(t.center).sub(Ee))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Le=new oe,Re=new oe,Pe=new oe,Ie=new oe,De=new oe,Ne=new oe,Oe=new oe;class ze{constructor(t=new oe,e=new oe(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Le)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(i).add(this.origin)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Le.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Le.copy(this.direction).multiplyScalar(e).add(this.origin),Le.distanceToSquared(t))}distanceSqToSegment(t,e,i,n){Re.copy(t).add(e).multiplyScalar(.5),Pe.copy(e).sub(t).normalize(),Ie.copy(this.origin).sub(Re);const r=.5*t.distanceTo(e),s=-this.direction.dot(Pe),a=Ie.dot(this.direction),o=-Ie.dot(Pe),l=Ie.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return i&&i.copy(this.direction).multiplyScalar(h).add(this.origin),n&&n.copy(Pe).multiplyScalar(u).add(Re),d}intersectSphere(t,e){Le.subVectors(t.center,this.origin);const i=Le.dot(this.direction),n=Le.dot(Le)-i*i,r=t.radius*t.radius;if(n>r)return null;const s=Math.sqrt(r-n),a=i-s,o=i+s;return a<0&&o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return null===i?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,n,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(i=(t.min.x-u.x)*l,n=(t.max.x-u.x)*l):(i=(t.max.x-u.x)*l,n=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),i>s||r>n?null:((r>i||isNaN(i))&&(i=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),i>o||a>n?null:((a>i||i!=i)&&(i=a),(o=0?i:n,e)))}intersectsBox(t){return null!==this.intersectBox(t,Le)}intersectTriangle(t,e,i,n,r){De.subVectors(e,t),Ne.subVectors(i,t),Oe.crossVectors(De,Ne);let s,a=this.direction.dot(Oe);if(a>0){if(n)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Ie.subVectors(this.origin,t);const o=s*this.direction.dot(Ne.crossVectors(Ie,Ne));if(o<0)return null;const l=s*this.direction.dot(De.cross(Ie));if(l<0)return null;if(o+l>a)return null;const c=-s*Ie.dot(Oe);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class Ue{constructor(){Ue.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set(t,e,i,n,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=n,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new Ue).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(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(t){const e=this.elements,i=t.elements,n=1/Be.setFromMatrixColumn(t,0).length(),r=1/Be.setFromMatrixColumn(t,1).length(),s=1/Be.setFromMatrixColumn(t,2).length();return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=0,e[4]=i[4]*r,e[5]=i[5]*r,e[6]=i[6]*r,e[7]=0,e[8]=i[8]*s,e[9]=i[9]*s,e[10]=i[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,n=t.y,r=t.z,s=Math.cos(i),a=Math.sin(i),o=Math.cos(n),l=Math.sin(n),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,i=s*h,n=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=i+n*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=n+i*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,i=o*h,n=l*c,r=l*h;e[0]=t+r*a,e[4]=n*a-i,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=i*a-n,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,i=o*h,n=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=n+i*a,e[1]=i+n*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,i=s*h,n=a*c,r=a*h;e[0]=o*c,e[4]=n*l-i,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=i*l-n,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,i=s*l,n=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=n*h+i,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=i*h+n,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,i=s*l,n=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=i*h-n,e[2]=n*h-i,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(ke,t,Ge)}lookAt(t,e,i){const n=this.elements;return We.subVectors(t,e),0===We.lengthSq()&&(We.z=1),We.normalize(),Ve.crossVectors(i,We),0===Ve.lengthSq()&&(1===Math.abs(i.z)?We.x+=1e-4:We.z+=1e-4,We.normalize(),Ve.crossVectors(i,We)),Ve.normalize(),He.crossVectors(We,Ve),n[0]=Ve.x,n[4]=He.x,n[8]=We.x,n[1]=Ve.y,n[5]=He.y,n[9]=We.y,n[2]=Ve.z,n[6]=He.z,n[10]=We.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,r=this.elements,s=i[0],a=i[4],o=i[8],l=i[12],c=i[1],h=i[5],u=i[9],d=i[13],p=i[2],m=i[6],f=i[10],g=i[14],v=i[3],x=i[7],_=i[11],y=i[15],M=n[0],b=n[4],S=n[8],w=n[12],T=n[1],A=n[5],E=n[9],C=n[13],L=n[2],R=n[6],P=n[10],I=n[14],D=n[3],N=n[7],O=n[11],z=n[15];return r[0]=s*M+a*T+o*L+l*D,r[4]=s*b+a*A+o*R+l*N,r[8]=s*S+a*E+o*P+l*O,r[12]=s*w+a*C+o*I+l*z,r[1]=c*M+h*T+u*L+d*D,r[5]=c*b+h*A+u*R+d*N,r[9]=c*S+h*E+u*P+d*O,r[13]=c*w+h*C+u*I+d*z,r[2]=p*M+m*T+f*L+g*D,r[6]=p*b+m*A+f*R+g*N,r[10]=p*S+m*E+f*P+g*O,r[14]=p*w+m*C+f*I+g*z,r[3]=v*M+x*T+_*L+y*D,r[7]=v*b+x*A+_*R+y*N,r[11]=v*S+x*E+_*P+y*O,r[15]=v*w+x*C+_*I+y*z,this}multiplyScalar(t){const 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}determinant(){const t=this.elements,e=t[0],i=t[4],n=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-n*l*h-r*a*u+i*l*u+n*a*d-i*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-n*s*d+n*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+i*s*d+r*a*c-i*l*c)+t[15]*(-n*a*c-e*o*h+e*a*u+n*s*h-i*s*u+i*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=e,n[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,x=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,_=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,y=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+i*x+n*_+r*y;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/M;return t[0]=v*b,t[1]=(m*u*r-h*f*r-m*n*d+i*f*d+h*n*g-i*u*g)*b,t[2]=(a*f*r-m*o*r+m*n*l-i*f*l-a*n*g+i*o*g)*b,t[3]=(h*o*r-a*u*r-h*n*l+i*u*l+a*n*d-i*o*d)*b,t[4]=x*b,t[5]=(c*f*r-p*u*r+p*n*d-e*f*d-c*n*g+e*u*g)*b,t[6]=(p*o*r-s*f*r-p*n*l+e*f*l+s*n*g-e*o*g)*b,t[7]=(s*u*r-c*o*r+c*n*l-e*u*l-s*n*d+e*o*d)*b,t[8]=_*b,t[9]=(p*h*r-c*m*r-p*i*d+e*m*d+c*i*g-e*h*g)*b,t[10]=(s*m*r-p*a*r+p*i*l-e*m*l-s*i*g+e*a*g)*b,t[11]=(c*a*r-s*h*r-c*i*l+e*h*l+s*i*d-e*a*d)*b,t[12]=y*b,t[13]=(c*m*n-p*h*n+p*i*u-e*m*u-c*i*f+e*h*f)*b,t[14]=(p*a*n-s*m*n-p*i*o+e*m*o+s*i*f-e*a*f)*b,t[15]=(s*h*n-c*a*n+c*i*o-e*h*o-s*i*u+e*a*u)*b,this}scale(t){const e=this.elements,i=t.x,n=t.y,r=t.z;return e[0]*=i,e[4]*=n,e[8]*=r,e[1]*=i,e[5]*=n,e[9]*=r,e[2]*=i,e[6]*=n,e[10]*=r,e[3]*=i,e[7]*=n,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,n))}makeTranslation(t,e,i){return this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),n=Math.sin(e),r=1-i,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+i,l*a-n*o,l*o+n*a,0,l*a+n*o,c*a+i,c*o-n*s,0,l*o-n*a,c*o+n*s,r*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,n,r,s){return this.set(1,i,r,0,t,1,s,0,e,n,1,0,0,0,0,1),this}compose(t,e,i){const n=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,x=o*c,_=o*h,y=i.x,M=i.y,b=i.z;return n[0]=(1-(m+g))*y,n[1]=(d+_)*y,n[2]=(p-x)*y,n[3]=0,n[4]=(d-_)*M,n[5]=(1-(u+g))*M,n[6]=(f+v)*M,n[7]=0,n[8]=(p+x)*b,n[9]=(f-v)*b,n[10]=(1-(u+m))*b,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,e,i){const n=this.elements;let r=Be.set(n[0],n[1],n[2]).length();const s=Be.set(n[4],n[5],n[6]).length(),a=Be.set(n[8],n[9],n[10]).length();this.determinant()<0&&(r=-r),t.x=n[12],t.y=n[13],t.z=n[14],Fe.copy(this);const o=1/r,l=1/s,c=1/a;return Fe.elements[0]*=o,Fe.elements[1]*=o,Fe.elements[2]*=o,Fe.elements[4]*=l,Fe.elements[5]*=l,Fe.elements[6]*=l,Fe.elements[8]*=c,Fe.elements[9]*=c,Fe.elements[10]*=c,e.setFromRotationMatrix(Fe),i.x=r,i.y=s,i.z=a,this}makePerspective(t,e,i,n,r,s){const a=this.elements,o=2*r/(e-t),l=2*r/(i-n),c=(e+t)/(e-t),h=(i+n)/(i-n),u=-(s+r)/(s-r),d=-2*s*r/(s-r);return a[0]=o,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=h,a[13]=0,a[2]=0,a[6]=0,a[10]=u,a[14]=d,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,i,n,r,s){const a=this.elements,o=1/(e-t),l=1/(i-n),c=1/(s-r),h=(e+t)*o,u=(i+n)*l,d=(s+r)*c;return a[0]=2*o,a[4]=0,a[8]=0,a[12]=-h,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-u,a[2]=0,a[6]=0,a[10]=-2*c,a[14]=-d,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const Be=new oe,Fe=new Ue,ke=new oe(0,0,0),Ge=new oe(1,1,1),Ve=new oe,He=new oe,We=new oe,je=new Ue,qe=new ae;class Xe{constructor(t=0,e=0,i=0,n=Xe.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,n=this._order){return this._x=t,this._y=e,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const n=t.elements,r=n[0],s=n[4],a=n[8],o=n[1],l=n[5],c=n[9],h=n[2],u=n[6],d=n[10];switch(e){case"XYZ":this._y=Math.asin(St(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-St(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(St(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-St(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(St(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-St(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return je.makeRotationFromQuaternion(t),this.setFromRotationMatrix(je,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return qe.setFromEuler(this),this.setFromQuaternion(qe,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Xe.DEFAULT_ORDER="XYZ";class Ye{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(i=i.concat(r))}return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ti,t,ei),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ti,ii,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,n=e.length;i0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),!1===this.matrixAutoUpdate&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(n.instanceColor=this.instanceColor.toJSON())),this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const i=e.shapes;if(Array.isArray(i))for(let e=0,n=i.length;e0){n.children=[];for(let e=0;e0){n.animations=[];for(let e=0;e0&&(i.geometries=e),n.length>0&&(i.materials=n),r.length>0&&(i.textures=r),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),c.length>0&&(i.animations=c),h.length>0&&(i.nodes=h)}return i.object=n,i;function s(t){const e=[];for(const i in t){const n=t[i];delete n.metadata,e.push(n)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,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.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.layers.mask=t.layers.mask,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)),!0===e)for(let e=0;e0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(t,e,i,n,r){ci.subVectors(n,e),hi.subVectors(i,e),ui.subVectors(t,e);const s=ci.dot(ci),a=ci.dot(hi),o=ci.dot(ui),l=hi.dot(hi),c=hi.dot(ui),h=s*l-a*a;if(0===h)return r.set(-2,-1,-1);const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,i,n){return this.getBarycoord(t,e,i,n,di),di.x>=0&&di.y>=0&&di.x+di.y<=1}static getUV(t,e,i,n,r,s,a,o){return this.getBarycoord(t,e,i,n,di),o.set(0,0),o.addScaledVector(r,di.x),o.addScaledVector(s,di.y),o.addScaledVector(a,di.z),o}static isFrontFacing(t,e,i,n){return ci.subVectors(i,e),hi.subVectors(t,e),ci.cross(hi).dot(n)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,e,i,n){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return ci.subVectors(this.c,this.b),hi.subVectors(this.a,this.b),.5*ci.cross(hi).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return _i.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return _i.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,i,n,r){return _i.getUV(t,this.a,this.b,this.c,e,i,n,r)}containsPoint(t){return _i.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return _i.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,n=this.b,r=this.c;let s,a;pi.subVectors(n,i),mi.subVectors(r,i),gi.subVectors(t,i);const o=pi.dot(gi),l=mi.dot(gi);if(o<=0&&l<=0)return e.copy(i);vi.subVectors(t,n);const c=pi.dot(vi),h=mi.dot(vi);if(c>=0&&h<=c)return e.copy(n);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(i).addScaledVector(pi,s);xi.subVectors(t,r);const d=pi.dot(xi),p=mi.dot(xi);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(mi,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return fi.subVectors(r,n),a=(h-c)/(h-c+(d-p)),e.copy(n).addScaledVector(fi,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(i).addScaledVector(pi,s).addScaledVector(mi,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let yi=0;class Mi extends vt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:yi++}),this.uuid=bt(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=i,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=pt,this.stencilZFail=pt,this.stencilZPass=pt,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const i=t[e];if(void 0===i){console.warn("THREE.Material: '"+e+"' parameter is undefined.");continue}const n=this[e];void 0!==n?n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[e]=i:console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.")}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const i={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function n(t){const e=[];for(const i in t){const n=t[i];delete n.metadata,e.push(n)}return e}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(i.blending=this.blending),0!==this.side&&(i.side=this.side),this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=this.transparent),i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.stencilWrite=this.stencilWrite,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(i.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(i.wireframe=this.wireframe),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=this.flatShading),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),e){const e=n(t.textures),r=n(t.images);e.length>0&&(i.textures=e),r.length>0&&(i.images=r)}return i}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,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.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(null!==e){const t=e.length;i=new Array(t);for(let n=0;n!==t;++n)i[n]=e[n].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}class bi extends Mi{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Zt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Si=new oe,wi=new It;class Ti{constructor(t,e,i=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=mt,this.updateRange={offset:0,count:-1},this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let n=0,r=this.itemSize;n0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const i in e)void 0!==e[i]&&(t[i]=e[i]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const e in i){const n=i[e];t.data.attributes[e]=n.toJSON(t.data)}const n={};let r=!1;for(const e in this.morphAttributes){const i=this.morphAttributes[e],s=[];for(let e=0,n=i.length;e0&&(n[e]=s,r=!0)}r&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;null!==i&&this.setIndex(i.clone(e));const n=t.attributes;for(const t in n){const i=n[t];this.setAttribute(t,i.clone(e))}const r=t.morphAttributes;for(const t in r){const i=[],n=r[t];for(let t=0,r=n.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;ti.far?null:{distance:c,point:Zi.clone(),object:t}}(t,e,i,n,ki,Gi,Vi,Yi);if(c){r&&(ji.fromBufferAttribute(r,a),qi.fromBufferAttribute(r,o),Xi.fromBufferAttribute(r,l),c.uv=_i.getUV(Yi,ki,Gi,Vi,ji,qi,Xi,new It)),s&&(ji.fromBufferAttribute(s,a),qi.fromBufferAttribute(s,o),Xi.fromBufferAttribute(s,l),c.uv2=_i.getUV(Yi,ki,Gi,Vi,ji,qi,Xi,new It));const t={a:a,b:o,c:l,normal:new oe,materialIndex:0};_i.getNormal(ki,Gi,Vi,t.normal),c.face=t}return c}class $i extends zi{constructor(t=1,e=1,i=1,n=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:n,heightSegments:r,depthSegments:s};const a=this;n=Math.floor(n),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,i,n,r,s,p,m,f,g,v){const x=s/f,_=p/g,y=s/2,M=p/2,b=m/2,S=f+1,w=g+1;let T=0,A=0;const E=new oe;for(let s=0;s0?1:-1,c.push(E.x,E.y,E.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;const i={};for(const t in this.extensions)!0===this.extensions[t]&&(i[t]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}}class sn extends li{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ue,this.projectionMatrix=new Ue,this.projectionMatrixInverse=new Ue}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}class an extends sn{constructor(t=50,e=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Mt*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*yt*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Mt*Math.atan(Math.tan(.5*yt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,i,n,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*yt*this.fov)/this.zoom,i=2*e,n=this.aspect*i,r=-.5*n;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*n/t,e-=s.offsetY*i/a,n*=s.width/t,i*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+n,e,e-i,t,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const on=-90;class ln extends li{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i;const n=new an(on,1,t,e);n.layers=this.layers,n.up.set(0,1,0),n.lookAt(1,0,0),this.add(n);const r=new an(on,1,t,e);r.layers=this.layers,r.up.set(0,1,0),r.lookAt(-1,0,0),this.add(r);const s=new an(on,1,t,e);s.layers=this.layers,s.up.set(0,0,-1),s.lookAt(0,1,0),this.add(s);const a=new an(on,1,t,e);a.layers=this.layers,a.up.set(0,0,1),a.lookAt(0,-1,0),this.add(a);const o=new an(on,1,t,e);o.layers=this.layers,o.up.set(0,1,0),o.lookAt(0,0,1),this.add(o);const l=new an(on,1,t,e);l.layers=this.layers,l.up.set(0,1,0),l.lookAt(0,0,-1),this.add(l)}update(t,e){null===this.parent&&this.updateMatrixWorld();const i=this.renderTarget,[n,r,s,a,o,l]=this.children,c=t.getRenderTarget(),h=t.toneMapping,u=t.xr.enabled;t.toneMapping=0,t.xr.enabled=!1;const d=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,t.setRenderTarget(i,0),t.render(e,n),t.setRenderTarget(i,1),t.render(e,r),t.setRenderTarget(i,2),t.render(e,s),t.setRenderTarget(i,3),t.render(e,a),t.setRenderTarget(i,4),t.render(e,o),i.texture.generateMipmaps=d,t.setRenderTarget(i,5),t.render(e,l),t.setRenderTarget(c),t.toneMapping=h,t.xr.enabled=u,i.texture.needsPMREMUpdate=!0}}class cn extends ee{constructor(t,e,i,n,s,a,o,l,c,h){super(t=void 0!==t?t:[],e=void 0!==e?e:r,i,n,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class hn extends ne{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const i={width:t,height:t,depth:1},n=[i,i,i,i,i,i];this.texture=new cn(n,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:f}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.encoding=e.encoding,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},n=new $i(5,5,5),r=new rn({name:"CubemapFromEquirect",uniforms:Qi(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const s=new Ji(n,r),a=e.minFilter;e.minFilter===v&&(e.minFilter=f);return new ln(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,i,n){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,i,n);t.setRenderTarget(r)}}const un=new oe,dn=new oe,pn=new Dt;class mn{constructor(t=new oe(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,n){return this.normal.set(t,e,i),this.constant=n,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const n=un.subVectors(i,e).cross(dn.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(this.normal).multiplyScalar(-this.distanceToPoint(t)).add(t)}intersectLine(t,e){const i=t.delta(un),n=this.normal.dot(i);if(0===n)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/n;return r<0||r>1?null:e.copy(i).multiplyScalar(r).add(t.start)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||pn.getNormalMatrix(t),n=this.coplanarPoint(un).applyMatrix4(t),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const fn=new Ce,gn=new oe;class vn{constructor(t=new mn,e=new mn,i=new mn,n=new mn,r=new mn,s=new mn){this.planes=[t,e,i,n,r,s]}set(t,e,i,n,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(n),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t){const e=this.planes,i=t.elements,n=i[0],r=i[1],s=i[2],a=i[3],o=i[4],l=i[5],c=i[6],h=i[7],u=i[8],d=i[9],p=i[10],m=i[11],f=i[12],g=i[13],v=i[14],x=i[15];return e[0].setComponents(a-n,h-o,m-u,x-f).normalize(),e[1].setComponents(a+n,h+o,m+u,x+f).normalize(),e[2].setComponents(a+r,h+l,m+d,x+g).normalize(),e[3].setComponents(a-r,h-l,m-d,x-g).normalize(),e[4].setComponents(a-s,h-c,m-p,x-v).normalize(),e[5].setComponents(a+s,h+c,m+p,x+v).normalize(),this}intersectsObject(t){const e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),fn.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(fn)}intersectsSprite(t){return fn.center.set(0,0,0),fn.radius=.7071067811865476,fn.applyMatrix4(t.matrixWorld),this.intersectsSphere(fn)}intersectsSphere(t){const e=this.planes,i=t.center,n=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(i)0?t.max.x:t.min.x,gn.y=n.normal.y>0?t.max.y:t.min.y,gn.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(gn)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function xn(){let t=null,e=!1,i=null,n=null;function r(e,s){i(e,s),n=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==i&&(n=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(t){i=t},setContext:function(e){t=e}}}function _n(t,e){const i=e.isWebGL2,n=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),n.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const i=n.get(e);i&&(t.deleteBuffer(i.buffer),n.delete(e))},update:function(e,r){if(e.isGLBufferAttribute){const t=n.get(e);return void((!t||t.version 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",output_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\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#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\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\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif",uv_pars_fragment:"#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}",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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",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\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},bn={common:{diffuse:{value:new Zt(16777215)},opacity:{value:1},map:{value:null},uvTransform:{value:new Dt},uv2Transform:{value:new Dt},alphaMap:{value:null},alphaTest:{value:0}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new It(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Zt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Zt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new Dt}},sprite:{diffuse:{value:new Zt(16777215)},opacity:{value:1},center:{value:new It(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new Dt}}},Sn={basic:{uniforms:tn([bn.common,bn.specularmap,bn.envmap,bn.aomap,bn.lightmap,bn.fog]),vertexShader:Mn.meshbasic_vert,fragmentShader:Mn.meshbasic_frag},lambert:{uniforms:tn([bn.common,bn.specularmap,bn.envmap,bn.aomap,bn.lightmap,bn.emissivemap,bn.bumpmap,bn.normalmap,bn.displacementmap,bn.fog,bn.lights,{emissive:{value:new Zt(0)}}]),vertexShader:Mn.meshlambert_vert,fragmentShader:Mn.meshlambert_frag},phong:{uniforms:tn([bn.common,bn.specularmap,bn.envmap,bn.aomap,bn.lightmap,bn.emissivemap,bn.bumpmap,bn.normalmap,bn.displacementmap,bn.fog,bn.lights,{emissive:{value:new Zt(0)},specular:{value:new Zt(1118481)},shininess:{value:30}}]),vertexShader:Mn.meshphong_vert,fragmentShader:Mn.meshphong_frag},standard:{uniforms:tn([bn.common,bn.envmap,bn.aomap,bn.lightmap,bn.emissivemap,bn.bumpmap,bn.normalmap,bn.displacementmap,bn.roughnessmap,bn.metalnessmap,bn.fog,bn.lights,{emissive:{value:new Zt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Mn.meshphysical_vert,fragmentShader:Mn.meshphysical_frag},toon:{uniforms:tn([bn.common,bn.aomap,bn.lightmap,bn.emissivemap,bn.bumpmap,bn.normalmap,bn.displacementmap,bn.gradientmap,bn.fog,bn.lights,{emissive:{value:new Zt(0)}}]),vertexShader:Mn.meshtoon_vert,fragmentShader:Mn.meshtoon_frag},matcap:{uniforms:tn([bn.common,bn.bumpmap,bn.normalmap,bn.displacementmap,bn.fog,{matcap:{value:null}}]),vertexShader:Mn.meshmatcap_vert,fragmentShader:Mn.meshmatcap_frag},points:{uniforms:tn([bn.points,bn.fog]),vertexShader:Mn.points_vert,fragmentShader:Mn.points_frag},dashed:{uniforms:tn([bn.common,bn.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Mn.linedashed_vert,fragmentShader:Mn.linedashed_frag},depth:{uniforms:tn([bn.common,bn.displacementmap]),vertexShader:Mn.depth_vert,fragmentShader:Mn.depth_frag},normal:{uniforms:tn([bn.common,bn.bumpmap,bn.normalmap,bn.displacementmap,{opacity:{value:1}}]),vertexShader:Mn.meshnormal_vert,fragmentShader:Mn.meshnormal_frag},sprite:{uniforms:tn([bn.sprite,bn.fog]),vertexShader:Mn.sprite_vert,fragmentShader:Mn.sprite_frag},background:{uniforms:{uvTransform:{value:new Dt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Mn.background_vert,fragmentShader:Mn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Mn.backgroundCube_vert,fragmentShader:Mn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Mn.cube_vert,fragmentShader:Mn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Mn.equirect_vert,fragmentShader:Mn.equirect_frag},distanceRGBA:{uniforms:tn([bn.common,bn.displacementmap,{referencePosition:{value:new oe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Mn.distanceRGBA_vert,fragmentShader:Mn.distanceRGBA_frag},shadow:{uniforms:tn([bn.lights,bn.fog,{color:{value:new Zt(0)},opacity:{value:1}}]),vertexShader:Mn.shadow_vert,fragmentShader:Mn.shadow_frag}};Sn.physical={uniforms:tn([Sn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new It(1,1)},clearcoatNormalMap:{value:null},iridescence:{value:0},iridescenceMap:{value:null},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},sheen:{value:0},sheenColor:{value:new Zt(0)},sheenColorMap:{value:null},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new It},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new Zt(0)},specularIntensity:{value:1},specularIntensityMap:{value:null},specularColor:{value:new Zt(1,1,1)},specularColorMap:{value:null}}]),vertexShader:Mn.meshphysical_vert,fragmentShader:Mn.meshphysical_frag};const wn={r:0,b:0,g:0};function Tn(t,e,i,n,r,s,a){const o=new Zt(0);let c,h,u=!0===s?0:1,d=null,p=0,m=null;function f(e,i){e.getRGB(wn,en(t)),n.buffers.color.setClear(wn.r,wn.g,wn.b,i,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),u=e,f(o,u)},getClearAlpha:function(){return u},setClearAlpha:function(t){u=t,f(o,u)},render:function(n,s){let a=!1,g=!0===s.isScene?s.background:null;if(g&&g.isTexture){g=(s.backgroundBlurriness>0?i:e).get(g)}const v=t.xr,x=v.getSession&&v.getSession();x&&"additive"===x.environmentBlendMode&&(g=null),null===g?f(o,u):g&&g.isColor&&(f(g,1),a=!0),(t.autoClear||a)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),g&&(g.isCubeTexture||g.mapping===l)?(void 0===h&&(h=new Ji(new $i(1,1,1),new rn({name:"BackgroundCubeMaterial",uniforms:Qi(Sn.backgroundCube.uniforms),vertexShader:Sn.backgroundCube.vertexShader,fragmentShader:Sn.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(t,e,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(h)),h.material.uniforms.envMap.value=g,h.material.uniforms.flipEnvMap.value=g.isCubeTexture&&!1===g.isRenderTargetTexture?-1:1,h.material.uniforms.backgroundBlurriness.value=s.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=s.backgroundIntensity,h.material.toneMapped=g.encoding!==ht,d===g&&p===g.version&&m===t.toneMapping||(h.material.needsUpdate=!0,d=g,p=g.version,m=t.toneMapping),h.layers.enableAll(),n.unshift(h,h.geometry,h.material,0,0,null)):g&&g.isTexture&&(void 0===c&&(c=new Ji(new yn(2,2),new rn({name:"BackgroundMaterial",uniforms:Qi(Sn.background.uniforms),vertexShader:Sn.background.vertexShader,fragmentShader:Sn.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=g,c.material.uniforms.backgroundIntensity.value=s.backgroundIntensity,c.material.toneMapped=g.encoding!==ht,!0===g.matrixAutoUpdate&&g.updateMatrix(),c.material.uniforms.uvTransform.value.copy(g.matrix),d===g&&p===g.version&&m===t.toneMapping||(c.material.needsUpdate=!0,d=g,p=g.version,m=t.toneMapping),c.layers.enableAll(),n.unshift(c,c.geometry,c.material,0,0,null))}}}function An(t,e,i,n){const r=t.getParameter(34921),s=n.isWebGL2?null:e.get("OES_vertex_array_object"),a=n.isWebGL2||null!==s,o={},l=p(null);let c=l,h=!1;function u(e){return n.isWebGL2?t.bindVertexArray(e):s.bindVertexArrayOES(e)}function d(e){return n.isWebGL2?t.deleteVertexArray(e):s.deleteVertexArrayOES(e)}function p(t){const e=[],i=[],n=[];for(let t=0;t=0){const i=r[e];let n=s[e];if(void 0===n&&("instanceMatrix"===e&&t.instanceMatrix&&(n=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(n=t.instanceColor)),void 0===i)return!0;if(i.attribute!==n)return!0;if(n&&i.data!==n.data)return!0;a++}}return c.attributesNum!==a||c.index!==n}(r,_,d,y),M&&function(t,e,i,n){const r={},s=e.attributes;let a=0;const o=i.getAttributes();for(const e in o){if(o[e].location>=0){let i=s[e];void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor));const n={};n.attribute=i,i&&i.data&&(n.data=i.data),r[e]=n,a++}}c.attributes=r,c.attributesNum=a,c.index=n}(r,_,d,y)}else{const t=!0===l.wireframe;c.geometry===_.id&&c.program===d.id&&c.wireframe===t||(c.geometry=_.id,c.program=d.id,c.wireframe=t,M=!0)}null!==y&&i.update(y,34963),(M||h)&&(h=!1,function(r,s,a,o){if(!1===n.isWebGL2&&(r.isInstancedMesh||o.isInstancedBufferGeometry)&&null===e.get("ANGLE_instanced_arrays"))return;m();const l=o.attributes,c=a.getAttributes(),h=s.defaultAttributeValues;for(const e in c){const n=c[e];if(n.location>=0){let s=l[e];if(void 0===s&&("instanceMatrix"===e&&r.instanceMatrix&&(s=r.instanceMatrix),"instanceColor"===e&&r.instanceColor&&(s=r.instanceColor)),void 0!==s){const e=s.normalized,a=s.itemSize,l=i.get(s);if(void 0===l)continue;const c=l.buffer,h=l.type,u=l.bytesPerElement;if(s.isInterleavedBufferAttribute){const i=s.data,l=i.stride,d=s.offset;if(i.isInstancedInterleavedBuffer){for(let t=0;t0&&t.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(35633,36337).precision>0&&t.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const s="undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext;let a=void 0!==i.precision?i.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||e.has("WEBGL_draw_buffers"),c=!0===i.logarithmicDepthBuffer,h=t.getParameter(34930),u=t.getParameter(35660),d=t.getParameter(3379),p=t.getParameter(34076),m=t.getParameter(34921),f=t.getParameter(36347),g=t.getParameter(36348),v=t.getParameter(36349),x=u>0,_=s||e.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==n)return n;if(!0===e.has("EXT_texture_filter_anisotropic")){const i=e.get("EXT_texture_filter_anisotropic");n=t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n},getMaxPrecision:r,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:f,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:x,floatFragmentTextures:_,floatVertexTextures:x&&_,maxSamples:s?t.getParameter(36183):0}}function Ln(t){const e=this;let i=null,n=0,r=!1,s=!1;const a=new mn,o=new Dt,l={value:null,needsUpdate:!1};function c(t,i,n,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=n+4*s,r=i.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0);e.numPlanes=n,e.numIntersection=0}();else{const t=s?0:n,e=4*t;let r=m.clippingState||null;l.value=r,r=c(u,o,e,h);for(let t=0;t!==e;++t)r[t]=i[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Rn(t){let e=new WeakMap;function i(t,e){return e===a?t.mapping=r:e===o&&(t.mapping=s),t}function n(t){const i=t.target;i.removeEventListener("dispose",n);const r=e.get(i);void 0!==r&&(e.delete(i),r.dispose())}return{get:function(r){if(r&&r.isTexture&&!1===r.isRenderTargetTexture){const s=r.mapping;if(s===a||s===o){if(e.has(r)){return i(e.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new hn(s.height/2);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",n),i(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}class Pn extends sn{constructor(t=-1,e=1,i=1,n=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=i,this.bottom=n,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,i,n,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let r=i-t,s=i+t,a=n+e,o=n-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const In=[.125,.215,.35,.446,.526,.582],Dn=20,Nn=new Pn,On=new Zt;let zn=null;const Un=(1+Math.sqrt(5))/2,Bn=1/Un,Fn=[new oe(1,1,1),new oe(-1,1,1),new oe(1,1,-1),new oe(-1,1,-1),new oe(0,Un,Bn),new oe(0,Un,-Bn),new oe(Bn,0,Un),new oe(-Bn,0,Un),new oe(Un,Bn,0),new oe(-Un,Bn,0)];class kn{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,i=.1,n=100){zn=this._renderer.getRenderTarget(),this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(t,i,n,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Wn(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Hn(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;tt-4?o=In[a-t+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,v=new Float32Array(m*p*d),x=new Float32Array(f*p*d),_=new Float32Array(g*p*d);for(let t=0;t2?0:-1,n=[e,i,0,e+2/3,i,0,e+2/3,i+1,0,e,i,0,e+2/3,i+1,0,e,i+1,0];v.set(n,m*p*t),x.set(u,f*p*t);const r=[t,t,t,t,t,t];_.set(r,g*p*t)}const y=new zi;y.setAttribute("position",new Ti(v,m)),y.setAttribute("uv",new Ti(x,f)),y.setAttribute("faceIndex",new Ti(_,g)),e.push(y),r>4&&r--}return{lodPlanes:e,sizeLods:i,sigmas:n}}(n)),this._blurMaterial=function(t,e,i){const n=new Float32Array(Dn),r=new oe(0,1,0),s=new rn({name:"SphericalGaussianBlur",defines:{n:Dn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:jn(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(n,t,e)}return n}_compileMaterial(t){const e=new Ji(this._lodPlanes[0],t);this._renderer.compile(e,Nn)}_sceneToCubeUV(t,e,i,n){const r=new an(90,1,e,i),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(On),o.toneMapping=0,o.autoClear=!1;const h=new bi({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Ji(new $i,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(On),d=!0);for(let e=0;e<6;e++){const i=e%3;0===i?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===i?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e]));const l=this._cubeSize;Vn(n,i*l,e>2?l:0,l,l),o.setRenderTarget(n),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const i=this._renderer,n=t.mapping===r||t.mapping===s;n?(null===this._cubemapMaterial&&(this._cubemapMaterial=Wn()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Hn());const a=n?this._cubemapMaterial:this._equirectMaterial,o=new Ji(this._lodPlanes[0],a);a.uniforms.envMap.value=t;const l=this._cubeSize;Vn(e,0,0,3*l,2*l),i.setRenderTarget(e),i.render(o,Nn)}_applyPMREM(t){const e=this._renderer,i=e.autoClear;e.autoClear=!1;for(let e=1;eDn&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;tv-4?n-v+4:0),4*(this._cubeSize-x),3*x,2*x),o.setRenderTarget(e),o.render(c,Nn)}}function Gn(t,e,i){const n=new ne(t,e,i);return n.texture.mapping=l,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Vn(t,e,i,n,r){t.viewport.set(e,i,n,r),t.scissor.set(e,i,n,r)}function Hn(){return new rn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:jn(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Wn(){return new rn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:jn(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function jn(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function qn(t){let e=new WeakMap,i=null;function n(t){const i=t.target;i.removeEventListener("dispose",n);const r=e.get(i);void 0!==r&&(e.delete(i),r.dispose())}return{get:function(l){if(l&&l.isTexture){const c=l.mapping,h=c===a||c===o,u=c===r||c===s;if(h||u){if(l.isRenderTargetTexture&&!0===l.needsPMREMUpdate){l.needsPMREMUpdate=!1;let n=e.get(l);return null===i&&(i=new kn(t)),n=h?i.fromEquirectangular(l,n):i.fromCubemap(l,n),e.set(l,n),n.texture}if(e.has(l))return e.get(l).texture;{const r=l.image;if(h&&r&&r.height>0||u&&r&&function(t){let e=0;const i=6;for(let n=0;ne.maxTextureSize&&(E=Math.ceil(A/e.maxTextureSize),A=e.maxTextureSize);const C=new Float32Array(A*E*4*m),L=new re(C,A,E,m);L.type=M,L.needsUpdate=!0;const R=4*T;for(let I=0;I0)return t;const r=e*i;let s=sr[r];if(void 0===s&&(s=new Float32Array(r),sr[r]=s),0!==e){n.toArray(s,0);for(let n=1,r=0;n!==e;++n)r+=i,t[n].toArray(s,r)}return s}function ur(t,e){if(t.length!==e.length)return!1;for(let i=0,n=t.length;i":" "} ${r}: ${i[t]}`)}return n.join("\n")}(t.getShaderSource(e),n)}return r}function ls(t,e){const i=function(t){switch(t){case ct:return["Linear","( value )"];case ht:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",t),["Linear","( value )"]}}(e);return"vec4 "+t+"( vec4 value ) { return LinearTo"+i[0]+i[1]+"; }"}function cs(t,e){let i;switch(e){case 1:i="Linear";break;case 2:i="Reinhard";break;case 3:i="OptimizedCineon";break;case 4:i="ACESFilmic";break;case 5:i="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),i="Linear"}return"vec3 "+t+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}function hs(t){return""!==t}function us(t,e){const i=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,i).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function ds(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const ps=/^[ \t]*#include +<([\w\d./]+)>/gm;function ms(t){return t.replace(ps,fs)}function fs(t,e){const i=Mn[e];if(void 0===i)throw new Error("Can not resolve #include <"+e+">");return ms(i)}const gs=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function vs(t){return t.replace(gs,xs)}function xs(t,e,i,n){let r="";for(let t=parseInt(e);t0&&(_+="\n"),y=[g,v].filter(hs).join("\n"),y.length>0&&(y+="\n")):(_=[_s(i),"#define SHADER_NAME "+i.shaderName,v,i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.supportsVertexTextures?"#define VERTEX_TEXTURES":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+p:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMap&&i.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",i.normalMap&&i.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.displacementMap&&i.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",i.specularColorMap?"#define USE_SPECULARCOLORMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEENCOLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",i.vertexTangents?"#define USE_TANGENT":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUvs?"#define USE_UV":"",i.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&!1===i.flatShading?"#define USE_MORPHNORMALS":"",i.morphColors&&i.isWebGL2?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+u:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\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(hs).join("\n"),y=[g,_s(i),"#define SHADER_NAME "+i.shaderName,v,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+d:"",i.envMap?"#define "+p:"",i.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMap&&i.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",i.normalMap&&i.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",i.specularColorMap?"#define USE_SPECULARCOLORMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEENCOLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.vertexTangents?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUvs?"#define USE_UV":"",i.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+u:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==i.toneMapping?"#define TONE_MAPPING":"",0!==i.toneMapping?Mn.tonemapping_pars_fragment:"",0!==i.toneMapping?cs("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",Mn.encodings_pars_fragment,ls("linearToOutputTexel",i.outputEncoding),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(hs).join("\n")),c=ms(c),c=us(c,i),c=ds(c,i),h=ms(h),h=us(h,i),h=ds(h,i),c=vs(c),h=vs(h),i.isWebGL2&&!0!==i.isRawShaderMaterial&&(M="#version 300 es\n",_=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+_,y=["#define varying in",i.glslVersion===ft?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===ft?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+y);const b=M+y+h,S=ss(a,35633,M+_+c),w=ss(a,35632,b);if(a.attachShader(x,S),a.attachShader(x,w),void 0!==i.index0AttributeName?a.bindAttribLocation(x,0,i.index0AttributeName):!0===i.morphTargets&&a.bindAttribLocation(x,0,"position"),a.linkProgram(x),t.debug.checkShaderErrors){const t=a.getProgramInfoLog(x).trim(),e=a.getShaderInfoLog(S).trim(),i=a.getShaderInfoLog(w).trim();let n=!0,r=!0;if(!1===a.getProgramParameter(x,35714)){n=!1;const e=os(a,S,"vertex"),i=os(a,w,"fragment");console.error("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(x,35715)+"\n\nProgram Info Log: "+t+"\n"+e+"\n"+i)}else""!==t?console.warn("THREE.WebGLProgram: Program Info Log:",t):""!==e&&""!==i||(r=!1);r&&(this.diagnostics={runnable:n,programLog:t,vertexShader:{log:e,prefix:_},fragmentShader:{log:i,prefix:y}})}let T,A;return a.deleteShader(S),a.deleteShader(w),this.getUniforms=function(){return void 0===T&&(T=new rs(a,x)),T},this.getAttributes=function(){return void 0===A&&(A=function(t,e){const i={},n=t.getProgramParameter(e,35721);for(let r=0;r0,D=s.clearcoat>0,N=s.iridescence>0;return{isWebGL2:u,shaderID:S,shaderName:s.type,vertexShader:A,fragmentShader:E,defines:s.defines,customVertexShaderID:C,customFragmentShaderID:L,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:m,instancing:!0===v.isInstancedMesh,instancingColor:!0===v.isInstancedMesh&&null!==v.instanceColor,supportsVertexTextures:p,outputEncoding:null===P?t.outputEncoding:!0===P.isXRRenderTarget?P.texture.encoding:ct,map:!!s.map,matcap:!!s.matcap,envMap:!!M,envMapMode:M&&M.mapping,envMapCubeUVHeight:b,lightMap:!!s.lightMap,aoMap:!!s.aoMap,emissiveMap:!!s.emissiveMap,bumpMap:!!s.bumpMap,normalMap:!!s.normalMap,objectSpaceNormalMap:1===s.normalMapType,tangentSpaceNormalMap:0===s.normalMapType,decodeVideoTexture:!!s.map&&!0===s.map.isVideoTexture&&s.map.encoding===ht,clearcoat:D,clearcoatMap:D&&!!s.clearcoatMap,clearcoatRoughnessMap:D&&!!s.clearcoatRoughnessMap,clearcoatNormalMap:D&&!!s.clearcoatNormalMap,iridescence:N,iridescenceMap:N&&!!s.iridescenceMap,iridescenceThicknessMap:N&&!!s.iridescenceThicknessMap,displacementMap:!!s.displacementMap,roughnessMap:!!s.roughnessMap,metalnessMap:!!s.metalnessMap,specularMap:!!s.specularMap,specularIntensityMap:!!s.specularIntensityMap,specularColorMap:!!s.specularColorMap,opaque:!1===s.transparent&&1===s.blending,alphaMap:!!s.alphaMap,alphaTest:I,gradientMap:!!s.gradientMap,sheen:s.sheen>0,sheenColorMap:!!s.sheenColorMap,sheenRoughnessMap:!!s.sheenRoughnessMap,transmission:s.transmission>0,transmissionMap:!!s.transmissionMap,thicknessMap:!!s.thicknessMap,combine:s.combine,vertexTangents:!!s.normalMap&&!!_.attributes.tangent,vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!_.attributes.color&&4===_.attributes.color.itemSize,vertexUvs:!!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatMap||s.clearcoatRoughnessMap||s.clearcoatNormalMap||s.iridescenceMap||s.iridescenceThicknessMap||s.displacementMap||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheenColorMap||s.sheenRoughnessMap),uvsVertexOnly:!(s.map||s.bumpMap||s.normalMap||s.specularMap||s.alphaMap||s.emissiveMap||s.roughnessMap||s.metalnessMap||s.clearcoatNormalMap||s.iridescenceMap||s.iridescenceThicknessMap||s.transmission>0||s.transmissionMap||s.thicknessMap||s.specularIntensityMap||s.specularColorMap||s.sheen>0||s.sheenColorMap||s.sheenRoughnessMap||!s.displacementMap),fog:!!x,useFog:!0===s.fog,fogExp2:x&&x.isFogExp2,flatShading:!!s.flatShading,sizeAttenuation:s.sizeAttenuation,logarithmicDepthBuffer:d,skinning:!0===v.isSkinnedMesh,morphTargets:void 0!==_.morphAttributes.position,morphNormals:void 0!==_.morphAttributes.normal,morphColors:void 0!==_.morphAttributes.color,morphTargetsCount:T,morphTextureStride:R,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:s.toneMapped?t.toneMapping:0,physicallyCorrectLights:t.physicallyCorrectLights,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:!!s.depthPacking,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionDerivatives:s.extensions&&s.extensions.derivatives,extensionFragDepth:s.extensions&&s.extensions.fragDepth,extensionDrawBuffers:s.extensions&&s.extensions.drawBuffers,extensionShaderTextureLOD:s.extensions&&s.extensions.shaderTextureLOD,rendererExtensionFragDepth:u||n.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||n.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||n.has("EXT_shader_texture_lod"),customProgramCacheKey:s.customProgramCacheKey()}},getProgramCacheKey:function(e){const i=[];if(e.shaderID?i.push(e.shaderID):(i.push(e.customVertexShaderID),i.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)i.push(t),i.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputEncoding),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.combine),t.push(e.vertexUvs),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(i,e),function(t,e){o.disableAll(),e.isWebGL2&&o.enable(0);e.supportsVertexTextures&&o.enable(1);e.instancing&&o.enable(2);e.instancingColor&&o.enable(3);e.map&&o.enable(4);e.matcap&&o.enable(5);e.envMap&&o.enable(6);e.lightMap&&o.enable(7);e.aoMap&&o.enable(8);e.emissiveMap&&o.enable(9);e.bumpMap&&o.enable(10);e.normalMap&&o.enable(11);e.objectSpaceNormalMap&&o.enable(12);e.tangentSpaceNormalMap&&o.enable(13);e.clearcoat&&o.enable(14);e.clearcoatMap&&o.enable(15);e.clearcoatRoughnessMap&&o.enable(16);e.clearcoatNormalMap&&o.enable(17);e.iridescence&&o.enable(18);e.iridescenceMap&&o.enable(19);e.iridescenceThicknessMap&&o.enable(20);e.displacementMap&&o.enable(21);e.specularMap&&o.enable(22);e.roughnessMap&&o.enable(23);e.metalnessMap&&o.enable(24);e.gradientMap&&o.enable(25);e.alphaMap&&o.enable(26);e.alphaTest&&o.enable(27);e.vertexColors&&o.enable(28);e.vertexAlphas&&o.enable(29);e.vertexUvs&&o.enable(30);e.vertexTangents&&o.enable(31);e.uvsVertexOnly&&o.enable(32);t.push(o.mask),o.disableAll(),e.fog&&o.enable(0);e.useFog&&o.enable(1);e.flatShading&&o.enable(2);e.logarithmicDepthBuffer&&o.enable(3);e.skinning&&o.enable(4);e.morphTargets&&o.enable(5);e.morphNormals&&o.enable(6);e.morphColors&&o.enable(7);e.premultipliedAlpha&&o.enable(8);e.shadowMapEnabled&&o.enable(9);e.physicallyCorrectLights&&o.enable(10);e.doubleSided&&o.enable(11);e.flipSided&&o.enable(12);e.useDepthPacking&&o.enable(13);e.dithering&&o.enable(14);e.specularIntensityMap&&o.enable(15);e.specularColorMap&&o.enable(16);e.transmission&&o.enable(17);e.transmissionMap&&o.enable(18);e.thicknessMap&&o.enable(19);e.sheen&&o.enable(20);e.sheenColorMap&&o.enable(21);e.sheenRoughnessMap&&o.enable(22);e.decodeVideoTexture&&o.enable(23);e.opaque&&o.enable(24);t.push(o.mask)}(i,e),i.push(t.outputEncoding)),i.push(e.customProgramCacheKey),i.join()},getUniforms:function(t){const e=f[t.type];let i;if(e){const t=Sn[e];i=nn.clone(t.uniforms)}else i=t.uniforms;return i},acquireProgram:function(e,i){let n;for(let t=0,e=h.length;t0?n.push(h):!0===a.transparent?r.push(h):i.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?n.unshift(h):!0===a.transparent?r.unshift(h):i.unshift(h)},finish:function(){for(let i=e,n=t.length;i1&&i.sort(t||As),n.length>1&&n.sort(e||Es),r.length>1&&r.sort(e||Es)}}}function Ls(){let t=new WeakMap;return{get:function(e,i){const n=t.get(e);let r;return void 0===n?(r=new Cs,t.set(e,[r])):i>=n.length?(r=new Cs,n.push(r)):r=n[i],r},dispose:function(){t=new WeakMap}}}function Rs(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":i={direction:new oe,color:new Zt};break;case"SpotLight":i={position:new oe,direction:new oe,color:new Zt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new oe,color:new Zt,distance:0,decay:0};break;case"HemisphereLight":i={direction:new oe,skyColor:new Zt,groundColor:new Zt};break;case"RectAreaLight":i={color:new Zt,position:new oe,halfWidth:new oe,halfHeight:new oe}}return t[e.id]=i,i}}}let Ps=0;function Is(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Ds(t,e){const i=new Rs,n=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":case"SpotLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"PointLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=i,i}}}(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0};for(let t=0;t<9;t++)r.probe.push(new oe);const s=new oe,a=new Ue,o=new Ue;return{setup:function(s,a){let o=0,l=0,c=0;for(let t=0;t<9;t++)r.probe[t].set(0,0,0);let h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0,x=0,_=0;s.sort(Is);const y=!0!==a?Math.PI:1;for(let t=0,e=s.length;t0&&(e.isWebGL2||!0===t.has("OES_texture_float_linear")?(r.rectAreaLTC1=bn.LTC_FLOAT_1,r.rectAreaLTC2=bn.LTC_FLOAT_2):!0===t.has("OES_texture_half_float_linear")?(r.rectAreaLTC1=bn.LTC_HALF_1,r.rectAreaLTC2=bn.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=o,r.ambient[1]=l,r.ambient[2]=c;const M=r.hash;M.directionalLength===h&&M.pointLength===u&&M.spotLength===d&&M.rectAreaLength===p&&M.hemiLength===m&&M.numDirectionalShadows===f&&M.numPointShadows===g&&M.numSpotShadows===v&&M.numSpotMaps===x||(r.directional.length=h,r.spot.length=d,r.rectArea.length=p,r.point.length=u,r.hemi.length=m,r.directionalShadow.length=f,r.directionalShadowMap.length=f,r.pointShadow.length=g,r.pointShadowMap.length=g,r.spotShadow.length=v,r.spotShadowMap.length=v,r.directionalShadowMatrix.length=f,r.pointShadowMatrix.length=g,r.spotLightMatrix.length=v+x-_,r.spotLightMap.length=x,r.numSpotLightShadowsWithMaps=_,M.directionalLength=h,M.pointLength=u,M.spotLength=d,M.rectAreaLength=p,M.hemiLength=m,M.numDirectionalShadows=f,M.numPointShadows=g,M.numSpotShadows=v,M.numSpotMaps=x,r.version=Ps++)},setupView:function(t,e){let i=0,n=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e=s.length?(a=new Ns(t,e),s.push(a)):a=s[r],a},dispose:function(){i=new WeakMap}}}class zs extends Mi{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class Us extends Mi{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.referencePosition=new oe,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.referencePosition.copy(t.referencePosition),this.nearDistance=t.nearDistance,this.farDistance=t.farDistance,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Bs(t,e,i){let n=new vn;const r=new It,s=new It,a=new ie,o=new zs({depthPacking:3201}),l=new Us,c={},h=i.maxTextureSize,u={0:1,1:0,2:2,3:2},p=new rn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new It},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),m=p.clone();m.defines.HORIZONTAL_PASS=1;const f=new zi;f.setAttribute("position",new Ti(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new Ji(f,p),v=this;function x(i,n){const s=e.update(g);p.defines.VSM_SAMPLES!==i.blurSamples&&(p.defines.VSM_SAMPLES=i.blurSamples,m.defines.VSM_SAMPLES=i.blurSamples,p.needsUpdate=!0,m.needsUpdate=!0),null===i.mapPass&&(i.mapPass=new ne(r.x,r.y)),p.uniforms.shadow_pass.value=i.map.texture,p.uniforms.resolution.value=i.mapSize,p.uniforms.radius.value=i.radius,t.setRenderTarget(i.mapPass),t.clear(),t.renderBufferDirect(n,null,s,p,g,null),m.uniforms.shadow_pass.value=i.mapPass.texture,m.uniforms.resolution.value=i.mapSize,m.uniforms.radius.value=i.radius,t.setRenderTarget(i.map),t.clear(),t.renderBufferDirect(n,null,s,m,g,null)}function _(e,i,n,r,s,a){let h=null;const d=!0===n.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==d)h=d;else if(h=!0===n.isPointLight?l:o,t.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0){const t=h.uuid,e=i.uuid;let n=c[t];void 0===n&&(n={},c[t]=n);let r=n[e];void 0===r&&(r=h.clone(),n[e]=r),h=r}return h.visible=i.visible,h.wireframe=i.wireframe,h.side=3===a?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:u[i.side],h.alphaMap=i.alphaMap,h.alphaTest=i.alphaTest,h.map=i.map,h.clipShadows=i.clipShadows,h.clippingPlanes=i.clippingPlanes,h.clipIntersection=i.clipIntersection,h.displacementMap=i.displacementMap,h.displacementScale=i.displacementScale,h.displacementBias=i.displacementBias,h.wireframeLinewidth=i.wireframeLinewidth,h.linewidth=i.linewidth,!0===n.isPointLight&&!0===h.isMeshDistanceMaterial&&(h.referencePosition.setFromMatrixPosition(n.matrixWorld),h.nearDistance=r,h.farDistance=s),h}function y(i,r,s,a,o){if(!1===i.visible)return;if(i.layers.test(r.layers)&&(i.isMesh||i.isLine||i.isPoints)&&(i.castShadow||i.receiveShadow&&3===o)&&(!i.frustumCulled||n.intersectsObject(i))){i.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,i.matrixWorld);const n=e.update(i),r=i.material;if(Array.isArray(r)){const e=n.groups;for(let l=0,c=e.length;lh||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/m.x),r.x=s.x*m.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/m.y),r.y=s.y*m.y,u.mapSize.y=s.y)),null===u.map){const t=3!==this.type?{minFilter:d,magFilter:d}:{};u.map=new ne(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const f=u.getViewportCount();for(let t=0;t=1):-1!==I.indexOf("OpenGL ES")&&(P=parseFloat(/^OpenGL ES (\d)/.exec(I)[1]),R=P>=2);let D=null,N={};const O=t.getParameter(3088),z=t.getParameter(2978),U=(new ie).fromArray(O),B=(new ie).fromArray(z);function F(e,i,n){const r=new Uint8Array(4),s=t.createTexture();t.bindTexture(e,s),t.texParameteri(e,10241,9728),t.texParameteri(e,10240,9728);for(let e=0;en||t.height>n)&&(r=n/Math.max(t.width,t.height)),r<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const n=e?Ct:Math.floor,s=n(r*t.width),a=n(r*t.height);void 0===D&&(D=z(s,a));const o=i?z(s,a):D;o.width=s,o.height=a;return o.getContext("2d").drawImage(t,0,0,s,a),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+t.width+"x"+t.height+") to ("+s+"x"+a+")."),o}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+t.width+"x"+t.height+")."),t}return t}function B(t){return At(t.width)&&At(t.height)}function F(t,e){return t.generateMipmaps&&e&&t.minFilter!==d&&t.minFilter!==f}function k(e){t.generateMipmap(e)}function G(i,n,r,s,a=!1){if(!1===o)return n;if(null!==i){if(void 0!==t[i])return t[i];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+i+"'")}let l=n;return 6403===n&&(5126===r&&(l=33326),5131===r&&(l=33325),5121===r&&(l=33321)),33319===n&&(5126===r&&(l=33328),5131===r&&(l=33327),5121===r&&(l=33323)),6408===n&&(5126===r&&(l=34836),5131===r&&(l=34842),5121===r&&(l=s===ht&&!1===a?35907:32856),32819===r&&(l=32854),32820===r&&(l=32855)),33325!==l&&33326!==l&&33327!==l&&33328!==l&&34842!==l&&34836!==l||e.get("EXT_color_buffer_float"),l}function V(t,e,i){return!0===F(t,i)||t.isFramebufferTexture&&t.minFilter!==d&&t.minFilter!==f?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function H(t){return t===d||t===p||t===m?9728:9729}function W(t){const e=t.target;e.removeEventListener("dispose",W),function(t){const e=n.get(t);if(void 0===e.__webglInit)return;const i=t.source,r=N.get(i);if(r){const n=r[e.__cacheKey];n.usedTimes--,0===n.usedTimes&&q(t),0===Object.keys(r).length&&N.delete(i)}n.remove(t)}(e),e.isVideoTexture&&I.delete(e)}function j(e){const i=e.target;i.removeEventListener("dispose",j),function(e){const i=e.texture,r=n.get(e),s=n.get(i);void 0!==s.__webglTexture&&(t.deleteTexture(s.__webglTexture),a.memory.textures--);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++)t.deleteFramebuffer(r.__webglFramebuffer[e]),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer[e]);else{if(t.deleteFramebuffer(r.__webglFramebuffer),r.__webglDepthbuffer&&t.deleteRenderbuffer(r.__webglDepthbuffer),r.__webglMultisampledFramebuffer&&t.deleteFramebuffer(r.__webglMultisampledFramebuffer),r.__webglColorRenderbuffer)for(let e=0;e0&&r.__version!==t.version){const i=t.image;if(null===i)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==i.complete)return void Q(r,t,e);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}i.bindTexture(3553,r.__webglTexture,33984+e)}const Z={[c]:10497,[h]:33071,[u]:33648},J={[d]:9728,[p]:9984,[m]:9986,[f]:9729,[g]:9985,[v]:9987};function K(i,s,a){if(a?(t.texParameteri(i,10242,Z[s.wrapS]),t.texParameteri(i,10243,Z[s.wrapT]),32879!==i&&35866!==i||t.texParameteri(i,32882,Z[s.wrapR]),t.texParameteri(i,10240,J[s.magFilter]),t.texParameteri(i,10241,J[s.minFilter])):(t.texParameteri(i,10242,33071),t.texParameteri(i,10243,33071),32879!==i&&35866!==i||t.texParameteri(i,32882,33071),s.wrapS===h&&s.wrapT===h||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(i,10240,H(s.magFilter)),t.texParameteri(i,10241,H(s.minFilter)),s.minFilter!==d&&s.minFilter!==f&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),!0===e.has("EXT_texture_filter_anisotropic")){const a=e.get("EXT_texture_filter_anisotropic");if(s.magFilter===d)return;if(s.minFilter!==m&&s.minFilter!==v)return;if(s.type===M&&!1===e.has("OES_texture_float_linear"))return;if(!1===o&&s.type===b&&!1===e.has("OES_texture_half_float_linear"))return;(s.anisotropy>1||n.get(s).__currentAnisotropy)&&(t.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),n.get(s).__currentAnisotropy=s.anisotropy)}}function $(e,i){let n=!1;void 0===e.__webglInit&&(e.__webglInit=!0,i.addEventListener("dispose",W));const r=i.source;let s=N.get(r);void 0===s&&(s={},N.set(r,s));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.encoding),e.join()}(i);if(o!==e.__cacheKey){void 0===s[o]&&(s[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,n=!0),s[o].usedTimes++;const r=s[e.__cacheKey];void 0!==r&&(s[e.__cacheKey].usedTimes--,0===r.usedTimes&&q(i)),e.__cacheKey=o,e.__webglTexture=s[o].texture}return n}function Q(e,r,a){let l=3553;(r.isDataArrayTexture||r.isCompressedArrayTexture)&&(l=35866),r.isData3DTexture&&(l=32879);const c=$(e,r),u=r.source;i.bindTexture(l,e.__webglTexture,33984+a);const p=n.get(u);if(u.version!==p.__version||!0===c){i.activeTexture(33984+a),t.pixelStorei(37440,r.flipY),t.pixelStorei(37441,r.premultiplyAlpha),t.pixelStorei(3317,r.unpackAlignment),t.pixelStorei(37443,0);const e=function(t){return!o&&(t.wrapS!==h||t.wrapT!==h||t.minFilter!==d&&t.minFilter!==f)}(r)&&!1===B(r.image);let n=U(r.image,e,!1,C);n=st(r,n);const m=B(n)||o,g=s.convert(r.format,r.encoding);let v,x=s.convert(r.type),b=G(r.internalFormat,g,x,r.encoding,r.isVideoTexture);K(l,r,m);const E=r.mipmaps,L=o&&!0!==r.isVideoTexture,R=void 0===p.__version||!0===c,P=V(r,n,m);if(r.isDepthTexture)b=6402,o?b=r.type===M?36012:r.type===y?33190:r.type===S?35056:33189:r.type===M&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),r.format===T&&6402===b&&r.type!==_&&r.type!==y&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),r.type=y,x=s.convert(r.type)),r.format===A&&6402===b&&(b=34041,r.type!==S&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),r.type=S,x=s.convert(r.type))),R&&(L?i.texStorage2D(3553,1,b,n.width,n.height):i.texImage2D(3553,0,b,n.width,n.height,0,g,x,null));else if(r.isDataTexture)if(E.length>0&&m){L&&R&&i.texStorage2D(3553,P,b,E[0].width,E[0].height);for(let t=0,e=E.length;t>=1,e>>=1}}else if(E.length>0&&m){L&&R&&i.texStorage2D(3553,P,b,E[0].width,E[0].height);for(let t=0,e=E.length;t=34069&&l<=34074)&&t.framebufferTexture2D(36160,o,l,n.get(a).__webglTexture,0),i.bindFramebuffer(36160,null)}function et(e,i,n){if(t.bindRenderbuffer(36161,e),i.depthBuffer&&!i.stencilBuffer){let r=33189;if(n||rt(i)){const e=i.depthTexture;e&&e.isDepthTexture&&(e.type===M?r=36012:e.type===y&&(r=33190));const n=nt(i);rt(i)?R.renderbufferStorageMultisampleEXT(36161,n,r,i.width,i.height):t.renderbufferStorageMultisample(36161,n,r,i.width,i.height)}else t.renderbufferStorage(36161,r,i.width,i.height);t.framebufferRenderbuffer(36160,36096,36161,e)}else if(i.depthBuffer&&i.stencilBuffer){const r=nt(i);n&&!1===rt(i)?t.renderbufferStorageMultisample(36161,r,35056,i.width,i.height):rt(i)?R.renderbufferStorageMultisampleEXT(36161,r,35056,i.width,i.height):t.renderbufferStorage(36161,34041,i.width,i.height),t.framebufferRenderbuffer(36160,33306,36161,e)}else{const e=!0===i.isWebGLMultipleRenderTargets?i.texture:[i.texture];for(let r=0;r0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function st(t,i){const n=t.encoding,r=t.format,s=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||t.format===gt||n!==ct&&(n===ht?!1===o?!0===e.has("EXT_sRGB")&&r===w?(t.format=gt,t.minFilter=f,t.generateMipmaps=!1):i=Kt.sRGBToLinear(i):r===w&&s===x||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture encoding:",n)),i}this.allocateTextureUnit=function(){const t=X;return t>=l&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+l),X+=1,t},this.resetTextureUnits=function(){X=0},this.setTexture2D=Y,this.setTexture2DArray=function(t,e){const r=n.get(t);t.version>0&&r.__version!==t.version?Q(r,t,e):i.bindTexture(35866,r.__webglTexture,33984+e)},this.setTexture3D=function(t,e){const r=n.get(t);t.version>0&&r.__version!==t.version?Q(r,t,e):i.bindTexture(32879,r.__webglTexture,33984+e)},this.setTextureCube=function(e,r){const a=n.get(e);e.version>0&&a.__version!==e.version?function(e,r,a){if(6!==r.image.length)return;const l=$(e,r),c=r.source;i.bindTexture(34067,e.__webglTexture,33984+a);const h=n.get(c);if(c.version!==h.__version||!0===l){i.activeTexture(33984+a),t.pixelStorei(37440,r.flipY),t.pixelStorei(37441,r.premultiplyAlpha),t.pixelStorei(3317,r.unpackAlignment),t.pixelStorei(37443,0);const e=r.isCompressedTexture||r.image[0].isCompressedTexture,n=r.image[0]&&r.image[0].isDataTexture,u=[];for(let t=0;t<6;t++)u[t]=e||n?n?r.image[t].image:r.image[t]:U(r.image[t],!1,!0,E),u[t]=st(r,u[t]);const d=u[0],p=B(d)||o,m=s.convert(r.format,r.encoding),f=s.convert(r.type),g=G(r.internalFormat,m,f,r.encoding),v=o&&!0!==r.isVideoTexture,x=void 0===h.__version||!0===l;let _,y=V(r,d,p);if(K(34067,r,p),e){v&&x&&i.texStorage2D(34067,y,g,d.width,d.height);for(let t=0;t<6;t++){_=u[t].mipmaps;for(let e=0;e<_.length;e++){const n=_[e];r.format!==w?null!==m?v?i.compressedTexSubImage2D(34069+t,e,0,0,n.width,n.height,m,n.data):i.compressedTexImage2D(34069+t,e,g,n.width,n.height,0,n.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):v?i.texSubImage2D(34069+t,e,0,0,n.width,n.height,m,f,n.data):i.texImage2D(34069+t,e,g,n.width,n.height,0,m,f,n.data)}}}else{_=r.mipmaps,v&&x&&(_.length>0&&y++,i.texStorage2D(34067,y,g,u[0].width,u[0].height));for(let t=0;t<6;t++)if(n){v?i.texSubImage2D(34069+t,0,0,0,u[t].width,u[t].height,m,f,u[t].data):i.texImage2D(34069+t,0,g,u[t].width,u[t].height,0,m,f,u[t].data);for(let e=0;e<_.length;e++){const n=_[e].image[t].image;v?i.texSubImage2D(34069+t,e+1,0,0,n.width,n.height,m,f,n.data):i.texImage2D(34069+t,e+1,g,n.width,n.height,0,m,f,n.data)}}else{v?i.texSubImage2D(34069+t,0,0,0,m,f,u[t]):i.texImage2D(34069+t,0,g,m,f,u[t]);for(let e=0;e<_.length;e++){const n=_[e];v?i.texSubImage2D(34069+t,e+1,0,0,m,f,n.image[t]):i.texImage2D(34069+t,e+1,g,m,f,n.image[t])}}}F(r,p)&&k(34067),h.__version=c.version,r.onUpdate&&r.onUpdate(r)}e.__version=r.version}(a,e,r):i.bindTexture(34067,a.__webglTexture,33984+r)},this.rebindTextures=function(t,e,i){const r=n.get(t);void 0!==e&&tt(r.__webglFramebuffer,t,t.texture,36064,3553),void 0!==i&&it(t)},this.setupRenderTarget=function(e){const l=e.texture,c=n.get(e),h=n.get(l);e.addEventListener("dispose",j),!0!==e.isWebGLMultipleRenderTargets&&(void 0===h.__webglTexture&&(h.__webglTexture=t.createTexture()),h.__version=l.version,a.memory.textures++);const u=!0===e.isWebGLCubeRenderTarget,d=!0===e.isWebGLMultipleRenderTargets,p=B(e)||o;if(u){c.__webglFramebuffer=[];for(let e=0;e<6;e++)c.__webglFramebuffer[e]=t.createFramebuffer()}else{if(c.__webglFramebuffer=t.createFramebuffer(),d)if(r.drawBuffers){const i=e.texture;for(let e=0,r=i.length;e0&&!1===rt(e)){const n=d?l:[l];c.__webglMultisampledFramebuffer=t.createFramebuffer(),c.__webglColorRenderbuffer=[],i.bindFramebuffer(36160,c.__webglMultisampledFramebuffer);for(let i=0;i0&&!1===rt(e)){const r=e.isWebGLMultipleRenderTargets?e.texture:[e.texture],s=e.width,a=e.height;let o=16384;const l=[],c=e.stencilBuffer?33306:36096,h=n.get(e),u=!0===e.isWebGLMultipleRenderTargets;if(u)for(let e=0;eo+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,i),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(n=e.getPose(t.targetRaySpace,i),null===n&&null!==r&&(n=r),null!==n&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ws)))}return null!==a&&(a.visible=null!==n),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const i=new Hs;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}class qs extends ee{constructor(t,e,i,n,r,s,a,o,l,c){if((c=void 0!==c?c:T)!==T&&c!==A)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===i&&c===T&&(i=y),void 0===i&&c===A&&(i=S),super(null,n,r,s,a,o,c,i,l),this.isDepthTexture=!0,this.image={width:t,height:e},this.magFilter=void 0!==a?a:d,this.minFilter=void 0!==o?o:d,this.flipY=!1,this.generateMipmaps=!1}}class Xs extends vt{constructor(t,e){super();const i=this;let n=null,r=1,s=null,a="local-floor",o=null,l=null,c=null,h=null,u=null,d=null;const p=e.getContextAttributes();let m=null,f=null;const g=[],v=[],_=new Set,M=new Map,b=new an;b.layers.enable(1),b.viewport=new ie;const E=new an;E.layers.enable(2),E.viewport=new ie;const C=[b,E],L=new Vs;L.layers.enable(1),L.layers.enable(2);let R=null,P=null;function I(t){const e=v.indexOf(t.inputSource);if(-1===e)return;const i=g[e];void 0!==i&&i.dispatchEvent({type:t.type,data:t.inputSource})}function D(){n.removeEventListener("select",I),n.removeEventListener("selectstart",I),n.removeEventListener("selectend",I),n.removeEventListener("squeeze",I),n.removeEventListener("squeezestart",I),n.removeEventListener("squeezeend",I),n.removeEventListener("end",D),n.removeEventListener("inputsourceschange",N);for(let t=0;t=0&&(v[n]=null,g[n].disconnect(i))}for(let e=0;e=v.length){v.push(i),n=t;break}if(null===v[t]){v[t]=i,n=t;break}}if(-1===n)break}const r=g[n];r&&r.connect(i)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=g[t];return void 0===e&&(e=new js,g[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=g[t];return void 0===e&&(e=new js,g[t]=e),e.getGripSpace()},this.getHand=function(t){let e=g[t];return void 0===e&&(e=new js,g[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===i.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===i.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return o||s},this.setReferenceSpace=function(t){o=t},this.getBaseLayer=function(){return null!==h?h:u},this.getBinding=function(){return c},this.getFrame=function(){return d},this.getSession=function(){return n},this.setSession=async function(l){if(n=l,null!==n){if(m=t.getRenderTarget(),n.addEventListener("select",I),n.addEventListener("selectstart",I),n.addEventListener("selectend",I),n.addEventListener("squeeze",I),n.addEventListener("squeezestart",I),n.addEventListener("squeezeend",I),n.addEventListener("end",D),n.addEventListener("inputsourceschange",N),!0!==p.xrCompatible&&await e.makeXRCompatible(),void 0===n.renderState.layers||!1===t.capabilities.isWebGL2){const i={antialias:void 0!==n.renderState.layers||p.antialias,alpha:p.alpha,depth:p.depth,stencil:p.stencil,framebufferScaleFactor:r};u=new XRWebGLLayer(n,e,i),n.updateRenderState({baseLayer:u}),f=new ne(u.framebufferWidth,u.framebufferHeight,{format:w,type:x,encoding:t.outputEncoding,stencilBuffer:p.stencil})}else{let i=null,s=null,a=null;p.depth&&(a=p.stencil?35056:33190,i=p.stencil?A:T,s=p.stencil?S:y);const o={colorFormat:32856,depthFormat:a,scaleFactor:r};c=new XRWebGLBinding(n,e),h=c.createProjectionLayer(o),n.updateRenderState({layers:[h]}),f=new ne(h.textureWidth,h.textureHeight,{format:w,type:x,depthTexture:new qs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,i),stencilBuffer:p.stencil,encoding:t.outputEncoding,samples:p.antialias?4:0});t.properties.get(f).__ignoreDepthValues=h.ignoreDepthValues}f.isXRRenderTarget=!0,this.setFoveation(1),o=null,s=await n.requestReferenceSpace(a),F.setContext(n),F.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}};const O=new oe,z=new oe;function U(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===n)return;L.near=E.near=b.near=t.near,L.far=E.far=b.far=t.far,R===L.near&&P===L.far||(n.updateRenderState({depthNear:L.near,depthFar:L.far}),R=L.near,P=L.far);const e=t.parent,i=L.cameras;U(L,e);for(let t=0;te&&(M.set(t,t.lastChangedTime),i.dispatchEvent({type:"planechanged",data:t}))}else _.add(t),M.set(t,n.lastChangedTime),i.dispatchEvent({type:"planeadded",data:t})}d=null})),this.setAnimationLoop=function(t){B=t},this.dispose=function(){}}}function Ys(t,e){function i(i,n){i.opacity.value=n.opacity,n.color&&i.diffuse.value.copy(n.color),n.emissive&&i.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(i.map.value=n.map),n.alphaMap&&(i.alphaMap.value=n.alphaMap),n.bumpMap&&(i.bumpMap.value=n.bumpMap,i.bumpScale.value=n.bumpScale,1===n.side&&(i.bumpScale.value*=-1)),n.displacementMap&&(i.displacementMap.value=n.displacementMap,i.displacementScale.value=n.displacementScale,i.displacementBias.value=n.displacementBias),n.emissiveMap&&(i.emissiveMap.value=n.emissiveMap),n.normalMap&&(i.normalMap.value=n.normalMap,i.normalScale.value.copy(n.normalScale),1===n.side&&i.normalScale.value.negate()),n.specularMap&&(i.specularMap.value=n.specularMap),n.alphaTest>0&&(i.alphaTest.value=n.alphaTest);const r=e.get(n).envMap;if(r&&(i.envMap.value=r,i.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,i.reflectivity.value=n.reflectivity,i.ior.value=n.ior,i.refractionRatio.value=n.refractionRatio),n.lightMap){i.lightMap.value=n.lightMap;const e=!0!==t.physicallyCorrectLights?Math.PI:1;i.lightMapIntensity.value=n.lightMapIntensity*e}let s,a;n.aoMap&&(i.aoMap.value=n.aoMap,i.aoMapIntensity.value=n.aoMapIntensity),n.map?s=n.map:n.specularMap?s=n.specularMap:n.displacementMap?s=n.displacementMap:n.normalMap?s=n.normalMap:n.bumpMap?s=n.bumpMap:n.roughnessMap?s=n.roughnessMap:n.metalnessMap?s=n.metalnessMap:n.alphaMap?s=n.alphaMap:n.emissiveMap?s=n.emissiveMap:n.clearcoatMap?s=n.clearcoatMap:n.clearcoatNormalMap?s=n.clearcoatNormalMap:n.clearcoatRoughnessMap?s=n.clearcoatRoughnessMap:n.iridescenceMap?s=n.iridescenceMap:n.iridescenceThicknessMap?s=n.iridescenceThicknessMap:n.specularIntensityMap?s=n.specularIntensityMap:n.specularColorMap?s=n.specularColorMap:n.transmissionMap?s=n.transmissionMap:n.thicknessMap?s=n.thicknessMap:n.sheenColorMap?s=n.sheenColorMap:n.sheenRoughnessMap&&(s=n.sheenRoughnessMap),void 0!==s&&(s.isWebGLRenderTarget&&(s=s.texture),!0===s.matrixAutoUpdate&&s.updateMatrix(),i.uvTransform.value.copy(s.matrix)),n.aoMap?a=n.aoMap:n.lightMap&&(a=n.lightMap),void 0!==a&&(a.isWebGLRenderTarget&&(a=a.texture),!0===a.matrixAutoUpdate&&a.updateMatrix(),i.uv2Transform.value.copy(a.matrix))}return{refreshFogUniforms:function(e,i){i.color.getRGB(e.fogColor.value,en(t)),i.isFog?(e.fogNear.value=i.near,e.fogFar.value=i.far):i.isFogExp2&&(e.fogDensity.value=i.density)},refreshMaterialUniforms:function(t,n,r,s,a){n.isMeshBasicMaterial||n.isMeshLambertMaterial?i(t,n):n.isMeshToonMaterial?(i(t,n),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,n)):n.isMeshPhongMaterial?(i(t,n),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,n)):n.isMeshStandardMaterial?(i(t,n),function(t,i){t.roughness.value=i.roughness,t.metalness.value=i.metalness,i.roughnessMap&&(t.roughnessMap.value=i.roughnessMap);i.metalnessMap&&(t.metalnessMap.value=i.metalnessMap);const n=e.get(i).envMap;n&&(t.envMapIntensity.value=i.envMapIntensity)}(t,n),n.isMeshPhysicalMaterial&&function(t,e,i){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap),e.clearcoatNormalMap&&(t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),t.clearcoatNormalMap.value=e.clearcoatNormalMap,1===e.side&&t.clearcoatNormalScale.value.negate()));e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap);e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap)}(t,n,a)):n.isMeshMatcapMaterial?(i(t,n),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,n)):n.isMeshDepthMaterial?i(t,n):n.isMeshDistanceMaterial?(i(t,n),function(t,e){t.referencePosition.value.copy(e.referencePosition),t.nearDistance.value=e.nearDistance,t.farDistance.value=e.farDistance}(t,n)):n.isMeshNormalMaterial?i(t,n):n.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity}(t,n),n.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,n)):n.isPointsMaterial?function(t,e,i,n){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*i,t.scale.value=.5*n,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let r;e.map?r=e.map:e.alphaMap&&(r=e.alphaMap);void 0!==r&&(!0===r.matrixAutoUpdate&&r.updateMatrix(),t.uvTransform.value.copy(r.matrix))}(t,n,r,s):n.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map);e.alphaMap&&(t.alphaMap.value=e.alphaMap);e.alphaTest>0&&(t.alphaTest.value=e.alphaTest);let i;e.map?i=e.map:e.alphaMap&&(i=e.alphaMap);void 0!==i&&(!0===i.matrixAutoUpdate&&i.updateMatrix(),t.uvTransform.value.copy(i.matrix))}(t,n):n.isShadowMaterial?(t.color.value.copy(n.color),t.opacity.value=n.opacity):n.isShaderMaterial&&(n.uniformsNeedUpdate=!1)}}}function Zs(t,e,i,n){let r={},s={},a=[];const o=i.isWebGL2?t.getParameter(35375):0;function l(t,e,i){const n=t.value;if(void 0===i[e]){if("number"==typeof n)i[e]=n;else{const t=Array.isArray(n)?n:[n],r=[];for(let e=0;e0){r=i%n;0!==r&&n-r-a.boundary<0&&(i+=n-r,s.__offset=i)}i+=a.storage}r=i%n,r>0&&(i+=n-r);t.__size=i,t.__cache={}}(i),d=function(e){const i=function(){for(let t=0;t0&&function(t,e,i){const n=Z.isWebGL2;null===V&&(V=new ne(1,1,{generateMipmaps:!0,type:Y.has("EXT_color_buffer_half_float")?b:x,minFilter:v,samples:n&&!0===a?4:0}));g.getDrawingBufferSize(W),n?V.setSize(W.x,W.y):V.setSize(Ct(W.x),Ct(W.y));const r=g.getRenderTarget();g.setRenderTarget(V),g.clear();const s=g.toneMapping;g.toneMapping=0,Ot(t,e,i),g.toneMapping=s,Q.updateMultisampleRenderTarget(V),Q.updateRenderTargetMipmap(V),g.setRenderTarget(r)}(r,e,i),n&&J.viewport(C.copy(n)),r.length>0&&Ot(r,e,i),s.length>0&&Ot(s,e,i),o.length>0&&Ot(o,e,i),J.buffers.depth.setTest(!0),J.buffers.depth.setMask(!0),J.buffers.color.setMask(!0),J.setPolygonOffset(!1)}function Ot(t,e,i){const n=!0===e.isScene?e.overrideMaterial:null;for(let r=0,s=t.length;r0?f[f.length-1]:null,m.pop(),d=m.length>0?m[m.length-1]:null},this.getActiveCubeFace=function(){return y},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,i){$.get(t.texture).__webglTexture=e,$.get(t.depthTexture).__webglTexture=i;const n=$.get(t);n.__hasExternalTextures=!0,n.__hasExternalTextures&&(n.__autoAllocateDepthBuffer=void 0===i,n.__autoAllocateDepthBuffer||!0===Y.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),n.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(t,e){const i=$.get(t);i.__webglFramebuffer=e,i.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,i=0){T=t,y=e,S=i;let n=!0,r=null,s=!1,a=!1;if(t){const i=$.get(t);void 0!==i.__useDefaultFramebuffer?(J.bindFramebuffer(36160,null),n=!1):void 0===i.__webglFramebuffer?Q.setupRenderTarget(t):i.__hasExternalTextures&&Q.rebindTextures(t,$.get(t.texture).__webglTexture,$.get(t.depthTexture).__webglTexture);const o=t.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(a=!0);const l=$.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=l[e],s=!0):r=Z.isWebGL2&&t.samples>0&&!1===Q.useMultisampledRTT(t)?$.get(t).__webglMultisampledFramebuffer:l,C.copy(t.viewport),L.copy(t.scissor),R=t.scissorTest}else C.copy(z).multiplyScalar(D).floor(),L.copy(U).multiplyScalar(D).floor(),R=B;if(J.bindFramebuffer(36160,r)&&Z.drawBuffers&&n&&J.drawBuffers(t,r),J.viewport(C),J.scissor(L),J.setScissorTest(R),s){const n=$.get(t.texture);_t.framebufferTexture2D(36160,36064,34069+e,n.__webglTexture,i)}else if(a){const n=$.get(t.texture),r=e||0;_t.framebufferTextureLayer(36160,36064,n.__webglTexture,i||0,r)}A=-1},this.readRenderTargetPixels=function(t,e,i,n,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=$.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){J.bindFramebuffer(36160,o);try{const a=t.texture,o=a.format,l=a.type;if(o!==w&>.convert(o)!==_t.getParameter(35739))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const c=l===b&&(Y.has("EXT_color_buffer_half_float")||Z.isWebGL2&&Y.has("EXT_color_buffer_float"));if(!(l===x||gt.convert(l)===_t.getParameter(35738)||l===M&&(Z.isWebGL2||Y.has("OES_texture_float")||Y.has("WEBGL_color_buffer_float"))||c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");e>=0&&e<=t.width-n&&i>=0&&i<=t.height-r&&_t.readPixels(e,i,n,r,gt.convert(o),gt.convert(l),s)}finally{const t=null!==T?$.get(T).__webglFramebuffer:null;J.bindFramebuffer(36160,t)}}},this.copyFramebufferToTexture=function(t,e,i=0){const n=Math.pow(2,-i),r=Math.floor(e.image.width*n),s=Math.floor(e.image.height*n);Q.setTexture2D(e,0),_t.copyTexSubImage2D(3553,i,0,0,t.x,t.y,r,s),J.unbindTexture()},this.copyTextureToTexture=function(t,e,i,n=0){const r=e.image.width,s=e.image.height,a=gt.convert(i.format),o=gt.convert(i.type);Q.setTexture2D(i,0),_t.pixelStorei(37440,i.flipY),_t.pixelStorei(37441,i.premultiplyAlpha),_t.pixelStorei(3317,i.unpackAlignment),e.isDataTexture?_t.texSubImage2D(3553,n,t.x,t.y,r,s,a,o,e.image.data):e.isCompressedTexture?_t.compressedTexSubImage2D(3553,n,t.x,t.y,e.mipmaps[0].width,e.mipmaps[0].height,a,e.mipmaps[0].data):_t.texSubImage2D(3553,n,t.x,t.y,a,o,e.image),0===n&&i.generateMipmaps&&_t.generateMipmap(3553),J.unbindTexture()},this.copyTextureToTexture3D=function(t,e,i,n,r=0){if(g.isWebGL1Renderer)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");const s=t.max.x-t.min.x+1,a=t.max.y-t.min.y+1,o=t.max.z-t.min.z+1,l=gt.convert(n.format),c=gt.convert(n.type);let h;if(n.isData3DTexture)Q.setTexture3D(n,0),h=32879;else{if(!n.isDataArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");Q.setTexture2DArray(n,0),h=35866}_t.pixelStorei(37440,n.flipY),_t.pixelStorei(37441,n.premultiplyAlpha),_t.pixelStorei(3317,n.unpackAlignment);const u=_t.getParameter(3314),d=_t.getParameter(32878),p=_t.getParameter(3316),m=_t.getParameter(3315),f=_t.getParameter(32877),v=i.isCompressedTexture?i.mipmaps[0]:i.image;_t.pixelStorei(3314,v.width),_t.pixelStorei(32878,v.height),_t.pixelStorei(3316,t.min.x),_t.pixelStorei(3315,t.min.y),_t.pixelStorei(32877,t.min.z),i.isDataTexture||i.isData3DTexture?_t.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,v.data):i.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),_t.compressedTexSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,v.data)):_t.texSubImage3D(h,r,e.x,e.y,e.z,s,a,o,l,c,v),_t.pixelStorei(3314,u),_t.pixelStorei(32878,d),_t.pixelStorei(3316,p),_t.pixelStorei(3315,m),_t.pixelStorei(32877,f),0===r&&n.generateMipmaps&&_t.generateMipmap(h),J.unbindTexture()},this.initTexture=function(t){t.isCubeTexture?Q.setTextureCube(t,0):t.isData3DTexture?Q.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?Q.setTexture2DArray(t,0):Q.setTexture2D(t,0),J.unbindTexture()},this.resetState=function(){y=0,S=0,T=null,J.reset(),vt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}class Ks extends Js{}Ks.prototype.isWebGL1Renderer=!0;class $s{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new Zt(t),this.density=e}clone(){return new $s(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}}class Qs{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new Zt(t),this.near=e,this.far=i}clone(){return new Qs(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}class ta extends li{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e}get autoUpdate(){return console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."),this.matrixWorldAutoUpdate}set autoUpdate(t){console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."),this.matrixWorldAutoUpdate=t}}class ea{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=mt,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=bt()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let n=0,r=this.stride;nt.far||e.push({distance:o,point:aa.clone(),uv:_i.getUV(aa,da,pa,ma,fa,ga,va,new It),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function _a(t,e,i,n,r,s){ca.subVectors(t,i).addScalar(.5).multiply(n),void 0!==r?(ha.x=s*ca.x-r*ca.y,ha.y=r*ca.x+s*ca.y):ha.copy(ca),t.copy(e),t.x+=ha.x,t.y+=ha.y,t.applyMatrix4(ua)}const ya=new oe,Ma=new oe;class ba extends li{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,i=e.length;t0){let i,n;for(i=1,n=e.length;i0){ya.setFromMatrixPosition(this.matrixWorld);const i=t.ray.origin.distanceTo(ya);this.getObjectForDistance(i).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){ya.setFromMatrixPosition(t.matrixWorld),Ma.setFromMatrixPosition(this.matrixWorld);const i=ya.distanceTo(Ma)/t.zoom;let n,r;for(e[0].object.visible=!0,n=1,r=e.length;n=t))break;e[n-1].object.visible=!1,e[n].object.visible=!0}for(this._currentLevel=n-1;no)continue;u.applyMatrix4(this.matrixWorld);const s=t.ray.origin.distanceTo(u);st.far||e.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}else{for(let i=Math.max(0,s.start),n=Math.min(m.count,s.start+s.count)-1;io)continue;u.applyMatrix4(this.matrixWorld);const n=t.ray.origin.distanceTo(u);nt.far||e.push({distance:n,point:h.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;t0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;tr.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:i,index:e,face:null,object:a})}}class so extends ee{constructor(t,e,i,n,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,n,r,h,u),this.isCompressedTexture=!0,this.image={width:e,height:i},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class ao{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const i=this.getUtoTmapping(t);return this.getPoint(i,e)}getPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return e}getSpacedPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPointAt(i/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let i,n=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)i=this.getPoint(s/t),r+=i.distanceTo(n),e.push(r),n=i;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const i=this.getLengths();let n=0;const r=i.length;let s;s=e||t*i[r-1];let a,o=0,l=r-1;for(;o<=l;)if(n=Math.floor(o+(l-o)/2),a=i[n]-s,a<0)o=n+1;else{if(!(a>0)){l=n;break}l=n-1}if(n=l,i[n]===s)return n/(r-1);const c=i[n];return(n+(s-c)/(i[n+1]-c))/(r-1)}getTangent(t,e){const i=1e-4;let n=t-i,r=t+i;n<0&&(n=0),r>1&&(r=1);const s=this.getPoint(n),a=this.getPoint(r),o=e||(s.isVector2?new It:new oe);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e){const i=new oe,n=[],r=[],s=[],a=new oe,o=new Ue;for(let e=0;e<=t;e++){const i=e/t;n[e]=this.getTangentAt(i,new oe)}r[0]=new oe,s[0]=new oe;let l=Number.MAX_VALUE;const c=Math.abs(n[0].x),h=Math.abs(n[0].y),u=Math.abs(n[0].z);c<=l&&(l=c,i.set(1,0,0)),h<=l&&(l=h,i.set(0,1,0)),u<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),r[0].crossVectors(n[0],a),s[0].crossVectors(n[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(n[e-1],n[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(St(n[e-1].dot(n[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(n[e],r[e])}if(!0===e){let e=Math.acos(St(r[0].dot(r[t]),-1,1));e/=t,n[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let i=1;i<=t;i++)r[i].applyMatrix4(o.makeRotationAxis(n[i],e*i)),s[i].crossVectors(n[i],r[i])}return{tangents:n,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class oo extends ao{constructor(t=0,e=0,i=1,n=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e){const i=e||new It,n=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)n;)r-=n;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=n[(l-1)%r]:(ho.subVectors(n[0],n[1]).add(n[0]),a=ho);const h=n[l%r],u=n[(l+1)%r];if(this.closed||l+2n.length-2?n.length-1:s+1],h=n[s>n.length-3?n.length-1:s+2];return i.set(go(a,o.x,l.x,c.x,h.x),go(a,o.y,l.y,c.y,h.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e=i){const t=n[r]-i,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,n=this.curves.length;i1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class Lo extends zi{constructor(t=[new It(0,-.5),new It(.5,0),new It(0,.5)],e=12,i=0,n=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:i,phiLength:n},e=Math.floor(e),n=St(n,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new oe,u=new It,d=new oe,p=new oe,m=new oe;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=i+r*c*n,p=Math.sin(d),m=Math.cos(d);for(let i=0;i<=t.length-1;i++){h.x=t[i].x*p,h.y=t[i].y,h.z=t[i].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=i/(t.length-1),a.push(u.x,u.y);const n=o[3*i+0]*p,c=o[3*i+1],d=o[3*i+0]*m;l.push(n,c,d)}}for(let i=0;i0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new Ci(h,3)),this.setAttribute("normal",new Ci(u,3)),this.setAttribute("uv",new Ci(d,2))}static fromJSON(t){return new Io(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Do extends Io{constructor(t=1,e=1,i=32,n=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,i,n,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:n,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new Do(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class No extends zi{constructor(t=[],e=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:i,detail:n};const r=[],s=[];function a(t,e,i,n){const r=n+1,s=[];for(let n=0;n<=r;n++){s[n]=[];const a=t.clone().lerp(i,n/r),o=e.clone().lerp(i,n/r),l=r-n;for(let t=0;t<=l;t++)s[n][t]=0===t&&n===r?a:a.clone().lerp(o,t/l)}for(let t=0;t.9&&a<.1&&(e<.2&&(s[t+0]+=1),i<.2&&(s[t+2]+=1),n<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new Ci(r,3)),this.setAttribute("normal",new Ci(r.slice(),3)),this.setAttribute("uv",new Ci(s,2)),0===n?this.computeVertexNormals():this.normalizeNormals()}static fromJSON(t){return new No(t.vertices,t.indices,t.radius,t.details)}}class Oo extends No{constructor(t=1,e=0){const i=(1+Math.sqrt(5))/2,n=1/i;super([-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,-n,-i,0,-n,i,0,n,-i,0,n,i,-n,-i,0,-n,i,0,n,-i,0,n,i,0,-i,0,-n,i,0,-n,-i,0,n,i,0,n],[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],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new Oo(t.radius,t.detail)}}const zo=new oe,Uo=new oe,Bo=new oe,Fo=new _i;class ko extends zi{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const i=4,n=Math.pow(10,i),r=Math.cos(yt*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t80*i){o=c=t[0],l=h=t[1];for(let e=i;ec&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return jo(s,a,i,o,l,p,0),a};function Ho(t,e,i,n,r){let s,a;if(r===function(t,e,i,n){let r=0;for(let s=e,a=i-n;s0)for(s=e;s=e;s-=n)a=hl(s,t[s],t[s+1],a);return a&&rl(a,a.next)&&(ul(a),a=a.next),a}function Wo(t,e){if(!t)return t;e||(e=t);let i,n=t;do{if(i=!1,n.steiner||!rl(n,n.next)&&0!==nl(n.prev,n,n.next))n=n.next;else{if(ul(n),n=e=n.prev,n===n.next)break;i=!0}}while(i||n!==e);return e}function jo(t,e,i,n,r,s,a){if(!t)return;!a&&s&&function(t,e,i,n){let r=t;do{0===r.z&&(r.z=Qo(r.x,r.y,e,i,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,i,n,r,s,a,o,l,c=1;do{for(i=t,t=null,s=null,a=0;i;){for(a++,n=i,o=0,e=0;e0||l>0&&n;)0!==o&&(0===l||!n||i.z<=n.z)?(r=i,i=i.nextZ,o--):(r=n,n=n.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;i=n}s.nextZ=null,c*=2}while(a>1)}(r)}(t,n,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?Xo(t,n,r,s):qo(t))e.push(o.i/i|0),e.push(t.i/i|0),e.push(l.i/i|0),ul(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?jo(t=Yo(Wo(t),e,i),e,i,n,r,s,2):2===a&&Zo(t,e,i,n,r,s):jo(Wo(t),e,i,n,r,s,1);break}}function qo(t){const e=t.prev,i=t,n=t.next;if(nl(e,i,n)>=0)return!1;const r=e.x,s=i.x,a=n.x,o=e.y,l=i.y,c=n.y,h=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=n.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&el(r,o,s,l,a,c,m.x,m.y)&&nl(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Xo(t,e,i,n){const r=t.prev,s=t,a=t.next;if(nl(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,u=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,v=Qo(p,m,e,i,n),x=Qo(f,g,e,i,n);let _=t.prevZ,y=t.nextZ;for(;_&&_.z>=v&&y&&y.z<=x;){if(_.x>=p&&_.x<=f&&_.y>=m&&_.y<=g&&_!==r&&_!==a&&el(o,h,l,u,c,d,_.x,_.y)&&nl(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&el(o,h,l,u,c,d,y.x,y.y)&&nl(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;_&&_.z>=v;){if(_.x>=p&&_.x<=f&&_.y>=m&&_.y<=g&&_!==r&&_!==a&&el(o,h,l,u,c,d,_.x,_.y)&&nl(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;y&&y.z<=x;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&el(o,h,l,u,c,d,y.x,y.y)&&nl(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Yo(t,e,i){let n=t;do{const r=n.prev,s=n.next.next;!rl(r,s)&&sl(r,n,n.next,s)&&ll(r,s)&&ll(s,r)&&(e.push(r.i/i|0),e.push(n.i/i|0),e.push(s.i/i|0),ul(n),ul(n.next),n=t=s),n=n.next}while(n!==t);return Wo(n)}function Zo(t,e,i,n,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&il(a,t)){let o=cl(a,t);return a=Wo(a,a.next),o=Wo(o,o.next),jo(a,e,i,n,r,s,0),void jo(o,e,i,n,r,s,0)}t=t.next}a=a.next}while(a!==t)}function Jo(t,e){return t.x-e.x}function Ko(t,e){const i=function(t,e){let i,n=e,r=-1/0;const s=t.x,a=t.y;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){const t=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(t<=s&&t>r&&(r=t,i=n.x=n.x&&n.x>=l&&s!==n.x&&el(ai.x||n.x===i.x&&$o(i,n)))&&(i=n,u=h)),n=n.next}while(n!==o);return i}(t,e);if(!i)return e;const n=cl(i,t);return Wo(n,n.next),Wo(i,i.next)}function $o(t,e){return nl(t.prev,t,e.prev)<0&&nl(e.next,t,t.next)<0}function Qo(t,e,i,n,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function tl(t){let e=t,i=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(i-a)*(e-o)&&(i-a)*(s-o)>=(r-a)*(n-o)}function il(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&sl(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(ll(t,e)&&ll(e,t)&&function(t,e){let i=t,n=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{i.y>s!=i.next.y>s&&i.next.y!==i.y&&r<(i.next.x-i.x)*(s-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)&&(nl(t.prev,t,e.prev)||nl(t,e.prev,e))||rl(t,e)&&nl(t.prev,t,t.next)>0&&nl(e.prev,e,e.next)>0)}function nl(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function rl(t,e){return t.x===e.x&&t.y===e.y}function sl(t,e,i,n){const r=ol(nl(t,e,i)),s=ol(nl(t,e,n)),a=ol(nl(i,n,t)),o=ol(nl(i,n,e));return r!==s&&a!==o||(!(0!==r||!al(t,i,e))||(!(0!==s||!al(t,n,e))||(!(0!==a||!al(i,t,n))||!(0!==o||!al(i,e,n)))))}function al(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function ol(t){return t>0?1:t<0?-1:0}function ll(t,e){return nl(t.prev,t,t.next)<0?nl(t,e,t.next)>=0&&nl(t,t.prev,e)>=0:nl(t,e,t.prev)<0||nl(t,t.next,e)<0}function cl(t,e){const i=new dl(t.i,t.x,t.y),n=new dl(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,n.next=i,i.prev=n,s.next=n,n.prev=s,n}function hl(t,e,i,n){const r=new dl(t,e,i);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function ul(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function dl(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class pl{static area(t){const e=t.length;let i=0;for(let n=e-1,r=0;r2&&t[e-1].equals(t[0])&&t.pop()}function fl(t,e){for(let i=0;iNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((i.x-c/d-p)*c-(i.y+l/d-m)*l)/(a*c-o*l);n=p+a*f-t.x,r=m+o*f-t.y;const g=n*n+r*r;if(g<=2)return new It(n,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(n=-o,r=a,s=Math.sqrt(h)):(n=a,r=o,s=Math.sqrt(h/2))}return new It(n/s,r/s)}const P=[];for(let t=0,e=A.length,i=e-1,n=t+1;t=0;t--){const e=t/p,i=h*Math.cos(e*Math.PI/2),n=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=A.length;t=0;){const n=i;let r=i-1;r<0&&(r=t.length-1);for(let t=0,i=o+2*p;t0)&&d.push(e,r,l),(t!==i-1||o0!=t>0&&this.version++,this._sheen=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class Nl extends Mi{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Zt(16777215),this.specular=new Zt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Zt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class Ol extends Mi{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Zt(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Zt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class zl extends Mi{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class Ul extends Mi{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Zt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Zt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class Bl extends Mi{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Zt(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this.fog=t.fog,this}}class Fl extends Ga{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function kl(t,e,i){return Vl(t)?new t.constructor(t.subarray(e,void 0!==i?i:t.length)):t.slice(e,i)}function Gl(t,e,i){return!t||!i&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)}function Vl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Hl(t){const e=t.length,i=new Array(e);for(let t=0;t!==e;++t)i[t]=t;return i.sort((function(e,i){return t[e]-t[i]})),i}function Wl(t,e,i){const n=t.length,r=new t.constructor(n);for(let s=0,a=0;a!==n;++s){const n=i[s]*e;for(let i=0;i!==e;++i)r[a++]=t[n+i]}return r}function jl(t,e,i,n){let r=1,s=t[0];for(;void 0!==s&&void 0===s[n];)s=t[r++];if(void 0===s)return;let a=s[n];if(void 0!==a)if(Array.isArray(a))do{a=s[n],void 0!==a&&(e.push(s.time),i.push.apply(i,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[n],void 0!==a&&(e.push(s.time),a.toArray(i,i.length)),s=t[r++]}while(void 0!==s);else do{a=s[n],void 0!==a&&(e.push(s.time),i.push(a)),s=t[r++]}while(void 0!==s)}var ql=Object.freeze({__proto__:null,arraySlice:kl,convertArray:Gl,flattenJSON:jl,getKeyframeOrder:Hl,isTypedArray:Vl,makeClipAdditive:function(t,e=0,i=t,n=30){n<=0&&(n=30);const r=i.tracks.length,s=e/n;for(let e=0;e=n.times[u]){const t=u*l+o,e=t+l-o;d=kl(n.values,t,e)}else{const t=n.createInterpolant(),e=o,i=l-o;t.evaluate(s),d=kl(t.resultBuffer,e,i)}if("quaternion"===r){(new ae).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let t=0;t=n)){l.push(e.times[t]);for(let i=0;is.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t=r)break t;{const a=e[1];t=r)break e}s=i,i=0}}for(;i>>1;te;)--s;if(++s,0!==r||s!==n){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=kl(i,r,s),this.values=kl(this.values,r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,n=this.values,r=i.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const n=i[e];if("number"==typeof n&&isNaN(n)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,n),t=!1;break}if(null!==s&&s>n){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,n,s),t=!1;break}s=n}if(void 0!==n&&Vl(n))for(let e=0,i=n.length;e!==i;++e){const i=n[e];if(isNaN(i)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,i),t=!1;break}}return t}optimize(){const t=kl(this.times),e=kl(this.values),i=this.getValueSize(),n=this.getInterpolation()===nt,r=t.length-1;let s=1;for(let a=1;a0){t[s]=t[r];for(let t=r*i,n=s*i,a=0;a!==i;++a)e[n+a]=e[t+a];++s}return s!==t.length?(this.times=kl(t,0,s),this.values=kl(e,0,s*i)):(this.times=t,this.values=e),this}clone(){const t=kl(this.times,0),e=kl(this.values,0),i=new(0,this.constructor)(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}}Kl.prototype.TimeBufferType=Float32Array,Kl.prototype.ValueBufferType=Float32Array,Kl.prototype.DefaultInterpolation=it;class $l extends Kl{}$l.prototype.ValueTypeName="bool",$l.prototype.ValueBufferType=Array,$l.prototype.DefaultInterpolation=et,$l.prototype.InterpolantFactoryMethodLinear=void 0,$l.prototype.InterpolantFactoryMethodSmooth=void 0;class Ql extends Kl{}Ql.prototype.ValueTypeName="color";class tc extends Kl{}tc.prototype.ValueTypeName="number";class ec extends Xl{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t,e,i,n){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(i-e)/(n-e);let l=t*a;for(let t=l+a;l!==t;l+=4)ae.slerpFlat(r,0,s,l-a,s,l,o);return r}}class ic extends Kl{InterpolantFactoryMethodLinear(t){return new ec(this.times,this.values,this.getValueSize(),t)}}ic.prototype.ValueTypeName="quaternion",ic.prototype.DefaultInterpolation=it,ic.prototype.InterpolantFactoryMethodSmooth=void 0;class nc extends Kl{}nc.prototype.ValueTypeName="string",nc.prototype.ValueBufferType=Array,nc.prototype.DefaultInterpolation=et,nc.prototype.InterpolantFactoryMethodLinear=void 0,nc.prototype.InterpolantFactoryMethodSmooth=void 0;class rc extends Kl{}rc.prototype.ValueTypeName="vector";class sc{constructor(t,e=-1,i,n=2500){this.name=t,this.tracks=i,this.duration=e,this.blendMode=n,this.uuid=bt(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],i=t.tracks,n=1/(t.fps||1);for(let t=0,r=i.length;t!==r;++t)e.push(ac(i[t]).scale(n));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],i=t.tracks,n={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,n=i.length;t!==n;++t)e.push(Kl.toJSON(i[t]));return n}static CreateFromMorphTargetSequence(t,e,i,n){const r=e.length,s=[];for(let t=0;t1){const t=s[1];let e=n[t];e||(n[t]=e=[]),e.push(i)}}const s=[];for(const t in n)s.push(this.CreateFromMorphTargetSequence(t,n[t],e,i));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(t,e,i,n,r){if(0!==i.length){const s=[],a=[];jl(i,s,a,n),0!==s.length&&r.push(new t(e,s,a))}},n=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==uc[t])return void uc[t].push({onLoad:e,onProgress:i,onError:n});uc[t]=[],uc[t].push({onLoad:e,onProgress:i,onError:n});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const i=uc[t],n=e.body.getReader(),r=e.headers.get("Content-Length")||e.headers.get("X-File-Size"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){n.read().then((({done:n,value:r})=>{if(n)t.close();else{o+=r.byteLength;const n=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=i.length;t{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),i=e&&e[1]?e[1].toLowerCase():void 0,n=new TextDecoder(i);return t.arrayBuffer().then((t=>n.decode(t)))}}})).then((e=>{oc.add(t,e);const i=uc[t];delete uc[t];for(let t=0,n=i.length;t{const i=uc[t];if(void 0===i)throw this.manager.itemError(t),e;delete uc[t];for(let t=0,n=i.length;t{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class mc extends hc{constructor(t){super(t)}load(t,e,i,n){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=oc.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=Bt("img");function o(){c(),oc.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),n&&n(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class fc extends li{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new Zt(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(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),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}class gc extends fc{constructor(t,e,i){super(t,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(li.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Zt(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}}const vc=new Ue,xc=new oe,_c=new oe;class yc{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new It(512,512),this.map=null,this.mapPass=null,this.matrix=new Ue,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new vn,this._frameExtents=new It(1,1),this._viewportCount=1,this._viewports=[new ie(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,i=this.matrix;xc.setFromMatrixPosition(t.matrixWorld),e.position.copy(xc),_c.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(_c),e.updateMatrixWorld(),vc.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(vc),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(vc)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Mc extends yc{constructor(){super(new an(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(t){const e=this.camera,i=2*Mt*t.angle*this.focus,n=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;i===e.fov&&n===e.aspect&&r===e.far||(e.fov=i,e.aspect=n,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class bc extends fc{constructor(t,e,i=0,n=Math.PI/3,r=0,s=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(li.DEFAULT_UP),this.updateMatrix(),this.target=new li,this.distance=i,this.angle=n,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Mc}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),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}}const Sc=new Ue,wc=new oe,Tc=new oe;class Ac extends yc{constructor(){super(new an(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new It(4,2),this._viewportCount=6,this._viewports=[new ie(2,1,1,1),new ie(0,1,1,1),new ie(3,1,1,1),new ie(1,1,1,1),new ie(3,0,1,1),new ie(1,0,1,1)],this._cubeDirections=[new oe(1,0,0),new oe(-1,0,0),new oe(0,0,1),new oe(0,0,-1),new oe(0,1,0),new oe(0,-1,0)],this._cubeUps=[new oe(0,1,0),new oe(0,1,0),new oe(0,1,0),new oe(0,1,0),new oe(0,0,1),new oe(0,0,-1)]}updateMatrices(t,e=0){const i=this.camera,n=this.matrix,r=t.distance||i.far;r!==i.far&&(i.far=r,i.updateProjectionMatrix()),wc.setFromMatrixPosition(t.matrixWorld),i.position.copy(wc),Tc.copy(i.position),Tc.add(this._cubeDirections[e]),i.up.copy(this._cubeUps[e]),i.lookAt(Tc),i.updateMatrixWorld(),n.makeTranslation(-wc.x,-wc.y,-wc.z),Sc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Sc)}}class Ec extends fc{constructor(t,e,i=0,n=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new Ac}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}class Cc extends yc{constructor(){super(new Pn(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Lc extends fc{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(li.DEFAULT_UP),this.updateMatrix(),this.target=new li,this.shadow=new Cc}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class Rc extends fc{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}class Pc extends fc{constructor(t,e,i=10,n=10){super(t,e),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=n}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}class Ic{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new oe)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const i=t.x,n=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*n),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*i),e.addScaledVector(s[4],i*n*1.092548),e.addScaledVector(s[5],n*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],i*r*1.092548),e.addScaledVector(s[8],.546274*(i*i-n*n)),e}getIrradianceAt(t,e){const i=t.x,n=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*n),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*i),e.addScaledVector(s[4],.858086*i*n),e.addScaledVector(s[5],.858086*n*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*i*r),e.addScaledVector(s[8],.429043*(i*i-n*n)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(t.coefficients[i],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let i=0;i<9;i++)this.coefficients[i].lerp(t.coefficients[i],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].fromArray(t,e+3*n);return this}toArray(t=[],e=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(t,e+3*n);return t}static getBasisAt(t,e){const i=t.x,n=t.y,r=t.z;e[0]=.282095,e[1]=.488603*n,e[2]=.488603*r,e[3]=.488603*i,e[4]=1.092548*i*n,e[5]=1.092548*n*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*i*r,e[8]=.546274*(i*i-n*n)}}class Dc extends fc{constructor(t=new Ic,e=1){super(void 0,e),this.isLightProbe=!0,this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}class Nc extends hc{constructor(t){super(t),this.textures={}}load(t,e,i,n){const r=this,s=new pc(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(i){try{e(r.parse(JSON.parse(i)))}catch(e){n?n(e):console.error(e),r.manager.itemError(t)}}),i,n)}parse(t){const e=this.textures;function i(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const n=Nc.createMaterialFromType(t.type);if(void 0!==t.uuid&&(n.uuid=t.uuid),void 0!==t.name&&(n.name=t.name),void 0!==t.color&&void 0!==n.color&&n.color.setHex(t.color),void 0!==t.roughness&&(n.roughness=t.roughness),void 0!==t.metalness&&(n.metalness=t.metalness),void 0!==t.sheen&&(n.sheen=t.sheen),void 0!==t.sheenColor&&(n.sheenColor=(new Zt).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(n.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==n.emissive&&n.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==n.specular&&n.specular.setHex(t.specular),void 0!==t.specularIntensity&&(n.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==n.specularColor&&n.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(n.shininess=t.shininess),void 0!==t.clearcoat&&(n.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(n.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.iridescence&&(n.iridescence=t.iridescence),void 0!==t.iridescenceIOR&&(n.iridescenceIOR=t.iridescenceIOR),void 0!==t.iridescenceThicknessRange&&(n.iridescenceThicknessRange=t.iridescenceThicknessRange),void 0!==t.transmission&&(n.transmission=t.transmission),void 0!==t.thickness&&(n.thickness=t.thickness),void 0!==t.attenuationDistance&&(n.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==n.attenuationColor&&n.attenuationColor.setHex(t.attenuationColor),void 0!==t.fog&&(n.fog=t.fog),void 0!==t.flatShading&&(n.flatShading=t.flatShading),void 0!==t.blending&&(n.blending=t.blending),void 0!==t.combine&&(n.combine=t.combine),void 0!==t.side&&(n.side=t.side),void 0!==t.shadowSide&&(n.shadowSide=t.shadowSide),void 0!==t.opacity&&(n.opacity=t.opacity),void 0!==t.transparent&&(n.transparent=t.transparent),void 0!==t.alphaTest&&(n.alphaTest=t.alphaTest),void 0!==t.depthTest&&(n.depthTest=t.depthTest),void 0!==t.depthWrite&&(n.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(n.colorWrite=t.colorWrite),void 0!==t.stencilWrite&&(n.stencilWrite=t.stencilWrite),void 0!==t.stencilWriteMask&&(n.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(n.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(n.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(n.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(n.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(n.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(n.stencilZPass=t.stencilZPass),void 0!==t.wireframe&&(n.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(n.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(n.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(n.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(n.rotation=t.rotation),1!==t.linewidth&&(n.linewidth=t.linewidth),void 0!==t.dashSize&&(n.dashSize=t.dashSize),void 0!==t.gapSize&&(n.gapSize=t.gapSize),void 0!==t.scale&&(n.scale=t.scale),void 0!==t.polygonOffset&&(n.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(n.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(n.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(n.dithering=t.dithering),void 0!==t.alphaToCoverage&&(n.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(n.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.visible&&(n.visible=t.visible),void 0!==t.toneMapped&&(n.toneMapped=t.toneMapped),void 0!==t.userData&&(n.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?n.vertexColors=t.vertexColors>0:n.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(n.uniforms[e]={},r.type){case"t":n.uniforms[e].value=i(r.value);break;case"c":n.uniforms[e].value=(new Zt).setHex(r.value);break;case"v2":n.uniforms[e].value=(new It).fromArray(r.value);break;case"v3":n.uniforms[e].value=(new oe).fromArray(r.value);break;case"v4":n.uniforms[e].value=(new ie).fromArray(r.value);break;case"m3":n.uniforms[e].value=(new Dt).fromArray(r.value);break;case"m4":n.uniforms[e].value=(new Ue).fromArray(r.value);break;default:n.uniforms[e].value=r.value}}if(void 0!==t.defines&&(n.defines=t.defines),void 0!==t.vertexShader&&(n.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(n.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(n.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)n.extensions[e]=t.extensions[e];if(void 0!==t.size&&(n.size=t.size),void 0!==t.sizeAttenuation&&(n.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(n.map=i(t.map)),void 0!==t.matcap&&(n.matcap=i(t.matcap)),void 0!==t.alphaMap&&(n.alphaMap=i(t.alphaMap)),void 0!==t.bumpMap&&(n.bumpMap=i(t.bumpMap)),void 0!==t.bumpScale&&(n.bumpScale=t.bumpScale),void 0!==t.normalMap&&(n.normalMap=i(t.normalMap)),void 0!==t.normalMapType&&(n.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),n.normalScale=(new It).fromArray(e)}return void 0!==t.displacementMap&&(n.displacementMap=i(t.displacementMap)),void 0!==t.displacementScale&&(n.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(n.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(n.roughnessMap=i(t.roughnessMap)),void 0!==t.metalnessMap&&(n.metalnessMap=i(t.metalnessMap)),void 0!==t.emissiveMap&&(n.emissiveMap=i(t.emissiveMap)),void 0!==t.emissiveIntensity&&(n.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(n.specularMap=i(t.specularMap)),void 0!==t.specularIntensityMap&&(n.specularIntensityMap=i(t.specularIntensityMap)),void 0!==t.specularColorMap&&(n.specularColorMap=i(t.specularColorMap)),void 0!==t.envMap&&(n.envMap=i(t.envMap)),void 0!==t.envMapIntensity&&(n.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(n.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(n.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(n.lightMap=i(t.lightMap)),void 0!==t.lightMapIntensity&&(n.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(n.aoMap=i(t.aoMap)),void 0!==t.aoMapIntensity&&(n.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(n.gradientMap=i(t.gradientMap)),void 0!==t.clearcoatMap&&(n.clearcoatMap=i(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(n.clearcoatRoughnessMap=i(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(n.clearcoatNormalMap=i(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(n.clearcoatNormalScale=(new It).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(n.iridescenceMap=i(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(n.iridescenceThicknessMap=i(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(n.transmissionMap=i(t.transmissionMap)),void 0!==t.thicknessMap&&(n.thicknessMap=i(t.thicknessMap)),void 0!==t.sheenColorMap&&(n.sheenColorMap=i(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(n.sheenRoughnessMap=i(t.sheenRoughnessMap)),n}setTextures(t){return this.textures=t,this}static createMaterialFromType(t){return new{ShadowMaterial:Rl,SpriteMaterial:ra,RawShaderMaterial:Pl,ShaderMaterial:rn,PointsMaterial:$a,MeshPhysicalMaterial:Dl,MeshStandardMaterial:Il,MeshPhongMaterial:Nl,MeshToonMaterial:Ol,MeshNormalMaterial:zl,MeshLambertMaterial:Ul,MeshDepthMaterial:zs,MeshDistanceMaterial:Us,MeshBasicMaterial:bi,MeshMatcapMaterial:Bl,LineDashedMaterial:Fl,LineBasicMaterial:Ga,Material:Mi}[t]}}class Oc{static decodeText(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let i=0,n=t.length;i0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(i,n,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(i[t]!==i[t+e]){a.setValue(i,n);break}}saveOriginalState(){const t=this.binding,e=this.buffer,i=this.valueSize,n=i*this._origIndex;t.getValue(e,n);for(let t=i,r=n;t!==r;++t)e[t]=e[n+t%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let i=t;i=.5)for(let n=0;n!==r;++n)t[e+n]=t[i+n]}_slerp(t,e,i,n){ae.slerpFlat(t,e,t,e,t,i,n)}_slerpAdditive(t,e,i,n,r){const s=this._workIndex*r;ae.multiplyQuaternionsFlat(t,s,t,e,t,i),ae.slerpFlat(t,e,t,e,t,s,n)}_lerp(t,e,i,n,r){const s=1-n;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[i+a]*n}}_lerpAdditive(t,e,i,n,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[i+s]*n}}}const rh="\\[\\]\\.:\\/",sh=new RegExp("["+rh+"]","g"),ah="[^"+rh+"]",oh="[^"+rh.replace("\\.","")+"]",lh=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",ah)+/(WCOD+)?/.source.replace("WCOD",oh)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ah)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ah)+"$"),ch=["material","materials","bones","map"];class hh{constructor(t,e,i){this.path=e,this.parsedPath=i||hh.parseTrackName(e),this.node=hh.findNode(t,this.parsedPath.nodeName)||t,this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,i){return t&&t.isAnimationObjectGroup?new hh.Composite(t,e,i):new hh(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(sh,"")}static parseTrackName(t){const e=lh.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const i={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(void 0!==n&&-1!==n){const t=i.nodeName.substring(n+1);-1!==ch.indexOf(t)&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=t)}if(null===i.propertyName||0===i.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const i=t.skeleton.getBoneByName(e);if(void 0!==i)return i}if(t.children){const i=function(t){for(let n=0;n0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===lt)for(let i=0,n=t.length;i!==n;++i)t[i].evaluate(s),e[i].accumulateAdditive(a);else for(let i=0,r=t.length;i!==r;++i)t[i].evaluate(s),e[i].accumulate(n,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const i=this._weightInterpolant;if(null!==i){const n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const i=this._timeScaleInterpolant;if(null!==i){e*=i.evaluate(t)[0],t>i.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,i=this.loop;let n=this.time+t,r=this._loopCount;const s=2202===i;if(0===t)return-1===r?n:s&&1==(1&r)?e-n:n;if(2200===i){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(n>=e)n=e;else{if(!(n<0)){this.time=n;break t}n=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),n>=e||n<0){const i=Math.floor(n/e);n-=e*i,r+=Math.abs(i);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=t>0?e:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:i})}}else this.time=n;if(s&&1==(1&r))return e-n}return n}_setEndings(t,e,i){const n=this._interpolantSettings;i?(n.endingStart=st,n.endingEnd=st):(n.endingStart=t?this.zeroSlopeAtStart?st:rt:at,n.endingEnd=e?this.zeroSlopeAtEnd?st:rt:at)}_scheduleFading(t,e,i){const n=this._mixer,r=n.time;let s=this._weightInterpolant;null===s&&(s=n._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=i,this}}const dh=new Float32Array(1);class ph{constructor(t){this.value=t}clone(){return new ph(void 0===this.value.clone?this.value:this.value.clone())}}let mh=0;function fh(t,e){return t.distance-e.distance}function gh(t,e,i,n){if(t.layers.test(e.layers)&&t.raycast(e,i),!0===n){const n=t.children;for(let t=0,r=n.length;t>-e-14,n[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(n[t]=e+15<<10,n[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(n[t]=31744,n[256|t]=64512,r[t]=24,r[256|t]=24):(n[t]=31744,n[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,i=0;for(;0==(8388608&e);)e<<=1,i-=8388608;e&=-8388609,i+=947912704,s[t]=e|i}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:i,baseTable:n,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}var kh=Object.freeze({__proto__:null,fromHalfFloat:function(t){const e=t>>10;return Bh.uint32View[0]=Bh.mantissaTable[Bh.offsetTable[e]+(1023&t)]+Bh.exponentTable[e],Bh.floatView[0]},toHalfFloat:function(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=St(t,-65504,65504),Bh.floatView[0]=t;const e=Bh.uint32View[0],i=e>>23&511;return Bh.baseTable[i]+((8388607&e)>>Bh.shiftTable[i])}});"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:e}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=e),t.ACESFilmicToneMapping=4,t.AddEquation=i,t.AddOperation=2,t.AdditiveAnimationBlendMode=lt,t.AdditiveBlending=2,t.AlphaFormat=1021,t.AlwaysDepth=1,t.AlwaysStencilFunc=519,t.AmbientLight=Rc,t.AmbientLightProbe=class extends Dc{constructor(t,e=1){super(void 0,e),this.isAmbientLightProbe=!0;const i=(new Zt).set(t);this.sh.coefficients[0].set(i.r,i.g,i.b).multiplyScalar(2*Math.sqrt(Math.PI))}},t.AnimationClip=sc,t.AnimationLoader=class extends hc{constructor(t){super(t)}load(t,e,i,n){const r=this,s=new pc(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(i){try{e(r.parse(JSON.parse(i)))}catch(e){n?n(e):console.error(e),r.manager.itemError(t)}}),i,n)}parse(t){const e=[];for(let i=0;i=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,i=this._nActiveActions,n=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==i;++a){e[a]._update(n,t,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=n;t!==e;++t){const e=i[t],n=e[s],r=e[l];e[l]=n,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,i=this._bindings,n=i.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=n;t!==e;++t){const e=i[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const i=this._bindingsIndicesByPath;let n=i[t];const r=this._bindings;if(void 0!==n)return r[n];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);n=r.length,i[t]=n,s.push(t),a.push(e),r.push(h);for(let i=c,n=o.length;i!==n;++i){const n=o[i];h[i]=new hh(n,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,i=e[t];if(void 0!==i){const n=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=i,s[i]=o,s.pop(),r[i]=r[a],r.pop(),n[i]=n[a],n.pop()}}},t.AnimationUtils=ql,t.ArcCurve=lo,t.ArrayCamera=Vs,t.ArrowHelper=class extends li{constructor(t=new oe(0,0,1),e=new oe(0,0,0),i=1,n=16776960,r=.2*i,s=.2*r){super(),this.type="ArrowHelper",void 0===zh&&(zh=new zi,zh.setAttribute("position",new Ci([0,0,0,0,1,0],3)),Uh=new Io(0,.5,1,5,1),Uh.translate(0,-.5,0)),this.position.copy(e),this.line=new Xa(zh,new Ga({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Ji(Uh,new bi({color:n,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(i,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{Oh.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(Oh,e)}}setLength(t,e=.2*t,i=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(i,e,i),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},t.Audio=$c,t.AudioAnalyser=class{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let i=0;ithis.max.x||t.ythis.max.y)}containsBox(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(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return vh.copy(t).clamp(this.min,this.max).sub(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},t.Box3=he,t.Box3Helper=class extends Ja{constructor(t,e=16776960){const i=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]),n=new zi;n.setIndex(new Ti(i,1)),n.setAttribute("position",new Ci([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(n,new Ga({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}dispose(){this.geometry.dispose(),this.material.dispose()}},t.BoxBufferGeometry=class extends $i{constructor(t,e,i,n,r,s){console.warn("THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry."),super(t,e,i,n,r,s)}},t.BoxGeometry=$i,t.BoxHelper=class extends Ja{constructor(t,e=16776960){const i=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]),n=new Float32Array(24),r=new zi;r.setIndex(new Ti(i,1)),r.setAttribute("position",new Ti(n,3)),super(r,new Ga({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&Nh.setFromObject(this.object),Nh.isEmpty())return;const e=Nh.min,i=Nh.max,n=this.geometry.attributes.position,r=n.array;r[0]=i.x,r[1]=i.y,r[2]=i.z,r[3]=e.x,r[4]=i.y,r[5]=i.z,r[6]=e.x,r[7]=e.y,r[8]=i.z,r[9]=i.x,r[10]=e.y,r[11]=i.z,r[12]=i.x,r[13]=i.y,r[14]=e.z,r[15]=e.x,r[16]=i.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=i.x,r[22]=e.y,r[23]=e.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t,e){return super.copy(t,e),this.object=t.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},t.BufferAttribute=Ti,t.BufferGeometry=zi,t.BufferGeometryLoader=Uc,t.ByteType=1010,t.Cache=oc,t.Camera=sn,t.CameraHelper=class extends Ja{constructor(t){const e=new zi,i=new Ga({color:16777215,vertexColors:!0,toneMapped:!1}),n=[],r=[],s={};function a(t,e){o(t),o(e)}function o(t){n.push(0,0,0),r.push(0,0,0),void 0===s[t]&&(s[t]=[]),s[t].push(n.length/3-1)}a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4"),e.setAttribute("position",new Ci(n,3)),e.setAttribute("color",new Ci(r,3)),super(e,i),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update();const l=new Zt(16755200),c=new Zt(16711680),h=new Zt(43775),u=new Zt(16777215),d=new Zt(3355443);this.setColors(l,c,h,u,d)}setColors(t,e,i,n,r){const s=this.geometry.getAttribute("color");s.setXYZ(0,t.r,t.g,t.b),s.setXYZ(1,t.r,t.g,t.b),s.setXYZ(2,t.r,t.g,t.b),s.setXYZ(3,t.r,t.g,t.b),s.setXYZ(4,t.r,t.g,t.b),s.setXYZ(5,t.r,t.g,t.b),s.setXYZ(6,t.r,t.g,t.b),s.setXYZ(7,t.r,t.g,t.b),s.setXYZ(8,t.r,t.g,t.b),s.setXYZ(9,t.r,t.g,t.b),s.setXYZ(10,t.r,t.g,t.b),s.setXYZ(11,t.r,t.g,t.b),s.setXYZ(12,t.r,t.g,t.b),s.setXYZ(13,t.r,t.g,t.b),s.setXYZ(14,t.r,t.g,t.b),s.setXYZ(15,t.r,t.g,t.b),s.setXYZ(16,t.r,t.g,t.b),s.setXYZ(17,t.r,t.g,t.b),s.setXYZ(18,t.r,t.g,t.b),s.setXYZ(19,t.r,t.g,t.b),s.setXYZ(20,t.r,t.g,t.b),s.setXYZ(21,t.r,t.g,t.b),s.setXYZ(22,t.r,t.g,t.b),s.setXYZ(23,t.r,t.g,t.b),s.setXYZ(24,e.r,e.g,e.b),s.setXYZ(25,e.r,e.g,e.b),s.setXYZ(26,e.r,e.g,e.b),s.setXYZ(27,e.r,e.g,e.b),s.setXYZ(28,e.r,e.g,e.b),s.setXYZ(29,e.r,e.g,e.b),s.setXYZ(30,e.r,e.g,e.b),s.setXYZ(31,e.r,e.g,e.b),s.setXYZ(32,i.r,i.g,i.b),s.setXYZ(33,i.r,i.g,i.b),s.setXYZ(34,i.r,i.g,i.b),s.setXYZ(35,i.r,i.g,i.b),s.setXYZ(36,i.r,i.g,i.b),s.setXYZ(37,i.r,i.g,i.b),s.setXYZ(38,n.r,n.g,n.b),s.setXYZ(39,n.r,n.g,n.b),s.setXYZ(40,r.r,r.g,r.b),s.setXYZ(41,r.r,r.g,r.b),s.setXYZ(42,r.r,r.g,r.b),s.setXYZ(43,r.r,r.g,r.b),s.setXYZ(44,r.r,r.g,r.b),s.setXYZ(45,r.r,r.g,r.b),s.setXYZ(46,r.r,r.g,r.b),s.setXYZ(47,r.r,r.g,r.b),s.setXYZ(48,r.r,r.g,r.b),s.setXYZ(49,r.r,r.g,r.b),s.needsUpdate=!0}update(){const t=this.geometry,e=this.pointMap;Ih.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),Dh("c",e,t,Ih,0,0,-1),Dh("t",e,t,Ih,0,0,1),Dh("n1",e,t,Ih,-1,-1,-1),Dh("n2",e,t,Ih,1,-1,-1),Dh("n3",e,t,Ih,-1,1,-1),Dh("n4",e,t,Ih,1,1,-1),Dh("f1",e,t,Ih,-1,-1,1),Dh("f2",e,t,Ih,1,-1,1),Dh("f3",e,t,Ih,-1,1,1),Dh("f4",e,t,Ih,1,1,1),Dh("u1",e,t,Ih,.7,1.1,-1),Dh("u2",e,t,Ih,-.7,1.1,-1),Dh("u3",e,t,Ih,0,2,-1),Dh("cf1",e,t,Ih,-1,0,1),Dh("cf2",e,t,Ih,1,0,1),Dh("cf3",e,t,Ih,0,-1,1),Dh("cf4",e,t,Ih,0,1,1),Dh("cn1",e,t,Ih,-1,0,-1),Dh("cn2",e,t,Ih,1,0,-1),Dh("cn3",e,t,Ih,0,-1,-1),Dh("cn4",e,t,Ih,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},t.CanvasTexture=class extends ee{constructor(t,e,i,n,r,s,a,o,l){super(t,e,i,n,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},t.CapsuleBufferGeometry=class extends Ro{constructor(t,e,i,n){console.warn("THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry."),super(t,e,i,n)}},t.CapsuleGeometry=Ro,t.CatmullRomCurve3=fo,t.CineonToneMapping=3,t.CircleBufferGeometry=class extends Po{constructor(t,e,i,n){console.warn("THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry."),super(t,e,i,n)}},t.CircleGeometry=Po,t.ClampToEdgeWrapping=h,t.Clock=qc,t.Color=Zt,t.ColorKeyframeTrack=Ql,t.ColorManagement=Vt,t.CompressedArrayTexture=class extends so{constructor(t,e,i,n,r,s){super(t,e,i,r,s),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=h}},t.CompressedTexture=so,t.CompressedTextureLoader=class extends hc{constructor(t){super(t)}load(t,e,i,n){const r=this,s=[],a=new so,o=new pc(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const i=r.parse(t,!0);s[c]={width:i.width,height:i.height,format:i.format,mipmaps:i.mipmaps},l+=1,6===l&&(1===i.mipmapCount&&(a.minFilter=f),a.image=s,a.format=i.format,a.needsUpdate=!0,e&&e(a))}),i,n)}if(Array.isArray(t))for(let e=0,i=t.length;e0){const i=new lc(e);r=new mc(i),r.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e0){n=new mc(this.manager),n.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e1)for(let i=0;iNumber.EPSILON){if(l<0&&(i=e[s],o=-o,a=e[r],l=-l),t.ya.y)continue;if(t.y===i.y){if(t.x===i.x)return!0}else{const e=l*(t.x-i.x)-o*(t.y-i.y);if(0===e)return!0;if(e<0)continue;n=!n}}else{if(t.y!==i.y)continue;if(a.x<=t.x&&t.x<=i.x||i.x<=t.x&&t.x<=a.x)return!0}}return n}const i=pl.isClockWise,n=this.subPaths;if(0===n.length)return[];let r,s,a;const o=[];if(1===n.length)return s=n[0],a=new Go,a.curves=s.curves,o.push(a),o;let l=!i(n[0].getPoints());l=t?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let e=0,a=n.length;e1){let t=!1,i=0;for(let t=0,e=h.length;t0&&!1===t&&(p=c)}for(let t=0,e=h.length;t=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}},t.WebGL1Renderer=Ks,t.WebGL3DRenderTarget=class extends ne{constructor(t=1,e=1,i=1){super(t,e),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new se(null,t,e,i),this.texture.isRenderTargetTexture=!0}},t.WebGLArrayRenderTarget=class extends ne{constructor(t=1,e=1,i=1){super(t,e),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new re(null,t,e,i),this.texture.isRenderTargetTexture=!0}},t.WebGLCubeRenderTarget=hn,t.WebGLMultipleRenderTargets=class extends ne{constructor(t=1,e=1,i=1,n={}){super(t,e,n),this.isWebGLMultipleRenderTargets=!0;const r=this.texture;this.texture=[];for(let t=0;t> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; + + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); + +} + +function clamp( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); + +} + +// compute euclidean modulo of m % n +// https://en.wikipedia.org/wiki/Modulo_operation +function euclideanModulo( n, m ) { + + return ( ( n % m ) + m ) % m; + +} + +// Linear mapping from range to range +function mapLinear( x, a1, a2, b1, b2 ) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + +} + +// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ +function inverseLerp( x, y, value ) { + + if ( x !== y ) { + + return ( value - x ) / ( y - x ); + + } else { + + return 0; + + } + +} + +// https://en.wikipedia.org/wiki/Linear_interpolation +function lerp( x, y, t ) { + + return ( 1 - t ) * x + t * y; + +} + +// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ +function damp( x, y, lambda, dt ) { + + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); + +} + +// https://www.desmos.com/calculator/vcsjnyz7x4 +function pingpong( x, length = 1 ) { + + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); + +} + +// http://en.wikipedia.org/wiki/Smoothstep +function smoothstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * ( 3 - 2 * x ); + +} + +function smootherstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + +} + +// Random integer from interval +function randInt( low, high ) { + + return low + Math.floor( Math.random() * ( high - low + 1 ) ); + +} + +// Random float from interval +function randFloat( low, high ) { + + return low + Math.random() * ( high - low ); + +} + +// Random float from <-range/2, range/2> interval +function randFloatSpread( range ) { + + return range * ( 0.5 - Math.random() ); + +} + +// Deterministic pseudo-random float in the interval [ 0, 1 ] +function seededRandom( s ) { + + if ( s !== undefined ) _seed = s; + + // Mulberry32 generator + + let t = _seed += 0x6D2B79F5; + + t = Math.imul( t ^ t >>> 15, t | 1 ); + + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); + + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; + +} + +function degToRad( degrees ) { + + return degrees * DEG2RAD; + +} + +function radToDeg( radians ) { + + return radians * RAD2DEG; + +} + +function isPowerOfTwo( value ) { + + return ( value & ( value - 1 ) ) === 0 && value !== 0; + +} + +function ceilPowerOfTwo( value ) { + + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + +} + +function floorPowerOfTwo( value ) { + + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + +} + +function setQuaternionFromProperEuler( q, a, b, c, order ) { + + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles + + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians + + const cos = Math.cos; + const sin = Math.sin; + + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); + + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); + + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); + + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); + + switch ( order ) { + + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; + + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; + + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; + + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; + + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; + + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; + + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + + } + +} + +function denormalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return value / 65535.0; + + case Uint8Array: + + return value / 255.0; + + case Int16Array: + + return Math.max( value / 32767.0, - 1.0 ); + + case Int8Array: + + return Math.max( value / 127.0, - 1.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + + return Math.round( value * 255.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'Invalid component type.' ); + + } + +} + +var MathUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + ceilPowerOfTwo: ceilPowerOfTwo, + clamp: clamp, + damp: damp, + degToRad: degToRad, + denormalize: denormalize, + euclideanModulo: euclideanModulo, + floorPowerOfTwo: floorPowerOfTwo, + generateUUID: generateUUID, + inverseLerp: inverseLerp, + isPowerOfTwo: isPowerOfTwo, + lerp: lerp, + mapLinear: mapLinear, + normalize: normalize, + pingpong: pingpong, + radToDeg: radToDeg, + randFloat: randFloat, + randFloatSpread: randFloatSpread, + randInt: randInt, + seededRandom: seededRandom, + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + smootherstep: smootherstep, + smoothstep: smoothstep +}); + +class Vector2 { + + constructor( x = 0, y = 0 ) { + + Vector2.prototype.isVector2 = true; + + this.x = x; + this.y = y; + + } + + get width() { + + return this.x; + + } + + set width( value ) { + + this.x = value; + + } + + get height() { + + return this.y; + + } + + set height( value ) { + + this.y = value; + + } + + set( x, y ) { + + this.x = x; + this.y = y; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + + return this; + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + + return this; + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + + return this; + + } + + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y; + + } + + cross( v ) { + + return this.x * v.y - this.y * v.x; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + angle() { + + // computes the angle in radians with respect to the positive x-axis + + const angle = Math.atan2( - this.y, - this.x ) + Math.PI; + + return angle; + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + + return this; + + } + + rotateAround( center, angle ) { + + const c = Math.cos( angle ), s = Math.sin( angle ); + + const x = this.x - center.x; + const y = this.y - center.y; + + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } + +} + +class Matrix3 { + + constructor() { + + Matrix3.prototype.isMatrix3 = true; + + this.elements = [ + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + + const te = this.elements; + + 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; + + } + + identity() { + + this.set( + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ); + + return this; + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); + + return this; + + } + + setFromMatrix4( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] + + ); + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + + const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + + return this; + + } + + multiplyScalar( s ) { + + const te = this.elements; + + 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; + + return this; + + } + + determinant() { + + const te = this.elements; + + const 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 a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + + } + + invert() { + + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], + n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], + n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], + + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, + + det = n11 * t11 + n21 * t12 + n31 * t13; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + + return this; + + } + + transpose() { + + let tmp; + const 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; + + return this; + + } + + getNormalMatrix( matrix4 ) { + + return this.setFromMatrix4( matrix4 ).invert().transpose(); + + } + + transposeIntoArray( r ) { + + const m = this.elements; + + 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 ]; + + return this; + + } + + setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { + + const c = Math.cos( rotation ); + const s = Math.sin( rotation ); + + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); + + return this; + + } + + // + + scale( sx, sy ) { + + this.premultiply( _m3.makeScale( sx, sy ) ); + + return this; + + } + + rotate( theta ) { + + this.premultiply( _m3.makeRotation( - theta ) ); + + return this; + + } + + translate( tx, ty ) { + + this.premultiply( _m3.makeTranslation( tx, ty ) ); + + return this; + + } + + // for 2D Transforms + + makeTranslation( x, y ) { + + this.set( + + 1, 0, x, + 0, 1, y, + 0, 0, 1 + + ); + + return this; + + } + + makeRotation( theta ) { + + // counterclockwise + + const c = Math.cos( theta ); + const s = Math.sin( theta ); + + this.set( + + c, - s, 0, + s, c, 0, + 0, 0, 1 + + ); + + return this; + + } + + makeScale( x, y ) { + + this.set( + + x, 0, 0, + 0, y, 0, + 0, 0, 1 + + ); + + return this; + + } + + // + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 9; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; + + return array; + + } + + clone() { + + return new this.constructor().fromArray( this.elements ); + + } + +} + +const _m3 = /*@__PURE__*/ new Matrix3(); + +function arrayNeedsUint32( array ) { + + // assumes larger values usually on last + + for ( let i = array.length - 1; i >= 0; -- i ) { + + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + + } + + return false; + +} + +const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; + +function getTypedArray( type, buffer ) { + + return new TYPED_ARRAYS[ type ]( buffer ); + +} + +function createElementNS( name ) { + + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); + +} + +function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + +} + +function LinearToSRGB( c ) { + + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + +} + +// JavaScript RGB-to-RGB transforms, defined as +// FN[InputColorSpace][OutputColorSpace] callback functions. +const FN = { + [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear }, + [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB }, +}; + +const ColorManagement = { + + legacyMode: true, + + get workingColorSpace() { + + return LinearSRGBColorSpace; + + }, + + set workingColorSpace( colorSpace ) { + + console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' ); + + }, + + convert: function ( color, sourceColorSpace, targetColorSpace ) { + + if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { + + return color; + + } + + if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) { + + const fn = FN[ sourceColorSpace ][ targetColorSpace ]; + + color.r = fn( color.r ); + color.g = fn( color.g ); + color.b = fn( color.b ); + + return color; + + } + + throw new Error( 'Unsupported color space conversion.' ); + + }, + + fromWorkingColorSpace: function ( color, targetColorSpace ) { + + return this.convert( color, this.workingColorSpace, targetColorSpace ); + + }, + + toWorkingColorSpace: function ( color, sourceColorSpace ) { + + return this.convert( color, sourceColorSpace, this.workingColorSpace ); + + }, + +}; + +const _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, 'rebeccapurple': 0x663399, '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 }; + +const _rgb$1 = { r: 0, g: 0, b: 0 }; +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; + +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; + +} + +function toComponents( source, target ) { + + target.r = source.r; + target.g = source.g; + target.b = source.b; + + return target; + +} + +class Color { + + constructor( r, g, b ) { + + this.isColor = true; + + this.r = 1; + this.g = 1; + this.b = 1; + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + return this.set( r ); + + } + + return this.setRGB( r, g, b ); + + } + + set( value ) { + + if ( value && value.isColor ) { + + this.copy( value ); + + } else if ( typeof value === 'number' ) { + + this.setHex( value ); + + } else if ( typeof value === 'string' ) { + + this.setStyle( value ); + + } + + return this; + + } + + setScalar( scalar ) { + + this.r = scalar; + this.g = scalar; + this.b = scalar; + + return this; + + } + + setHex( hex, colorSpace = SRGBColorSpace ) { + + hex = Math.floor( hex ); + + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { + + this.r = r; + this.g = g; + this.b = b; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); + + if ( s === 0 ) { + + this.r = this.g = this.b = l; + + } else { + + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const 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 ); + + } + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + setStyle( style, colorSpace = SRGBColorSpace ) { + + function handleAlpha( string ) { + + if ( string === undefined ) return; + + if ( parseFloat( string ) < 1 ) { + + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + + } + + } + + + let m; + + if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) { + + // rgb / hsl + + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; + + switch ( name ) { + + case 'rgb': + case 'rgba': + + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // 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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + handleAlpha( color[ 4 ] ); + + return this; + + } + + break; + + case 'hsl': + case 'hsla': + + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + const h = parseFloat( color[ 1 ] ) / 360; + const s = parseFloat( color[ 2 ] ) / 100; + const l = parseFloat( color[ 3 ] ) / 100; + + handleAlpha( color[ 4 ] ); + + return this.setHSL( h, s, l, colorSpace ); + + } + + break; + + } + + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + + // hex color + + const hex = m[ 1 ]; + const size = hex.length; + + if ( size === 3 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } else if ( size === 6 ) { + + // #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; + + ColorManagement.toWorkingColorSpace( this, colorSpace ); + + return this; + + } + + } + + if ( style && style.length > 0 ) { + + return this.setColorName( style, colorSpace ); + + } + + return this; + + } + + setColorName( style, colorSpace = SRGBColorSpace ) { + + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; + + if ( hex !== undefined ) { + + // red + this.setHex( hex, colorSpace ); + + } else { + + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); + + } + + return this; + + } + + clone() { + + return new this.constructor( this.r, this.g, this.b ); + + } + + copy( color ) { + + this.r = color.r; + this.g = color.g; + this.b = color.b; + + return this; + + } + + copySRGBToLinear( color ) { + + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); + + return this; + + } + + copyLinearToSRGB( color ) { + + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); + + return this; + + } + + convertSRGBToLinear() { + + this.copySRGBToLinear( this ); + + return this; + + } + + convertLinearToSRGB() { + + this.copyLinearToSRGB( this ); + + return this; + + } + + getHex( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0; + + } + + getHexString( colorSpace = SRGBColorSpace ) { + + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 ); + + } + + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b; + + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); + + let hue, saturation; + const lightness = ( min + max ) / 2.0; + + if ( min === max ) { + + hue = 0; + saturation = 0; + + } else { + + const delta = max - min; + + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + 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; + + } + + hue /= 6; + + } + + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + + } + + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + target.r = _rgb$1.r; + target.g = _rgb$1.g; + target.b = _rgb$1.b; + + return target; + + } + + getStyle( colorSpace = SRGBColorSpace ) { + + ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace ); + + if ( colorSpace !== SRGBColorSpace ) { + + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`; + + } + + return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`; + + } + + offsetHSL( h, s, l ) { + + this.getHSL( _hslA ); + + _hslA.h += h; _hslA.s += s; _hslA.l += l; + + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + + return this; + + } + + add( color ) { + + this.r += color.r; + this.g += color.g; + this.b += color.b; + + return this; + + } + + addColors( color1, color2 ) { + + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + + return this; + + } + + addScalar( s ) { + + this.r += s; + this.g += s; + this.b += s; + + return this; + + } + + sub( color ) { + + 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; + + } + + multiply( color ) { + + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + + return this; + + } + + multiplyScalar( s ) { + + this.r *= s; + this.g *= s; + this.b *= s; + + return this; + + } + + lerp( color, alpha ) { + + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; + + return this; + + } + + lerpColors( color1, color2, alpha ) { + + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; + + return this; + + } + + lerpHSL( color, alpha ) { + + this.getHSL( _hslA ); + color.getHSL( _hslB ); + + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); + + return this; + + } + + equals( c ) { + + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + + } + + fromArray( array, offset = 0 ) { + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); + + return this; + + } + + toJSON() { + + return this.getHex(); + + } + + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + +} + +Color.NAMES = _colorKeywords; + +let _canvas; + +class ImageUtils { + + static getDataURL( image ) { + + if ( /^data:/i.test( image.src ) ) { + + return image.src; + + } + + if ( typeof HTMLCanvasElement == 'undefined' ) { + + return image.src; + + } + + let canvas; + + if ( image instanceof HTMLCanvasElement ) { + + canvas = image; + + } else { + + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); + + _canvas.width = image.width; + _canvas.height = image.height; + + const context = _canvas.getContext( '2d' ); + + if ( image instanceof ImageData ) { + + context.putImageData( image, 0, 0 ); + + } else { + + context.drawImage( image, 0, 0, image.width, image.height ); + + } + + canvas = _canvas; + + } + + if ( canvas.width > 2048 || canvas.height > 2048 ) { + + console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image ); + + return canvas.toDataURL( 'image/jpeg', 0.6 ); + + } else { + + return canvas.toDataURL( 'image/png' ); + + } + + } + + static sRGBToLinear( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const canvas = createElementNS( 'canvas' ); + + canvas.width = image.width; + canvas.height = image.height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); + + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; + + for ( let i = 0; i < data.length; i ++ ) { + + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; + + } + + context.putImageData( imageData, 0, 0 ); + + return canvas; + + } else if ( image.data ) { + + const data = image.data.slice( 0 ); + + for ( let i = 0; i < data.length; i ++ ) { + + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { + + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); + + } else { + + // assuming float + + data[ i ] = SRGBToLinear( data[ i ] ); + + } + + } + + return { + data: data, + width: image.width, + height: image.height + }; + + } else { + + console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; + + } + + } + +} + +class Source { + + constructor( data = null ) { + + this.isSource = true; + + this.uuid = generateUUID(); + + this.data = data; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { + + return meta.images[ this.uuid ]; + + } + + const output = { + uuid: this.uuid, + url: '' + }; + + const data = this.data; + + if ( data !== null ) { + + let url; + + if ( Array.isArray( data ) ) { + + // cube texture + + url = []; + + for ( let i = 0, l = data.length; i < l; i ++ ) { + + if ( data[ i ].isDataTexture ) { + + url.push( serializeImage( data[ i ].image ) ); + + } else { + + url.push( serializeImage( data[ i ] ) ); + + } + + } + + } else { + + // texture + + url = serializeImage( data ); + + } + + output.url = url; + + } + + if ( ! isRootObject ) { + + meta.images[ this.uuid ] = output; + + } + + return output; + + } + +} + +function serializeImage( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + // default images + + return ImageUtils.getDataURL( image ); + + } else { + + if ( image.data ) { + + // images of DataTexture + + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + + } else { + + console.warn( 'THREE.Texture: Unable to serialize Texture.' ); + return {}; + + } + + } + +} + +let textureId = 0; + +class Texture extends EventDispatcher { + + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding ) { + + super(); + + this.isTexture = true; + + Object.defineProperty( this, 'id', { value: textureId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + + this.source = new Source( image ); + this.mipmaps = []; + + this.mapping = mapping; + + this.wrapS = wrapS; + this.wrapT = wrapT; + + this.magFilter = magFilter; + this.minFilter = minFilter; + + this.anisotropy = anisotropy; + + this.format = format; + this.internalFormat = null; + this.type = type; + + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; + + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + + 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) + + // 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; + + this.userData = {}; + + this.version = 0; + this.onUpdate = null; + + this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not + this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures) + + } + + get image() { + + return this.source.data; + + } + + set image( value ) { + + this.source.data = value; + + } + + updateMatrix() { + + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); + + this.mapping = source.mapping; + + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + + this.anisotropy = source.anisotropy; + + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); + + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + this.needsUpdate = true; + + return this; + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + + return meta.textures[ this.uuid ]; + + } + + const output = { + + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, + + uuid: this.uuid, + name: this.name, + + image: this.source.toJSON( meta ).uuid, + + mapping: this.mapping, + + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, + + wrap: [ this.wrapS, this.wrapT ], + + format: this.format, + type: this.type, + encoding: this.encoding, + + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + + flipY: this.flipY, + + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + + }; + + if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData; + + if ( ! isRootObject ) { + + meta.textures[ this.uuid ] = output; + + } + + return output; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + transformUv( uv ) { + + if ( this.mapping !== UVMapping ) return uv; + + uv.applyMatrix3( this.matrix ); + + if ( uv.x < 0 || uv.x > 1 ) { + + switch ( this.wrapS ) { + + case RepeatWrapping: + + uv.x = uv.x - Math.floor( uv.x ); + break; + + case ClampToEdgeWrapping: + + uv.x = uv.x < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + + uv.x = Math.ceil( uv.x ) - uv.x; + + } else { + + uv.x = uv.x - Math.floor( uv.x ); + + } + + break; + + } + + } + + if ( uv.y < 0 || uv.y > 1 ) { + + switch ( this.wrapT ) { + + case RepeatWrapping: + + uv.y = uv.y - Math.floor( uv.y ); + break; + + case ClampToEdgeWrapping: + + uv.y = uv.y < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + + uv.y = Math.ceil( uv.y ) - uv.y; + + } else { + + uv.y = uv.y - Math.floor( uv.y ); + + } + + break; + + } + + } + + if ( this.flipY ) { + + uv.y = 1 - uv.y; + + } + + return uv; + + } + + set needsUpdate( value ) { + + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } + + } + +} + +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; + +class Vector4 { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + Vector4.prototype.isVector4 = true; + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + } + + get width() { + + return this.z; + + } + + set width( value ) { + + this.z = value; + + } + + get height() { + + return this.w; + + } + + set height( value ) { + + this.w = value; + + } + + set( x, y, z, w ) { + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setW( w ) { + + this.w = w; + + return this; + + } + + setComponent( index, value ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z, this.w ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + this.w += s; + + return this; + + } + + addVectors( 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( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + + return this; + + } + + subVectors( 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; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + + return this; + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z, w = this.w; + const 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; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + setAxisAngleFromQuaternion( q ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + + // q is assumed to be normalized + + this.w = 2 * Math.acos( q.w ); + + const s = Math.sqrt( 1 - q.w * q.w ); + + if ( s < 0.0001 ) { + + this.x = 1; + this.y = 0; + this.z = 0; + + } else { + + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + + } + + return this; + + } + + setAxisAngleFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + + 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 ]; + + 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 + + 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 + + this.set( 1, 0, 0, 0 ); + + return this; // zero angle, arbitrary axis + + } + + // otherwise this singularity is angle = 180 + + angle = Math.PI; + + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; + + if ( ( xx > yy ) && ( xx > zz ) ) { + + // m11 is the largest diagonal term + + if ( xx < epsilon ) { + + x = 0; + y = 0.707106781; + z = 0.707106781; + + } else { + + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; + + } + + } else if ( yy > zz ) { + + // m22 is the largest diagonal term + + if ( yy < epsilon ) { + + x = 0.707106781; + y = 0; + z = 0.707106781; + + } else { + + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; + + } + + } else { + + // m33 is the largest diagonal term so base result on this + + if ( zz < epsilon ) { + + x = 0.707106781; + y = 0.707106781; + z = 0; + + } else { + + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; + + } + + } + + this.set( x, y, z, angle ); + + return this; // return 180 deg rotation + + } + + // as we have reached here there are no singularities so we can handle normally + + let 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 ); + + return this; + + } + + min( v ) { + + 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; + + } + + max( 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 ); + this.w = Math.max( this.w, v.w ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + 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() { + + 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() { + + 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() { + + 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; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + + } + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + 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; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + yield this.w; + + } + +} + +/* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers +*/ +class WebGLRenderTarget extends EventDispatcher { + + constructor( width = 1, height = 1, options = {} ) { + + super(); + + this.isWebGLRenderTarget = true; + + this.width = width; + this.height = height; + this.depth = 1; + + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; + + this.viewport = new Vector4( 0, 0, width, height ); + + const image = { width: width, height: height, depth: 1 }; + + this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + this.texture.isRenderTargetTexture = true; + + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false; + + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + + this.samples = options.samples !== undefined ? options.samples : 0; + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.copy( source.viewport ); + + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; + + // ensure image object is not shared, see #20328 + + const image = Object.assign( {}, source.texture.image ); + this.texture.source = new Source( image ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.samples = source.samples; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class DataArrayTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + super( null ); + + this.isDataArrayTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +class WebGLArrayRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGLArrayRenderTarget = true; + + this.depth = depth; + + this.texture = new DataArrayTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +class Data3DTexture extends Texture { + + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // const texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + super( null ); + + this.isData3DTexture = true; + + this.image = { data, width, height, depth }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +class WebGL3DRenderTarget extends WebGLRenderTarget { + + constructor( width = 1, height = 1, depth = 1 ) { + + super( width, height ); + + this.isWebGL3DRenderTarget = true; + + this.depth = depth; + + this.texture = new Data3DTexture( null, width, height, depth ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +class WebGLMultipleRenderTargets extends WebGLRenderTarget { + + constructor( width = 1, height = 1, count = 1, options = {} ) { + + super( width, height, options ); + + this.isWebGLMultipleRenderTargets = true; + + const texture = this.texture; + + this.texture = []; + + for ( let i = 0; i < count; i ++ ) { + + this.texture[ i ] = texture.clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + } + + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + for ( let i = 0, il = this.texture.length; i < il; i ++ ) { + + this.texture[ i ].image.width = width; + this.texture[ i ].image.height = height; + this.texture[ i ].image.depth = depth; + + } + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + return this; + + } + + copy( source ) { + + this.dispose(); + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.viewport.set( 0, 0, this.width, this.height ); + this.scissor.set( 0, 0, this.width, this.height ); + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone(); + + this.texture.length = 0; + + for ( let i = 0, il = source.texture.length; i < il; i ++ ) { + + this.texture[ i ] = source.texture[ i ].clone(); + this.texture[ i ].isRenderTargetTexture = true; + + } + + return this; + + } + +} + +class Quaternion { + + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + this.isQuaternion = true; + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + } + + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + + // fuzz-free, array-based Quaternion SLERP operation + + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; + + if ( t === 0 ) { + + dst[ dstOffset + 0 ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + return; + + } + + if ( t === 1 ) { + + dst[ dstOffset + 0 ] = x1; + dst[ dstOffset + 1 ] = y1; + dst[ dstOffset + 2 ] = z1; + dst[ dstOffset + 3 ] = w1; + return; + + } + + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; + + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { + + const sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); + + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; + + } + + const tDir = t * dir; + + 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 ) { + + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + + } + + } + + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + + } + + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; + + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + + return dst; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get w() { + + return this._w; + + } + + set w( value ) { + + this._w = value; + this._onChangeCallback(); + + } + + set( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._w ); + + } + + copy( quaternion ) { + + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); + + return this; + + } + + setFromEuler( euler, update ) { + + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m + + const cos = Math.cos; + const sin = Math.sin; + + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); + + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); + + switch ( order ) { + + case 'XYZ': + 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; + break; + + case '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; + break; + + case 'ZXY': + 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; + break; + + case '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; + break; + + case '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; + break; + + case 'XZY': + 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; + break; + + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + + } + + if ( update !== false ) this._onChangeCallback(); + + return this; + + } + + setFromAxisAngle( axis, angle ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + + // assumes axis is normalized + + const halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const 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 ], + + trace = m11 + m22 + m33; + + if ( trace > 0 ) { + + const s = 0.5 / Math.sqrt( trace + 1.0 ); + + 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 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; + + } else { + + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._onChangeCallback(); + + return this; + + } + + setFromUnitVectors( vFrom, vTo ) { + + // assumes direction vectors vFrom and vTo are normalized + + let r = vFrom.dot( vTo ) + 1; + + if ( r < Number.EPSILON ) { + + // vFrom and vTo point in opposite directions + + r = 0; + + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + + } else { + + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; + + } + + } else { + + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + + } + + return this.normalize(); + + } + + angleTo( q ) { + + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) ); + + } + + rotateTowards( q, step ) { + + const angle = this.angleTo( q ); + + if ( angle === 0 ) return this; + + const t = Math.min( 1, step / angle ); + + this.slerp( q, t ); + + return this; + + } + + identity() { + + return this.set( 0, 0, 0, 1 ); + + } + + invert() { + + // quaternion is assumed to have unit length + + return this.conjugate(); + + } + + conjugate() { + + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; + + this._onChangeCallback(); + + return this; + + } + + dot( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + + } + + lengthSq() { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + + } + + length() { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + + } + + normalize() { + + let l = this.length(); + + if ( l === 0 ) { + + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + + } else { + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + + } + + this._onChangeCallback(); + + return this; + + } + + multiply( q ) { + + return this.multiplyQuaternions( this, q ); + + } + + premultiply( q ) { + + return this.multiplyQuaternions( q, this ); + + } + + multiplyQuaternions( a, b ) { + + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + 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(); + + return this; + + } + + slerp( qb, t ) { + + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); + + const x = this._x, y = this._y, z = this._z, w = this._w; + + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + + if ( cosHalfTheta < 0 ) { + + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; + + cosHalfTheta = - cosHalfTheta; + + } else { + + this.copy( qb ); + + } + + if ( cosHalfTheta >= 1.0 ) { + + this._w = w; + this._x = x; + this._y = y; + this._z = z; + + return this; + + } + + const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + + if ( sqrSinHalfTheta <= Number.EPSILON ) { + + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + + this.normalize(); + this._onChangeCallback(); + + return this; + + } + + const sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + const 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 ); + + this._onChangeCallback(); + + return this; + + } + + slerpQuaternions( qa, qb, t ) { + + return this.copy( qa ).slerp( qb, t ); + + } + + random() { + + // Derived from http://planning.cs.uiuc.edu/node198.html + // Note, this source uses w, x, y, z ordering, + // so we swap the order below. + + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt( 1 - u1 ); + const sqrtu1 = Math.sqrt( u1 ); + + const u2 = 2 * Math.PI * Math.random(); + + const u3 = 2 * Math.PI * Math.random(); + + return this.set( + sqrt1u1 * Math.cos( u2 ), + sqrtu1 * Math.sin( u3 ), + sqrtu1 * Math.cos( u3 ), + sqrt1u1 * Math.sin( u2 ), + ); + + } + + equals( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + + } + + fromArray( array, offset = 0 ) { + + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); + + return this; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + +} + +class Vector3 { + + constructor( x = 0, y = 0, z = 0 ) { + + Vector3.prototype.isVector3 = true; + + this.x = x; + this.y = y; + this.z = z; + + } + + set( x, y, z ) { + + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + + this.x = x; + this.y = y; + this.z = z; + + return this; + + } + + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + + return this; + + } + + setX( x ) { + + this.x = x; + + return this; + + } + + setY( y ) { + + this.y = y; + + return this; + + } + + setZ( z ) { + + this.z = z; + + return this; + + } + + setComponent( index, value ) { + + switch ( index ) { + + 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 ); + + } + + return this; + + } + + getComponent( index ) { + + switch ( index ) { + + 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 ); + + } + + } + + clone() { + + return new this.constructor( this.x, this.y, this.z ); + + } + + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + + return this; + + } + + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + + return this; + + } + + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + + return this; + + } + + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + + return this; + + } + + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; + + } + + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + + return this; + + } + + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + + return this; + + } + + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + + return this; + + } + + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + + return this; + + } + + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + + return this; + + } + + multiplyVectors( a, b ) { + + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + + return this; + + } + + applyEuler( euler ) { + + return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) ); + + } + + applyAxisAngle( axis, angle ) { + + return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) ); + + } + + applyMatrix3( m ) { + + const x = this.x, y = this.y, z = this.z; + const 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; + + } + + applyNormalMatrix( m ) { + + return this.applyMatrix3( m ).normalize(); + + } + + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + 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; + + return this; + + } + + applyQuaternion( q ) { + + const x = this.x, y = this.y, z = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // calculate quat * vector + + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = - qx * x - qy * y - qz * z; + + // 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; + + return this; + + } + + project( camera ) { + + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + + } + + unproject( camera ) { + + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + + } + + transformDirection( m ) { + + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + 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; + + return this.normalize(); + + } + + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; + + } + + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + + return this; + + } + + max( 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 ); + + return this; + + } + + clamp( min, max ) { + + // assumes min < max, componentwise + + 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 ) ); + + return this; + + } + + clampScalar( minVal, maxVal ) { + + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + + return this; + + } + + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + + } + + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + + return this; + + } + + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + + return this; + + } + + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; + + } + + roundToZero() { + + 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 ); + + return this; + + } + + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + + return this; + + } + + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z; + + } + + // TODO lengthSquared? + + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z; + + } + + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + + } + + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + + } + + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + + return this; + + } + + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + + return this; + + } + + cross( v ) { + + return this.crossVectors( this, v ); + + } + + crossVectors( a, b ) { + + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + + } + + projectOnVector( v ) { + + const denominator = v.lengthSq(); + + if ( denominator === 0 ) return this.set( 0, 0, 0 ); + + const scalar = v.dot( this ) / denominator; + + return this.copy( v ).multiplyScalar( scalar ); + + } + + projectOnPlane( planeNormal ) { + + _vector$c.copy( this ).projectOnVector( planeNormal ); + + return this.sub( _vector$c ); + + } + + reflect( normal ) { + + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length + + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + + } + + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, - 1, 1 ) ); + + } + + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + + return dx * dx + dy * dy + dz * dz; + + } + + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + + } + + setFromSpherical( s ) { + + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + + } + + setFromSphericalCoords( radius, phi, theta ) { + + const sinPhiRadius = Math.sin( phi ) * radius; + + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); + + return this; + + } + + setFromCylindrical( c ) { + + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + + } + + setFromCylindricalCoords( radius, theta, y ) { + + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); + + return this; + + } + + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + + return this; + + } + + setFromMatrixScale( m ) { + + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); + + this.x = sx; + this.y = sy; + this.z = sz; + + return this; + + } + + setFromMatrixColumn( m, index ) { + + return this.fromArray( m.elements, index * 4 ); + + } + + setFromMatrix3Column( m, index ) { + + return this.fromArray( m.elements, index * 3 ); + + } + + setFromEuler( e ) { + + this.x = e._x; + this.y = e._y; + this.z = e._z; + + return this; + + } + + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + + } + + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + + return array; + + } + + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + + return this; + + } + + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; + + } + + randomDirection() { + + // Derived from https://mathworld.wolfram.com/SpherePointPicking.html + + const u = ( Math.random() - 0.5 ) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt( 1 - u ** 2 ); + + this.x = f * Math.cos( t ); + this.y = f * Math.sin( t ); + this.z = u; + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + + } + +} + +const _vector$c = /*@__PURE__*/ new Vector3(); +const _quaternion$4 = /*@__PURE__*/ new Quaternion(); + +class Box3 { + + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + + this.isBox3 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromArray( array ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const x = array[ i ]; + const y = array[ i + 1 ]; + const z = array[ i + 2 ]; + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromBufferAttribute( attribute ) { + + let minX = + Infinity; + let minY = + Infinity; + let minZ = + Infinity; + + let maxX = - Infinity; + let maxY = - Infinity; + let maxZ = - Infinity; + + for ( let i = 0, l = attribute.count; i < l; i ++ ) { + + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + setFromObject( object, precise = false ) { + + this.makeEmpty(); + + return this.expandByObject( object, precise ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ) || ( this.max.z < this.min.z ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + expandByObject( object, precise = false ) { + + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms + + object.updateWorldMatrix( false, false ); + + const geometry = object.geometry; + + if ( geometry !== undefined ) { + + if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) { + + const position = geometry.attributes.position; + for ( let i = 0, l = position.count; i < l; i ++ ) { + + _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); + + } + + } else { + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + _box$3.copy( geometry.boundingBox ); + _box$3.applyMatrix4( object.matrixWorld ); + + this.union( _box$3 ); + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } + + return this; + + } + + containsPoint( point ) { + + return 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 ? false : true; + + } + + containsBox( box ) { + + return 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; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.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 ) + ); + + } + + intersectsBox( box ) { + + // using 6 splitting planes to rule out intersections. + return 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 ? false : true; + + } + + intersectsSphere( sphere ) { + + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); + + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + intersectsPlane( plane ) { + + // 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. + + let min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + + } else { + + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + + } + + if ( plane.normal.y > 0 ) { + + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + + } else { + + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + + } + + if ( plane.normal.z > 0 ) { + + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + + } else { + + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); + + } + + intersectsTriangle( triangle ) { + + if ( this.isEmpty() ) { + + return false; + + } + + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); + + // translate triangle to aabb origin + _v0$2.subVectors( triangle.a, _center ); + _v1$7.subVectors( triangle.b, _center ); + _v2$4.subVectors( triangle.c, _center ); + + // compute edge vectors for triangle + _f0.subVectors( _v1$7, _v0$2 ); + _f1.subVectors( _v2$4, _v1$7 ); + _f2.subVectors( _v0$2, _v2$4 ); + + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) { + + return false; + + } + + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + + return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ); + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max ); + + return clampedPoint.sub( point ).length(); + + } + + getBoundingSphere( target ) { + + this.getCenter( target.center ); + + target.radius = this.getSize( _vector$b ).length() * 0.5; + + return target; + + } + + intersect( box ) { + + 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(); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + applyMatrix4( matrix ) { + + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; + + // 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 + + this.setFromPoints( _points ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + +} + +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; + +const _vector$b = /*@__PURE__*/ new Vector3(); + +const _box$3 = /*@__PURE__*/ new Box3(); + +// triangle centered vertices + +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$7 = /*@__PURE__*/ new Vector3(); +const _v2$4 = /*@__PURE__*/ new Vector3(); + +// triangle edge vectors + +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); + +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); + +function satForAxes( axes, v0, v1, v2, extents ) { + + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; + + } + + } + + return true; + +} + +const _box$2 = /*@__PURE__*/ new Box3(); +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); + +class Sphere { + + constructor( center = new Vector3(), radius = - 1 ) { + + this.center = center; + this.radius = radius; + + } + + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; + + } + + setFromPoints( points, optionalCenter ) { + + const center = this.center; + + if ( optionalCenter !== undefined ) { + + center.copy( optionalCenter ); + + } else { + + _box$2.setFromPoints( points ).getCenter( center ); + + } + + let maxRadiusSq = 0; + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + + } + + this.radius = Math.sqrt( maxRadiusSq ); + + return this; + + } + + copy( sphere ) { + + this.center.copy( sphere.center ); + this.radius = sphere.radius; + + return this; + + } + + isEmpty() { + + return ( this.radius < 0 ); + + } + + makeEmpty() { + + this.center.set( 0, 0, 0 ); + this.radius = - 1; + + return this; + + } + + containsPoint( point ) { + + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + + } + + distanceToPoint( point ) { + + return ( point.distanceTo( this.center ) - this.radius ); + + } + + intersectsSphere( sphere ) { + + const radiusSum = this.radius + sphere.radius; + + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + + } + + intersectsBox( box ) { + + return box.intersectsSphere( this ); + + } + + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + + } + + clampPoint( point, target ) { + + const deltaLengthSq = this.center.distanceToSquared( point ); + + target.copy( point ); + + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); + + } + + return target; + + } + + getBoundingBox( target ) { + + if ( this.isEmpty() ) { + + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; + + } + + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); + + return target; + + } + + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + + return this; + + } + + translate( offset ) { + + this.center.add( offset ); + + return this; + + } + + expandByPoint( point ) { + + if ( this.isEmpty() ) { + + this.center.copy( point ); + + this.radius = 0; + + return this; + + } + + _v1$6.subVectors( point, this.center ); + + const lengthSq = _v1$6.lengthSq(); + + if ( lengthSq > ( this.radius * this.radius ) ) { + + // calculate the minimal sphere + + const length = Math.sqrt( lengthSq ); + + const delta = ( length - this.radius ) * 0.5; + + this.center.addScaledVector( _v1$6, delta / length ); + + this.radius += delta; + + } + + return this; + + } + + union( sphere ) { + + if ( sphere.isEmpty() ) { + + return this; + + } + + if ( this.isEmpty() ) { + + this.copy( sphere ); + + return this; + + } + + if ( this.center.equals( sphere.center ) === true ) { + + this.radius = Math.max( this.radius, sphere.radius ); + + } else { + + _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius ); + + this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) ); + + this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) ); + + } + + return this; + + } + + equals( sphere ) { + + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$a = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); + +const _edge1 = /*@__PURE__*/ new Vector3(); +const _edge2 = /*@__PURE__*/ new Vector3(); +const _normal$1 = /*@__PURE__*/ new Vector3(); + +class Ray { + + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) { + + this.origin = origin; + this.direction = direction; + + } + + set( origin, direction ) { + + this.origin.copy( origin ); + this.direction.copy( direction ); + + return this; + + } + + copy( ray ) { + + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); + + return this; + + } + + at( t, target ) { + + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + + } + + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); + + return this; + + } + + recast( t ) { + + this.origin.copy( this.at( t, _vector$a ) ); + + return this; + + } + + closestPointToPoint( point, target ) { + + target.subVectors( point, this.origin ); + + const directionDistance = target.dot( this.direction ); + + if ( directionDistance < 0 ) { + + return target.copy( this.origin ); + + } + + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + } + + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); + + } + + distanceSqToPoint( point ) { + + const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction ); + + // point behind the ray + + if ( directionDistance < 0 ) { + + return this.origin.distanceToSquared( point ); + + } + + _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + + return _vector$a.distanceToSquared( point ); + + } + + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + + // from https://github.com/pmjoniak/GeometricTools/blob/master/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 + + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); + + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; + + if ( det > 0 ) { + + // The ray and segment are not parallel. + + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { + + if ( s1 >= - extDet ) { + + if ( s1 <= extDet ) { + + // region 0 + // Minimum at interior points of ray and segment. + + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + + } else { + + // region 1 + + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + if ( s1 <= - extDet ) { + + // 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 ) { + + // region 3 + + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; + + } else { + + // region 2 + + 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 { + + // Ray and segment are parallel. + + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + if ( optionalPointOnRay ) { + + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + + } + + if ( optionalPointOnSegment ) { + + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + + } + + return sqrDist; + + } + + intersectSphere( sphere, target ) { + + _vector$a.subVectors( sphere.center, this.origin ); + const tca = _vector$a.dot( this.direction ); + const d2 = _vector$a.dot( _vector$a ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + const thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + const 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; + + // 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, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); + + } + + intersectsSphere( sphere ) { + + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + distanceToPlane( plane ) { + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { + + return 0; + + } + + // Null is preferable to undefined since undefined means.... it is undefined + + return null; + + } + + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + + // Return if the ray never intersects the plane + + return t >= 0 ? t : null; + + } + + intersectPlane( plane, target ) { + + const t = this.distanceToPlane( plane ); + + if ( t === null ) { + + return null; + + } + + return this.at( t, target ); + + } + + intersectsPlane( plane ) { + + // check if the ray lies on the plane first + + const distToPoint = plane.distanceToPoint( this.origin ); + + if ( distToPoint === 0 ) { + + return true; + + } + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator * distToPoint < 0 ) { + + return true; + + } + + // ray origin is behind the plane (and is pointing behind it) + + return false; + + } + + intersectBox( box, target ) { + + let tmin, tmax, tymin, tymax, tzmin, tzmax; + + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; + + const origin = this.origin; + + if ( invdirx >= 0 ) { + + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; + + } else { + + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + + } + + if ( invdiry >= 0 ) { + + 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; + + } + + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + + if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin; + + if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; + + } else { + + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + + } + + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + + //return point closest to the ray (positive side) + + if ( tmax < 0 ) return null; + + return this.at( tmin >= 0 ? tmin : tmax, target ); + + } + + intersectsBox( box ) { + + return this.intersectBox( box, _vector$a ) !== null; + + } + + intersectTriangle( a, b, c, backfaceCulling, target ) { + + // Compute the offset origin, edges, and normal. + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal$1.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) + let DdN = this.direction.dot( _normal$1 ); + let sign; + + if ( DdN > 0 ) { + + if ( backfaceCulling ) return null; + sign = 1; + + } else if ( DdN < 0 ) { + + sign = - 1; + DdN = - DdN; + + } else { + + return null; + + } + + _diff.subVectors( this.origin, a ); + const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { + + return null; + + } + + const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { + + return null; + + } + + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { + + return null; + + } + + // Line intersects triangle, check if ray does. + const QdN = - sign * _diff.dot( _normal$1 ); + + // t < 0, no intersection + if ( QdN < 0 ) { + + return null; + + } + + // Ray intersects triangle. + return this.at( QdN / DdN, target ); + + } + + applyMatrix4( matrix4 ) { + + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); + + return this; + + } + + equals( ray ) { + + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class Matrix4 { + + constructor() { + + Matrix4.prototype.isMatrix4 = true; + + this.elements = [ + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ]; + + } + + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + const 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; + + return this; + + } + + identity() { + + this.set( + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + clone() { + + return new Matrix4().fromArray( this.elements ); + + } + + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + + return this; + + } + + copyPosition( m ) { + + const te = this.elements, me = m.elements; + + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; + + return this; + + } + + setFromMatrix3( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); + + return this; + + } + + makeBasis( xAxis, yAxis, zAxis ) { + + 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; + + } + + extractRotation( m ) { + + // this method does not support reflection matrices + + const te = this.elements; + const me = m.elements; + + const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length(); + + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; + + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; + + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; + + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromEuler( euler ) { + + const te = this.elements; + + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); + + if ( euler.order === 'XYZ' ) { + + const ae = a * e, af = a * f, be = b * e, bf = b * f; + + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; + + 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; + + } else if ( euler.order === 'YXZ' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZXY' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + 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; + + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZYX' ) { + + const 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; + + 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; + + } else if ( euler.order === 'YZX' ) { + + const 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' ) { + + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; + + 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; + + } + + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; + + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + makeRotationFromQuaternion( q ) { + + return this.compose( _zero, q, _one ); + + } + + lookAt( eye, target, up ) { + + const te = this.elements; + + _z.subVectors( eye, target ); + + if ( _z.lengthSq() === 0 ) { + + // eye and target are in the same position + + _z.z = 1; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + if ( _x.lengthSq() === 0 ) { + + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { + + _z.x += 0.0001; + + } else { + + _z.z += 0.0001; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + } + + _x.normalize(); + _y.crossVectors( _z, _x ); + + 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; + + return this; + + } + + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const 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; + + 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; + + } + + multiplyScalar( s ) { + + const 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; + + } + + determinant() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + + 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 + ) + + ); + + } + + transpose() { + + const te = this.elements; + let 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; + + 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; + + } + + setPosition( x, y, z ) { + + const te = this.elements; + + if ( x.isVector3 ) { + + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; + + } else { + + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; + + } + + return this; + + } + + invert() { + + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 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; + + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + 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; + + 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; + + 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; + + return this; + + } + + scale( v ) { + + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + + 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; + + return this; + + } + + getMaxScaleOnAxis() { + + const te = this.elements; + + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + + } + + makeTranslation( x, y, z ) { + + this.set( + + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationX( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationY( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationZ( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeRotationAxis( axis, angle ) { + + // Based on http://www.gamedev.net/reference/articles/article1199.asp + + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + + this.set( + + 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 + + ); + + return this; + + } + + makeScale( x, y, z ) { + + this.set( + + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + makeShear( xy, xz, yx, yz, zx, zy ) { + + this.set( + + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + compose( position, quaternion, scale ) { + + const te = this.elements; + + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + + const sx = scale.x, sy = scale.y, sz = scale.z; + + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; + + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; + + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; + + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; + + return this; + + } + + decompose( position, quaternion, scale ) { + + const te = this.elements; + + let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + + // if determine is negative, we need to invert one scale + const det = this.determinant(); + if ( det < 0 ) sx = - sx; + + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; + + // scale the rotation part + _m1$2.copy( this ); + + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; + + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; + + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; + + quaternion.setFromRotationMatrix( _m1$2 ); + + scale.x = sx; + scale.y = sy; + scale.z = sz; + + return this; + + } + + makePerspective( left, right, top, bottom, near, far ) { + + const te = this.elements; + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); + + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + const c = - ( far + near ) / ( far - near ); + const 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; + + return this; + + } + + makeOrthographic( left, right, top, bottom, near, far ) { + + const te = this.elements; + const w = 1.0 / ( right - left ); + const h = 1.0 / ( top - bottom ); + const p = 1.0 / ( far - near ); + + const x = ( right + left ) * w; + const y = ( top + bottom ) * h; + const 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; + + return this; + + } + + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 16; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 16; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + 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 ]; + 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 ]; + + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; + + return array; + + } + +} + +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); + +const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _quaternion$3 = /*@__PURE__*/ new Quaternion(); + +class Euler { + + constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) { + + this.isEuler = true; + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + } + + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + get order() { + + return this._order; + + } + + set order( value ) { + + this._order = value; + this._onChangeCallback(); + + } + + set( x, y, z, order = this._order ) { + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + this._onChangeCallback(); + + return this; + + } + + clone() { + + return new this.constructor( this._x, this._y, this._z, this._order ); + + } + + copy( euler ) { + + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + + this._onChangeCallback(); + + return this; + + } + + setFromRotationMatrix( m, order = this._order, update = true ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + switch ( order ) { + + case 'XYZ': + + this._y = Math.asin( clamp( m13, - 1, 1 ) ); + + if ( Math.abs( m13 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); + + } else { + + this._x = Math.atan2( m32, m22 ); + this._z = 0; + + } + + break; + + case 'YXZ': + + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + + if ( Math.abs( m23 ) < 0.9999999 ) { + + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); + + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; + + } + + break; + + case 'ZXY': + + this._x = Math.asin( clamp( m32, - 1, 1 ) ); + + if ( Math.abs( m32 ) < 0.9999999 ) { + + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); + + } else { + + this._y = 0; + this._z = Math.atan2( m21, m11 ); + + } + + break; + + case 'ZYX': + + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + + if ( Math.abs( m31 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); + + } else { + + this._x = 0; + this._z = Math.atan2( - m12, m22 ); + + } + + break; + + case 'YZX': + + this._z = Math.asin( clamp( m21, - 1, 1 ) ); + + if ( Math.abs( m21 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); + + } else { + + this._x = 0; + this._y = Math.atan2( m13, m33 ); + + } + + break; + + case 'XZY': + + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + + if ( Math.abs( m12 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); + + } else { + + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + break; + + default: + + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + + } + + this._order = order; + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + setFromQuaternion( q, order, update ) { + + _matrix$1.makeRotationFromQuaternion( q ); + + return this.setFromRotationMatrix( _matrix$1, order, update ); + + } + + setFromVector3( v, order = this._order ) { + + return this.set( v.x, v.y, v.z, order ); + + } + + reorder( newOrder ) { + + // WARNING: this discards revolution information -bhouston + + _quaternion$3.setFromEuler( this ); + + return this.setFromQuaternion( _quaternion$3, newOrder ); + + } + + equals( euler ) { + + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + + } + + fromArray( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + + this._onChangeCallback(); + + return this; + + } + + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; + + return array; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + +} + +Euler.DEFAULT_ORDER = 'XYZ'; + +class Layers { + + constructor() { + + this.mask = 1 | 0; + + } + + set( channel ) { + + this.mask = ( 1 << channel | 0 ) >>> 0; + + } + + enable( channel ) { + + this.mask |= 1 << channel | 0; + + } + + enableAll() { + + this.mask = 0xffffffff | 0; + + } + + toggle( channel ) { + + this.mask ^= 1 << channel | 0; + + } + + disable( channel ) { + + this.mask &= ~ ( 1 << channel | 0 ); + + } + + disableAll() { + + this.mask = 0; + + } + + test( layers ) { + + return ( this.mask & layers.mask ) !== 0; + + } + + isEnabled( channel ) { + + return ( this.mask & ( 1 << channel | 0 ) ) !== 0; + + } + +} + +let _object3DId = 0; + +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); + +const _position$3 = /*@__PURE__*/ new Vector3(); +const _scale$2 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); + +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); + +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; + +class Object3D extends EventDispatcher { + + constructor() { + + super(); + + this.isObject3D = true; + + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Object3D'; + + this.parent = null; + this.children = []; + + this.up = Object3D.DEFAULT_UP.clone(); + + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); + + function onRotationChange() { + + quaternion.setFromEuler( rotation, false ); + + } + + function onQuaternionChange() { + + rotation.setFromQuaternion( quaternion, undefined, false ); + + } + + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); + + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); + + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer + + this.layers = new Layers(); + this.visible = true; + + this.castShadow = false; + this.receiveShadow = false; + + this.frustumCulled = true; + this.renderOrder = 0; + + this.animations = []; + + this.userData = {}; + + } + + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + applyMatrix4( matrix ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + this.matrix.premultiply( matrix ); + + this.matrix.decompose( this.position, this.quaternion, this.scale ); + + } + + applyQuaternion( q ) { + + this.quaternion.premultiply( q ); + + return this; + + } + + setRotationFromAxisAngle( axis, angle ) { + + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); + + } + + setRotationFromEuler( euler ) { + + this.quaternion.setFromEuler( euler, true ); + + } + + setRotationFromMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + this.quaternion.setFromRotationMatrix( m ); + + } + + setRotationFromQuaternion( q ) { + + // assumes q is normalized + + this.quaternion.copy( q ); + + } + + rotateOnAxis( axis, angle ) { + + // rotate object on axis in object space + // axis is assumed to be normalized + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.multiply( _q1 ); + + return this; + + } + + rotateOnWorldAxis( axis, angle ) { + + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.premultiply( _q1 ); + + return this; + + } + + rotateX( angle ) { + + return this.rotateOnAxis( _xAxis, angle ); + + } + + rotateY( angle ) { + + return this.rotateOnAxis( _yAxis, angle ); + + } + + rotateZ( angle ) { + + return this.rotateOnAxis( _zAxis, angle ); + + } + + translateOnAxis( axis, distance ) { + + // translate object by distance along axis in object space + // axis is assumed to be normalized + + _v1$4.copy( axis ).applyQuaternion( this.quaternion ); + + this.position.add( _v1$4.multiplyScalar( distance ) ); + + return this; + + } + + translateX( distance ) { + + return this.translateOnAxis( _xAxis, distance ); + + } + + translateY( distance ) { + + return this.translateOnAxis( _yAxis, distance ); + + } + + translateZ( distance ) { + + return this.translateOnAxis( _zAxis, distance ); + + } + + localToWorld( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( this.matrixWorld ); + + } + + worldToLocal( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + + } + + lookAt( x, y, z ) { + + // This method does not support objects having non-uniformly-scaled parent(s) + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + const parent = this.parent; + + this.updateWorldMatrix( true, false ); + + _position$3.setFromMatrixPosition( this.matrixWorld ); + + if ( this.isCamera || this.isLight ) { + + _m1$1.lookAt( _position$3, _target, this.up ); + + } else { + + _m1$1.lookAt( _target, _position$3, this.up ); + + } + + this.quaternion.setFromRotationMatrix( _m1$1 ); + + if ( parent ) { + + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); + + } + + } + + add( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + } + + if ( object === this ) { + + console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object ); + return this; + + } + + if ( object && object.isObject3D ) { + + if ( object.parent !== null ) { + + object.parent.remove( object ); + + } + + object.parent = this; + this.children.push( object ); + + object.dispatchEvent( _addedEvent ); + + } else { + + console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object ); + + } + + return this; + + } + + remove( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.remove( arguments[ i ] ); + + } + + return this; + + } + + const index = this.children.indexOf( object ); + + if ( index !== - 1 ) { + + object.parent = null; + this.children.splice( index, 1 ); + + object.dispatchEvent( _removedEvent ); + + } + + return this; + + } + + removeFromParent() { + + const parent = this.parent; + + if ( parent !== null ) { + + parent.remove( this ); + + } + + return this; + + } + + clear() { + + for ( let i = 0; i < this.children.length; i ++ ) { + + const object = this.children[ i ]; + + object.parent = null; + + object.dispatchEvent( _removedEvent ); + + } + + this.children.length = 0; + + return this; + + + } + + attach( object ) { + + // adds object as a child of this, while maintaining the object's world transform + + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + + this.updateWorldMatrix( true, false ); + + _m1$1.copy( this.matrixWorld ).invert(); + + if ( object.parent !== null ) { + + object.parent.updateWorldMatrix( true, false ); + + _m1$1.multiply( object.parent.matrixWorld ); + + } + + object.applyMatrix4( _m1$1 ); + + this.add( object ); + + object.updateWorldMatrix( false, true ); + + return this; + + } + + getObjectById( id ) { + + return this.getObjectByProperty( 'id', id ); + + } + + getObjectByName( name ) { + + return this.getObjectByProperty( 'name', name ); + + } + + getObjectByProperty( name, value ) { + + if ( this[ name ] === value ) return this; + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); + + if ( object !== undefined ) { + + return object; + + } + + } + + return undefined; + + } + + getObjectsByProperty( name, value ) { + + let result = []; + + if ( this[ name ] === value ) result.push( this ); + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const childResult = this.children[ i ].getObjectsByProperty( name, value ); + + if ( childResult.length > 0 ) { + + result = result.concat( childResult ); + + } + + } + + return result; + + } + + getWorldPosition( target ) { + + this.updateWorldMatrix( true, false ); + + return target.setFromMatrixPosition( this.matrixWorld ); + + } + + getWorldQuaternion( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, target, _scale$2 ); + + return target; + + } + + getWorldScale( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$3, _quaternion$2, target ); + + return target; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + + } + + raycast( /* raycaster, intersects */ ) {} + + traverse( callback ) { + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverse( callback ); + + } + + } + + traverseVisible( callback ) { + + if ( this.visible === false ) return; + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverseVisible( callback ); + + } + + } + + traverseAncestors( callback ) { + + const parent = this.parent; + + if ( parent !== null ) { + + callback( parent ); + + parent.traverseAncestors( callback ); + + } + + } + + updateMatrix() { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + this.matrixWorldNeedsUpdate = true; + + } + + updateMatrixWorld( force ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // update children + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true || force === true ) { + + child.updateMatrixWorld( force ); + + } + + } + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + const parent = this.parent; + + if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) { + + parent.updateWorldMatrix( true, false ); + + } + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + // update children + + if ( updateChildren === true ) { + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + if ( child.matrixWorldAutoUpdate === true ) { + + child.updateWorldMatrix( false, true ); + + } + + } + + } + + } + + toJSON( meta ) { + + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + const output = {}; + + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { + + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; + + } + + // standard Object3D serialization + + const object = {}; + + object.uuid = this.uuid; + object.type = this.type; + + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData; + + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; + + // object specific properties + + if ( this.isInstancedMesh ) { + + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); + + } + + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); + + } + + return element.uuid; + + } + + if ( this.isScene ) { + + if ( this.background ) { + + if ( this.background.isColor ) { + + object.background = this.background.toJSON(); + + } else if ( this.background.isTexture ) { + + object.background = this.background.toJSON( meta ).uuid; + + } + + } + + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { + + object.environment = this.environment.toJSON( meta ).uuid; + + } + + } else if ( this.isMesh || this.isLine || this.isPoints ) { + + object.geometry = serialize( meta.geometries, this.geometry ); + + const parameters = this.geometry.parameters; + + if ( parameters !== undefined && parameters.shapes !== undefined ) { + + const shapes = parameters.shapes; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + serialize( meta.shapes, shape ); + + } + + } else { + + serialize( meta.shapes, shapes ); + + } + + } + + } + + if ( this.isSkinnedMesh ) { + + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + + if ( this.skeleton !== undefined ) { + + serialize( meta.skeletons, this.skeleton ); + + object.skeleton = this.skeleton.uuid; + + } + + } + + if ( this.material !== undefined ) { + + if ( Array.isArray( this.material ) ) { + + const uuids = []; + + for ( let i = 0, l = this.material.length; i < l; i ++ ) { + + uuids.push( serialize( meta.materials, this.material[ i ] ) ); + + } + + object.material = uuids; + + } else { + + object.material = serialize( meta.materials, this.material ); + + } + + } + + // + + if ( this.children.length > 0 ) { + + object.children = []; + + for ( let i = 0; i < this.children.length; i ++ ) { + + object.children.push( this.children[ i ].toJSON( meta ).object ); + + } + + } + + // + + if ( this.animations.length > 0 ) { + + object.animations = []; + + for ( let i = 0; i < this.animations.length; i ++ ) { + + const animation = this.animations[ i ]; + + object.animations.push( serialize( meta.animations, animation ) ); + + } + + } + + if ( isRootObject ) { + + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); + + 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; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; + + } + + output.object = object; + + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { + + const values = []; + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + } + + clone( recursive ) { + + return new this.constructor().copy( this, recursive ); + + } + + copy( source, recursive = true ) { + + this.name = source.name; + + this.up.copy( source.up ); + + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); + + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + + this.layers.mask = source.layers.mask; + this.visible = source.visible; + + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { + + for ( let i = 0; i < source.children.length; i ++ ) { + + const child = source.children[ i ]; + this.add( child.clone() ); + + } + + } + + return this; + + } + +} + +Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); +const _v3$1 = /*@__PURE__*/ new Vector3(); + +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); + +class Triangle { + + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + + this.a = a; + this.b = b; + this.c = c; + + } + + static getNormal( a, b, c, target ) { + + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); + + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { + + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + + } + + return target.set( 0, 0, 0 ); + + } + + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord( point, a, b, c, target ) { + + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$2.subVectors( point, a ); + + const dot00 = _v0$1.dot( _v0$1 ); + const dot01 = _v0$1.dot( _v1$3 ); + const dot02 = _v0$1.dot( _v2$2 ); + const dot11 = _v1$3.dot( _v1$3 ); + const dot12 = _v1$3.dot( _v2$2 ); + + const denom = ( dot00 * dot11 - dot01 * dot01 ); + + // 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 target.set( - 2, - 1, - 1 ); + + } + + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); + + } + + static containsPoint( point, a, b, c ) { + + this.getBarycoord( point, a, b, c, _v3$1 ); + + return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 ); + + } + + static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { + + this.getBarycoord( point, p1, p2, p3, _v3$1 ); + + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3$1.x ); + target.addScaledVector( uv2, _v3$1.y ); + target.addScaledVector( uv3, _v3$1.z ); + + return target; + + } + + static isFrontFacing( a, b, c, direction ) { + + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); + + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + + } + + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); + + return this; + + } + + setFromPointsAndIndices( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; + + } + + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { + + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( triangle ) { + + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; + + } + + getArea() { + + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); + + return _v0$1.cross( _v1$3 ).length() * 0.5; + + } + + getMidpoint( target ) { + + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + + } + + getNormal( target ) { + + return Triangle.getNormal( this.a, this.b, this.c, target ); + + } + + getPlane( target ) { + + return target.setFromCoplanarPoints( this.a, this.b, this.c ); + + } + + getBarycoord( point, target ) { + + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + + } + + getUV( point, uv1, uv2, uv3, target ) { + + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + + } + + containsPoint( point ) { + + return Triangle.containsPoint( point, this.a, this.b, this.c ); + + } + + isFrontFacing( direction ) { + + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + + } + + intersectsBox( box ) { + + return box.intersectsTriangle( this ); + + } + + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; + + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. + + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { + + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); + + } + + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { + + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } + + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); + + } + + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { + + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } + + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); + + } + + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + + } + + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; + + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + + } + + equals( triangle ) { + + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + + } + +} + +let materialId = 0; + +class Material extends EventDispatcher { + + constructor() { + + super(); + + this.isMaterial = true; + + Object.defineProperty( this, 'id', { value: materialId ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'Material'; + + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + + 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; + + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + + this.shadowSide = null; + + this.colorWrite = true; + + this.precision = null; // override the renderer's default precision for this material + + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + + this.dithering = false; + + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + + this.visible = true; + + this.toneMapped = true; + + this.userData = {}; + + this.version = 0; + + this._alphaTest = 0; + + } + + get alphaTest() { + + return this._alphaTest; + + } + + set alphaTest( value ) { + + if ( this._alphaTest > 0 !== value > 0 ) { + + this.version ++; + + } + + this._alphaTest = value; + + } + + onBuild( /* shaderobject, renderer */ ) {} + + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} + + onBeforeCompile( /* shaderobject, renderer */ ) {} + + customProgramCacheKey() { + + return this.onBeforeCompile.toString(); + + } + + setValues( values ) { + + if ( values === undefined ) return; + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' ); + continue; + + } + + if ( currentValue && currentValue.isColor ) { + + currentValue.set( newValue ); + + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( isRootObject ) { + + meta = { + textures: {}, + images: {} + }; + + } + + const data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; + + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; + + if ( this.name !== '' ) data.name = this.name; + + 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.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; + + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + + } + + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.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; + data.lightMapIntensity = this.lightMapIntensity; + + } + + if ( this.aoMap && this.aoMap.isTexture ) { + + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; + + } + + if ( this.bumpMap && this.bumpMap.isTexture ) { + + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; + + } + + if ( this.normalMap && this.normalMap.isTexture ) { + + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + + } + + if ( this.displacementMap && this.displacementMap.isTexture ) { + + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + + } + + 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 && 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.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; + + if ( this.envMap && this.envMap.isTexture ) { + + data.envMap = this.envMap.toJSON( meta ).uuid; + + if ( this.combine !== undefined ) data.combine = this.combine; + + } + + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; + + if ( this.gradientMap && this.gradientMap.isTexture ) { + + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + + } + + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); + + if ( this.size !== undefined ) data.size = this.size; + if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; + + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; + + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; + + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; + + // rotation (SpriteMaterial) + if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation; + + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; + + if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; + + if ( this.dithering === true ) data.dithering = true; + + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; + + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + + if ( this.flatShading === true ) data.flatShading = this.flatShading; + + if ( this.visible === false ) data.visible = false; + + if ( this.toneMapped === false ) data.toneMapped = false; + + if ( this.fog === false ) data.fog = false; + + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + // TODO: Copied from Object3D.toJSON + + function extractFromCache( cache ) { + + const values = []; + + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + if ( isRootObject ) { + + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.name = source.name; + + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + + if ( srcPlanes !== null ) { + + const n = srcPlanes.length; + dstPlanes = new Array( n ); + + for ( let i = 0; i !== n; ++ i ) { + + dstPlanes[ i ] = srcPlanes[ i ].clone(); + + } + + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +class MeshBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + this.color = new Color( 0xffffff ); // emissive + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + 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'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _vector$9 = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector2(); + +class BufferAttribute { + + constructor( array, itemSize, normalized = false ) { + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + + } + + this.isBufferAttribute = true; + + this.name = ''; + + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.itemSize; + index2 *= attribute.itemSize; + + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + copyArray( array ) { + + this.array.set( array ); + + return this; + + } + + applyMatrix3( m ) { + + if ( this.itemSize === 2 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector2$1.fromBufferAttribute( this, i ); + _vector2$1.applyMatrix3( m ); + + this.setXY( i, _vector2$1.x, _vector2$1.y ); + + } + + } else if ( this.itemSize === 3 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + _vector$9.applyMatrix3( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + } + + return this; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyMatrix4( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$9.fromBufferAttribute( this, i ); + + _vector$9.transformDirection( m ); + + this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + return this; + + } + + set( value, offset = 0 ) { + + // Matching BufferAttribute constructor, do not normalize the array. + this.array.set( value, offset ); + + return this; + + } + + getX( index ) { + + let x = this.array[ index * this.itemSize ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = x; + + return this; + + } + + getY( index ) { + + let y = this.array[ index * this.itemSize + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = y; + + return this; + + } + + getZ( index ) { + + let z = this.array[ index * this.itemSize + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = z; + + return this; + + } + + getW( index ) { + + let w = this.array[ index * this.itemSize + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = w; + + return this; + + } + + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; + + return this; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + clone() { + + return new this.constructor( this.array, this.itemSize ).copy( this ); + + } + + toJSON() { + + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from( this.array ), + normalized: this.normalized + }; + + if ( this.name !== '' ) data.name = this.name; + if ( this.usage !== StaticDrawUsage ) data.usage = this.usage; + if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange; + + return data; + + } + + // @deprecated + + copyColorsArray() { + + console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' ); + + } + + copyVector2sArray() { + + console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' ); + + } + + copyVector3sArray() { + + console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' ); + + } + + copyVector4sArray() { + + console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' ); + + } + +} + +// + +class Int8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int8Array( array ), itemSize, normalized ); + + } + +} + +class Uint8BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8Array( array ), itemSize, normalized ); + + } + +} + +class Uint8ClampedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint8ClampedArray( array ), itemSize, normalized ); + + } + +} + +class Int16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int16Array( array ), itemSize, normalized ); + + } + +} + +class Uint16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + } + +} + +class Int32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Int32Array( array ), itemSize, normalized ); + + } + +} + +class Uint32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint32Array( array ), itemSize, normalized ); + + } + +} + +class Float16BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + this.isFloat16BufferAttribute = true; + + } + +} + + +class Float32BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } + +} + +class Float64BufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized ) { + + super( new Float64Array( array ), itemSize, normalized ); + + } + +} + +let _id$1 = 0; + +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box$1 = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$8 = /*@__PURE__*/ new Vector3(); + +class BufferGeometry extends EventDispatcher { + + constructor() { + + super(); + + this.isBufferGeometry = true; + + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); + + this.uuid = generateUUID(); + + this.name = ''; + this.type = 'BufferGeometry'; + + this.index = null; + this.attributes = {}; + + this.morphAttributes = {}; + this.morphTargetsRelative = false; + + this.groups = []; + + this.boundingBox = null; + this.boundingSphere = null; + + this.drawRange = { start: 0, count: Infinity }; + + this.userData = {}; + + } + + getIndex() { + + return this.index; + + } + + setIndex( index ) { + + if ( Array.isArray( index ) ) { + + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; + + } + + return this; + + } + + getAttribute( name ) { + + return this.attributes[ name ]; + + } + + setAttribute( name, attribute ) { + + this.attributes[ name ] = attribute; + + return this; + + } + + deleteAttribute( name ) { + + delete this.attributes[ name ]; + + return this; + + } + + hasAttribute( name ) { + + return this.attributes[ name ] !== undefined; + + } + + addGroup( start, count, materialIndex = 0 ) { + + this.groups.push( { + + start: start, + count: count, + materialIndex: materialIndex + + } ); + + } + + clearGroups() { + + this.groups = []; + + } + + setDrawRange( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; + + } + + applyMatrix4( matrix ) { + + const position = this.attributes.position; + + if ( position !== undefined ) { + + position.applyMatrix4( matrix ); + + position.needsUpdate = true; + + } + + const normal = this.attributes.normal; + + if ( normal !== undefined ) { + + const normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + normal.applyNormalMatrix( normalMatrix ); + + normal.needsUpdate = true; + + } + + const tangent = this.attributes.tangent; + + if ( tangent !== undefined ) { + + tangent.transformDirection( matrix ); + + tangent.needsUpdate = true; + + } + + if ( this.boundingBox !== null ) { + + this.computeBoundingBox(); + + } + + if ( this.boundingSphere !== null ) { + + this.computeBoundingSphere(); + + } + + return this; + + } + + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateX( angle ) { + + // rotate geometry around world x-axis + + _m1.makeRotationX( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateY( angle ) { + + // rotate geometry around world y-axis + + _m1.makeRotationY( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + rotateZ( angle ) { + + // rotate geometry around world z-axis + + _m1.makeRotationZ( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + translate( x, y, z ) { + + // translate geometry + + _m1.makeTranslation( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + scale( x, y, z ) { + + // scale geometry + + _m1.makeScale( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + lookAt( vector ) { + + _obj.lookAt( vector ); + + _obj.updateMatrix(); + + this.applyMatrix4( _obj.matrix ); + + return this; + + } + + center() { + + this.computeBoundingBox(); + + this.boundingBox.getCenter( _offset ).negate(); + + this.translate( _offset.x, _offset.y, _offset.z ); + + return this; + + } + + setFromPoints( points ) { + + const position = []; + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + const point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } + + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + return this; + + } + + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingBox.set( + new Vector3( - Infinity, - Infinity, - Infinity ), + new Vector3( + Infinity, + Infinity, + Infinity ) + ); + + return; + + } + + if ( position !== undefined ) { + + this.boundingBox.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _box$1.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( this.boundingBox.min, _box$1.min ); + this.boundingBox.expandByPoint( _vector$8 ); + + _vector$8.addVectors( this.boundingBox.max, _box$1.max ); + this.boundingBox.expandByPoint( _vector$8 ); + + } else { + + this.boundingBox.expandByPoint( _box$1.min ); + this.boundingBox.expandByPoint( _box$1.max ); + + } + + } + + } + + } else { + + this.boundingBox.makeEmpty(); + + } + + 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 ); + + } + + } + + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this ); + + this.boundingSphere.set( new Vector3(), Infinity ); + + return; + + } + + if ( position ) { + + // first, find the center of the bounding sphere + + const center = this.boundingSphere.center; + + _box$1.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$8.addVectors( _box$1.min, _boxMorphTargets.min ); + _box$1.expandByPoint( _vector$8 ); + + _vector$8.addVectors( _box$1.max, _boxMorphTargets.max ); + _box$1.expandByPoint( _vector$8 ); + + } else { + + _box$1.expandByPoint( _boxMorphTargets.min ); + _box$1.expandByPoint( _boxMorphTargets.max ); + + } + + } + + } + + _box$1.getCenter( center ); + + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + + let maxRadiusSq = 0; + + for ( let i = 0, il = position.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( position, i ); + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + const morphTargetsRelative = this.morphTargetsRelative; + + for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + + _vector$8.fromBufferAttribute( morphAttribute, j ); + + if ( morphTargetsRelative ) { + + _offset.fromBufferAttribute( position, j ); + _vector$8.add( _offset ); + + } + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) ); + + } + + } + + } + + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + + if ( isNaN( this.boundingSphere.radius ) ) { + + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + } + + computeTangents() { + + const index = this.index; + const attributes = this.attributes; + + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) + + if ( index === null || + attributes.position === undefined || + attributes.normal === undefined || + attributes.uv === undefined ) { + + console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' ); + return; + + } + + const indices = index.array; + const positions = attributes.position.array; + const normals = attributes.normal.array; + const uvs = attributes.uv.array; + + const nVertices = positions.length / 3; + + if ( this.hasAttribute( 'tangent' ) === false ) { + + this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); + + } + + const tangents = this.getAttribute( 'tangent' ).array; + + const tan1 = [], tan2 = []; + + for ( let i = 0; i < nVertices; i ++ ) { + + tan1[ i ] = new Vector3(); + tan2[ i ] = new Vector3(); + + } + + const vA = new Vector3(), + vB = new Vector3(), + vC = new Vector3(), + + uvA = new Vector2(), + uvB = new Vector2(), + uvC = new Vector2(), + + sdir = new Vector3(), + tdir = new Vector3(); + + function handleTriangle( a, b, c ) { + + vA.fromArray( positions, a * 3 ); + vB.fromArray( positions, b * 3 ); + vC.fromArray( positions, c * 3 ); + + uvA.fromArray( uvs, a * 2 ); + uvB.fromArray( uvs, b * 2 ); + uvC.fromArray( uvs, c * 2 ); + + vB.sub( vA ); + vC.sub( vA ); + + uvB.sub( uvA ); + uvC.sub( uvA ); + + const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); + + // silently ignore degenerate uv triangles having coincident or colinear vertices + + if ( ! isFinite( r ) ) return; + + sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); + tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); + + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); + + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); + + } + + let groups = this.groups; + + if ( groups.length === 0 ) { + + groups = [ { + start: 0, + count: indices.length + } ]; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleTriangle( + indices[ j + 0 ], + indices[ j + 1 ], + indices[ j + 2 ] + ); + + } + + } + + const tmp = new Vector3(), tmp2 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + + function handleVertex( v ) { + + n.fromArray( normals, v * 3 ); + n2.copy( n ); + + const t = tan1[ v ]; + + // Gram-Schmidt orthogonalize + + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + + // Calculate handedness + + tmp2.crossVectors( n2, t ); + const test = tmp2.dot( tan2[ v ] ); + const w = ( test < 0.0 ) ? - 1.0 : 1.0; + + tangents[ v * 4 ] = tmp.x; + tangents[ v * 4 + 1 ] = tmp.y; + tangents[ v * 4 + 2 ] = tmp.z; + tangents[ v * 4 + 3 ] = w; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleVertex( indices[ j + 0 ] ); + handleVertex( indices[ j + 1 ] ); + handleVertex( indices[ j + 2 ] ); + + } + + } + + } + + computeVertexNormals() { + + const index = this.index; + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute !== undefined ) { + + let normalAttribute = this.getAttribute( 'normal' ); + + if ( normalAttribute === undefined ) { + + normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 ); + this.setAttribute( 'normal', normalAttribute ); + + } else { + + // reset existing normals to zero + + for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) { + + normalAttribute.setXYZ( i, 0, 0, 0 ); + + } + + } + + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + + // indexed elements + + if ( index ) { + + for ( let i = 0, il = index.count; i < il; i += 3 ) { + + const vA = index.getX( i + 0 ); + const vB = index.getX( i + 1 ); + const vC = index.getX( i + 2 ); + + pA.fromBufferAttribute( positionAttribute, vA ); + pB.fromBufferAttribute( positionAttribute, vB ); + pC.fromBufferAttribute( positionAttribute, vC ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + nA.fromBufferAttribute( normalAttribute, vA ); + nB.fromBufferAttribute( normalAttribute, vB ); + nC.fromBufferAttribute( normalAttribute, vC ); + + nA.add( cb ); + nB.add( cb ); + nC.add( cb ); + + normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z ); + normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z ); + normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z ); + + } + + } else { + + // non-indexed elements (unconnected triangle soup) + + for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) { + + pA.fromBufferAttribute( positionAttribute, i + 0 ); + pB.fromBufferAttribute( positionAttribute, i + 1 ); + pC.fromBufferAttribute( positionAttribute, i + 2 ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z ); + + } + + } + + this.normalizeNormals(); + + normalAttribute.needsUpdate = true; + + } + + } + + // @deprecated since r144 + + merge() { + + console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' ); + return this; + + } + + normalizeNormals() { + + const normals = this.attributes.normal; + + for ( let i = 0, il = normals.count; i < il; i ++ ) { + + _vector$8.fromBufferAttribute( normals, i ); + + _vector$8.normalize(); + + normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + } + + toNonIndexed() { + + function convertBufferAttribute( attribute, indices ) { + + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array2 = new array.constructor( indices.length * itemSize ); + + let index = 0, index2 = 0; + + for ( let i = 0, l = indices.length; i < l; i ++ ) { + + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } + + for ( let j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + return new BufferAttribute( array2, itemSize, normalized ); + + } + + // + + if ( this.index === null ) { + + console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' ); + return this; + + } + + const geometry2 = new BufferGeometry(); + + const indices = this.index.array; + const attributes = this.attributes; + + // attributes + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + geometry2.setAttribute( name, newAttribute ); + + } + + // morph attributes + + const morphAttributes = this.morphAttributes; + + for ( const name in morphAttributes ) { + + const morphArray = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const attribute = morphAttribute[ i ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + morphArray.push( newAttribute ); + + } + + geometry2.morphAttributes[ name ] = morphArray; + + } + + geometry2.morphTargetsRelative = this.morphTargetsRelative; + + // groups + + const groups = this.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); + + } + + return geometry2; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; + + // standard BufferGeometry serialization + + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + if ( this.parameters !== undefined ) { + + const parameters = this.parameters; + + for ( const key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + + } + + return data; + + } + + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + + data.data = { attributes: {} }; + + const index = this.index; + + if ( index !== null ) { + + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; + + } + + const attributes = this.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + + data.data.attributes[ key ] = attribute.toJSON( data.data ); + + } + + const morphAttributes = {}; + let hasMorphAttributes = false; + + for ( const key in this.morphAttributes ) { + + const attributeArray = this.morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + + array.push( attribute.toJSON( data.data ) ); + + } + + if ( array.length > 0 ) { + + morphAttributes[ key ] = array; + + hasMorphAttributes = true; + + } + + } + + if ( hasMorphAttributes ) { + + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + + } + + const groups = this.groups; + + if ( groups.length > 0 ) { + + data.data.groups = JSON.parse( JSON.stringify( groups ) ); + + } + + const boundingSphere = this.boundingSphere; + + if ( boundingSphere !== null ) { + + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + + } + + return data; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + // reset + + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + + // used for storing cloned, shared data + + const data = {}; + + // name + + this.name = source.name; + + // index + + const index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone( data ) ); + + } + + // attributes + + const attributes = source.attributes; + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone( data ) ); + + } + + // morph attributes + + const morphAttributes = source.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone( data ) ); + + } + + this.morphAttributes[ name ] = array; + + } + + this.morphTargetsRelative = source.morphTargetsRelative; + + // groups + + const groups = source.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); + + } + + // bounding box + + const boundingBox = source.boundingBox; + + if ( boundingBox !== null ) { + + this.boundingBox = boundingBox.clone(); + + } + + // bounding sphere + + const boundingSphere = source.boundingSphere; + + if ( boundingSphere !== null ) { + + this.boundingSphere = boundingSphere.clone(); + + } + + // draw range + + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + + // user data + + this.userData = source.userData; + + // geometry generator parameters + + if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); +const _sphere$3 = /*@__PURE__*/ new Sphere(); + +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); + +const _tempA = /*@__PURE__*/ new Vector3(); +const _morphA = /*@__PURE__*/ new Vector3(); + +const _uvA$1 = /*@__PURE__*/ new Vector2(); +const _uvB$1 = /*@__PURE__*/ new Vector2(); +const _uvC$1 = /*@__PURE__*/ new Vector2(); + +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); + +class Mesh extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { + + super(); + + this.isMesh = true; + + this.type = 'Mesh'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.morphTargetInfluences !== undefined ) { + + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + + } + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + getVertexPosition( index, target ) { + + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + + target.fromBufferAttribute( position, index ); + + const morphInfluences = this.morphTargetInfluences; + + if ( morphPosition && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + + for ( let i = 0, il = morphPosition.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morphAttribute = morphPosition[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morphAttribute, index ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( target ), influence ); + + } + + } + + target.add( _morphA ); + + } + + if ( this.isSkinnedMesh ) { + + this.boneTransform( index, target ); + + } + + return target; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; + + // + + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + + // Check boundingBox before continuing + + if ( geometry.boundingBox !== null ) { + + if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return; + + } + + let intersection; + + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv2 = geometry.attributes.uv2; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } else if ( position !== undefined ) { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = j; + const b = j + 1; + const c = j + 2; + + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = i; + const b = i + 1; + const c = i + 2; + + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } + + } + +} + +function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { + + let intersect; + + if ( material.side === BackSide ) { + + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + + } else { + + intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point ); + + } + + if ( intersect === null ) return null; + + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + + if ( distance < raycaster.near || distance > raycaster.far ) return null; + + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; + +} + +function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) { + + object.getVertexPosition( a, _vA$1 ); + object.getVertexPosition( b, _vB$1 ); + object.getVertexPosition( c, _vC$1 ); + + const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint ); + + if ( intersection ) { + + if ( uv ) { + + _uvA$1.fromBufferAttribute( uv, a ); + _uvB$1.fromBufferAttribute( uv, b ); + _uvC$1.fromBufferAttribute( uv, c ); + + intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + if ( uv2 ) { + + _uvA$1.fromBufferAttribute( uv2, a ); + _uvB$1.fromBufferAttribute( uv2, b ); + _uvC$1.fromBufferAttribute( uv2, c ); + + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ); + + } + + const face = { + a: a, + b: b, + c: c, + normal: new Vector3(), + materialIndex: 0 + }; + + Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal ); + + intersection.face = face; + + } + + return intersection; + +} + +class BoxGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + this.type = 'BoxGeometry'; + + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; + + const scope = this; + + // segments + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let numberOfVertices = 0; + let groupStart = 0; + + // 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 + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + let vertexCounter = 0; + let groupCount = 0; + + const vector = new Vector3(); + + // generate vertices, normals and uvs + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segmentHeight - heightHalf; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segmentWidth - widthHalf; + + // set values to correct vector component + + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; + + // now apply vector to vertex buffer + + vertices.push( vector.x, vector.y, vector.z ); + + // set values to correct vector component + + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; + + // now apply vector to normal buffer + + normals.push( vector.x, vector.y, vector.z ); + + // uvs + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + // counters + + vertexCounter += 1; + + } + + } + + // indices + + // 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 + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // increase counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, materialIndex ); + + // calculate new start value for groups + + groupStart += groupCount; + + // update total number of vertices + + numberOfVertices += vertexCounter; + + } + + } + + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + +} + +/** + * Uniform Utilities + */ + +function cloneUniforms( src ) { + + const dst = {}; + + for ( const u in src ) { + + dst[ u ] = {}; + + for ( const p in src[ u ] ) { + + const property = src[ u ][ p ]; + + if ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ) { + + dst[ u ][ p ] = property.clone(); + + } else if ( Array.isArray( property ) ) { + + dst[ u ][ p ] = property.slice(); + + } else { + + dst[ u ][ p ] = property; + + } + + } + + } + + return dst; + +} + +function mergeUniforms( uniforms ) { + + const merged = {}; + + for ( let u = 0; u < uniforms.length; u ++ ) { + + const tmp = cloneUniforms( uniforms[ u ] ); + + for ( const p in tmp ) { + + merged[ p ] = tmp[ p ]; + + } + + } + + return merged; + +} + +function cloneUniformsGroups( src ) { + + const dst = []; + + for ( let u = 0; u < src.length; u ++ ) { + + dst.push( src[ u ].clone() ); + + } + + return dst; + +} + +function getUnlitUniformColorSpace( renderer ) { + + if ( renderer.getRenderTarget() === null ) { + + // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398 + return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; + + } + + return LinearSRGBColorSpace; + +} + +// Legacy + +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + +class ShaderMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShaderMaterial = true; + + this.type = 'ShaderMaterial'; + + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + + this.linewidth = 1; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + 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 + + 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 + }; + + // 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; + this.uniformsNeedUpdate = false; + + this.glslVersion = null; + + if ( parameters !== undefined ) { + + this.setValues( parameters ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); + + this.defines = Object.assign( {}, source.defines ); + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + + this.extensions = Object.assign( {}, source.extensions ); + + this.glslVersion = source.glslVersion; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.glslVersion = this.glslVersion; + data.uniforms = {}; + + for ( const name in this.uniforms ) { + + const uniform = this.uniforms[ name ]; + const value = uniform.value; + + if ( value && value.isTexture ) { + + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; + + } else if ( value && value.isColor ) { + + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; + + } else if ( value && value.isVector2 ) { + + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; + + } else if ( value && value.isVector3 ) { + + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; + + } else if ( value && value.isVector4 ) { + + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; + + } else if ( value && value.isMatrix3 ) { + + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; + + } else if ( value && value.isMatrix4 ) { + + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; + + } else { + + data.uniforms[ name ] = { + value: value + }; + + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + + } + + } + + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + const extensions = {}; + + for ( const key in this.extensions ) { + + if ( this.extensions[ key ] === true ) extensions[ key ] = true; + + } + + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + + return data; + + } + +} + +class Camera extends Object3D { + + constructor() { + + super(); + + this.isCamera = true; + + this.type = 'Camera'; + + this.matrixWorldInverse = new Matrix4(); + + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); + + return this; + + } + + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + updateWorldMatrix( updateParents, updateChildren ) { + + super.updateWorldMatrix( updateParents, updateChildren ); + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class PerspectiveCamera extends Camera { + + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + this.fov = fov; + this.zoom = 1; + + this.near = near; + this.far = far; + this.focus = 10; + + this.aspect = aspect; + this.view = null; + + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + 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( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * 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 + * + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( 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( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const near = this.near; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = - 0.5 * width; + const view = this.view; + + if ( this.view !== null && this.view.enabled ) { + + const fullWidth = view.fullWidth, + fullHeight = view.fullHeight; + + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + + } + + const skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.fov = this.fov; + data.object.zoom = this.zoom; + + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + + data.object.aspect = this.aspect; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + + return data; + + } + +} + +const fov = - 90; // negative fov is not an error +const aspect = 1; + +class CubeCamera extends Object3D { + + constructor( near, far, renderTarget ) { + + super(); + + this.type = 'CubeCamera'; + + this.renderTarget = renderTarget; + + const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + cameraPX.up.set( 0, 1, 0 ); + cameraPX.lookAt( 1, 0, 0 ); + this.add( cameraPX ); + + const cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + cameraNX.up.set( 0, 1, 0 ); + cameraNX.lookAt( - 1, 0, 0 ); + this.add( cameraNX ); + + const cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + cameraPY.up.set( 0, 0, - 1 ); + cameraPY.lookAt( 0, 1, 0 ); + this.add( cameraPY ); + + const cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + cameraNY.up.set( 0, 0, 1 ); + cameraNY.lookAt( 0, - 1, 0 ); + this.add( cameraNY ); + + const cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + cameraPZ.up.set( 0, 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + this.add( cameraPZ ); + + const cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + cameraNZ.up.set( 0, 1, 0 ); + cameraNZ.lookAt( 0, 0, - 1 ); + this.add( cameraNZ ); + + } + + update( renderer, scene ) { + + if ( this.parent === null ) this.updateMatrixWorld(); + + const renderTarget = this.renderTarget; + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; + + const currentRenderTarget = renderer.getRenderTarget(); + + const currentToneMapping = renderer.toneMapping; + const currentXrEnabled = renderer.xr.enabled; + + renderer.toneMapping = NoToneMapping; + renderer.xr.enabled = false; + + const generateMipmaps = renderTarget.texture.generateMipmaps; + + renderTarget.texture.generateMipmaps = false; + + renderer.setRenderTarget( renderTarget, 0 ); + renderer.render( scene, cameraPX ); + + renderer.setRenderTarget( renderTarget, 1 ); + renderer.render( scene, cameraNX ); + + renderer.setRenderTarget( renderTarget, 2 ); + renderer.render( scene, cameraPY ); + + renderer.setRenderTarget( renderTarget, 3 ); + renderer.render( scene, cameraNY ); + + renderer.setRenderTarget( renderTarget, 4 ); + renderer.render( scene, cameraPZ ); + + renderTarget.texture.generateMipmaps = generateMipmaps; + + renderer.setRenderTarget( renderTarget, 5 ); + renderer.render( scene, cameraNZ ); + + renderer.setRenderTarget( currentRenderTarget ); + + renderer.toneMapping = currentToneMapping; + renderer.xr.enabled = currentXrEnabled; + + renderTarget.texture.needsPMREMUpdate = true; + + } + +} + +class CubeTexture extends Texture { + + constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + + super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCubeTexture = true; + + this.flipY = false; + + } + + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + + constructor( size = 1, options = {} ) { + + super( size, size, options ); + + this.isWebGLCubeRenderTarget = true; + + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. + + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). + + this.texture.isRenderTargetTexture = true; + + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + + } + + fromEquirectangularTexture( renderer, texture ) { + + this.texture.type = texture.type; + this.texture.encoding = texture.encoding; + + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + + const shader = { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: /* glsl */` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + + fragmentShader: /* glsl */` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + + const geometry = new BoxGeometry( 5, 5, 5 ); + + const material = new ShaderMaterial( { + + name: 'CubemapFromEquirect', + + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + + } ); + + material.uniforms.tEquirect.value = texture; + + const mesh = new Mesh( geometry, material ); + + const currentMinFilter = texture.minFilter; + + // Avoid blurred poles + if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter; + + const camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, mesh ); + + texture.minFilter = currentMinFilter; + + mesh.geometry.dispose(); + mesh.material.dispose(); + + return this; + + } + + clear( renderer, color, depth, stencil ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + for ( let i = 0; i < 6; i ++ ) { + + renderer.setRenderTarget( this, i ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( currentRenderTarget ); + + } + +} + +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); + +class Plane { + + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + + this.isPlane = true; + + // normal is assumed to be normalized + + this.normal = normal; + this.constant = constant; + + } + + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; + + } + + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; + + return this; + + } + + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + negate() { + + this.constant *= - 1; + this.normal.negate(); + + return this; + + } + + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + projectPoint( point, target ) { + + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + + } + + intersectLine( line, target ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( t < 0 || t > 1 ) { + + return null; + + } + + return target.copy( direction ).multiplyScalar( t ).add( line.start ); + + } + + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _sphere$2 = /*@__PURE__*/ new Sphere(); +const _vector$7 = /*@__PURE__*/ new Vector3(); + +class Frustum { + + constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { + + this.planes = [ p0, p1, p2, p3, p4, p5 ]; + + } + + set( p0, p1, p2, p3, p4, p5 ) { + + const 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 ); + + return this; + + } + + copy( frustum ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + planes[ i ].copy( frustum.planes[ i ] ); + + } + + return this; + + } + + setFromProjectionMatrix( m ) { + + const planes = this.planes; + const me = m.elements; + const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + + 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(); + + return this; + + } + + intersectsObject( object ) { + + const geometry = object.geometry; + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSprite( sprite ) { + + _sphere$2.center.set( 0, 0, 0 ); + _sphere$2.radius = 0.7071067811865476; + _sphere$2.applyMatrix4( sprite.matrixWorld ); + + return this.intersectsSphere( _sphere$2 ); + + } + + intersectsSphere( sphere ) { + + const planes = this.planes; + const center = sphere.center; + const negRadius = - sphere.radius; + + for ( let i = 0; i < 6; i ++ ) { + + const distance = planes[ i ].distanceToPoint( center ); + + if ( distance < negRadius ) { + + return false; + + } + + } + + return true; + + } + + intersectsBox( box ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + const plane = planes[ i ]; + + // corner at max distance + + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; + + if ( plane.distanceToPoint( _vector$7 ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + containsPoint( point ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +function WebGLAnimation() { + + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + + function onAnimationFrame( time, frame ) { + + animationLoop( time, frame ); + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + } + + return { + + start: function () { + + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + isAnimating = true; + + }, + + stop: function () { + + context.cancelAnimationFrame( requestId ); + + isAnimating = false; + + }, + + setAnimationLoop: function ( callback ) { + + animationLoop = callback; + + }, + + setContext: function ( value ) { + + context = value; + + } + + }; + +} + +function WebGLAttributes( gl, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + const buffers = new WeakMap(); + + function createBuffer( attribute, bufferType ) { + + const array = attribute.array; + const usage = attribute.usage; + + const buffer = gl.createBuffer(); + + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); + + attribute.onUploadCallback(); + + let type; + + if ( array instanceof Float32Array ) { + + type = 5126; + + } else if ( array instanceof Uint16Array ) { + + if ( attribute.isFloat16BufferAttribute ) { + + if ( isWebGL2 ) { + + type = 5131; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' ); + + } + + } else { + + type = 5123; + + } + + } else if ( array instanceof Int16Array ) { + + type = 5122; + + } else if ( array instanceof Uint32Array ) { + + type = 5125; + + } else if ( array instanceof Int32Array ) { + + type = 5124; + + } else if ( array instanceof Int8Array ) { + + type = 5120; + + } else if ( array instanceof Uint8Array ) { + + type = 5121; + + } else if ( array instanceof Uint8ClampedArray ) { + + type = 5121; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + + } + + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; + + } + + function updateBuffer( buffer, attribute, bufferType ) { + + const array = attribute.array; + const updateRange = attribute.updateRange; + + gl.bindBuffer( bufferType, buffer ); + + if ( updateRange.count === - 1 ) { + + // Not using update ranges + + gl.bufferSubData( bufferType, 0, array ); + + } else { + + if ( isWebGL2 ) { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array, updateRange.offset, updateRange.count ); + + } else { + + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); + + } + + updateRange.count = - 1; // reset range + + } + + attribute.onUploadCallback(); + + } + + // + + function get( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + return buffers.get( attribute ); + + } + + function remove( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data ) { + + gl.deleteBuffer( data.buffer ); + + buffers.delete( attribute ); + + } + + } + + function update( attribute, bufferType ) { + + if ( attribute.isGLBufferAttribute ) { + + const cached = buffers.get( attribute ); + + if ( ! cached || cached.version < attribute.version ) { + + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); + + } + + return; + + } + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data === undefined ) { + + buffers.set( attribute, createBuffer( attribute, bufferType ) ); + + } else if ( data.version < attribute.version ) { + + updateBuffer( data.buffer, attribute, bufferType ); + + data.version = attribute.version; + + } + + } + + return { + + get: get, + remove: remove, + update: update + + }; + +} + +class PlaneGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { + + super(); + + this.type = 'PlaneGeometry'; + + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + + const width_half = width / 2; + const height_half = height / 2; + + const gridX = Math.floor( widthSegments ); + const gridY = Math.floor( heightSegments ); + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + const segment_width = width / gridX; + const segment_height = height / gridY; + + // + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segment_height - height_half; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segment_width - width_half; + + vertices.push( x, - y, 0 ); + + normals.push( 0, 0, 1 ); + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + } + + } + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = ix + gridX1 * iy; + const b = ix + gridX1 * ( iy + 1 ); + const c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = ( ix + 1 ) + gridX1 * iy; + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + +} + +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; + +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + +var begin_vertex = "vec3 transformed = vec3( position );"; + +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + +var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif"; + +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\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#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; + +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; + +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + +var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + +var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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.a );\n}"; + +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + +var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif"; + +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif"; + +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + +var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + +var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + +var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + +var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif"; + +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif"; + +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + +var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\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\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif"; + +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; + +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\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\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; + +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\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( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), 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( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), 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 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + +var skinbase_vertex = "#ifdef USE_SKINNING\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#endif"; + +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif"; + +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + +var skinnormal_vertex = "#ifdef USE_SKINNING\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\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; + +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif"; + +var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; + +var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; + +var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; + +var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + +var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; + +var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; + +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + +const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + +const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; + +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}"; + +const fragment$b = "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\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\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}"; + +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying 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 \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$6 = "#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 \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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\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\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\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 \n#include \n#include \nvoid main() {\n\t#include \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\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\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\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\t#include \n}"; + +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + 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_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + 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_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + 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, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + output_fragment: output_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + 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, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_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, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; + +/** + * Uniforms library for shared webgl shaders + */ + +const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + uv2Transform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + + }, + + envmap: { + + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 } + + }, + + emissivemap: { + + emissiveMap: { value: null } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + roughnessmap: { + + roughnessMap: { value: null } + + }, + + metalnessmap: { + + metalnessMap: { value: null } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + } + +}; + +const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distanceRGBA: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + +}; + +ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatNormalMap: { value: null }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + +}; + +const _rgb = { r: 0, b: 0, g: 0 }; + +function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function render( renderList, scene ) { + + let forceClear = false; + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background ); + + } + + // Ignore background in AR + // TODO: Reconsider this. + + const xr = renderer.xr; + const session = xr.getSession && xr.getSession(); + + if ( session && session.environmentBlendMode === 'additive' ) { + + background = null; + + } + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + if ( renderer.autoClear || forceClear ) { + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render + + }; + +} + +function WebGLBindingStates( gl, extensions, attributes, capabilities ) { + + const maxVertexAttributes = gl.getParameter( 34921 ); + + const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' ); + const vaoAvailable = capabilities.isWebGL2 || extension !== null; + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + if ( vaoAvailable ) { + + const state = getBindingState( geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + } else { + + const wireframe = ( material.wireframe === true ); + + if ( currentState.geometry !== geometry.id || + currentState.program !== program.id || + currentState.wireframe !== wireframe ) { + + currentState.geometry = geometry.id; + currentState.program = program.id; + currentState.wireframe = wireframe; + + updateBuffers = true; + + } + + } + + if ( index !== null ) { + + attributes.update( index, 34963 ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( 34963, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + if ( capabilities.isWebGL2 ) return gl.createVertexArray(); + + return extension.createVertexArrayOES(); + + } + + function bindVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao ); + + return extension.bindVertexArrayOES( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao ); + + return extension.deleteVertexArrayOES( vao ); + + } + + function getBindingState( geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let programMap = bindingStates[ geometry.id ]; + + if ( programMap === undefined ) { + + programMap = {}; + bindingStates[ geometry.id ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + + extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset ) { + + if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { + + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return; + + } + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( 34962, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( 34962, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const programMap = bindingStates[ geometry.id ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + +} + +function WebGLBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawArraysInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawArraysInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLCapabilities( gl, extensions, parameters ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 && + gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 && + gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext; + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ); + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + + const maxTextures = gl.getParameter( 34930 ); + const maxVertexTextures = gl.getParameter( 35660 ); + const maxTextureSize = gl.getParameter( 3379 ); + const maxCubemapSize = gl.getParameter( 34076 ); + + const maxAttributes = gl.getParameter( 34921 ); + const maxVertexUniforms = gl.getParameter( 36347 ); + const maxVaryings = gl.getParameter( 36348 ); + const maxFragmentUniforms = gl.getParameter( 36349 ); + + const vertexTextures = maxVertexTextures > 0; + const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' ); + const floatVertexTextures = vertexTextures && floatFragmentTextures; + + const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0; + + return { + + isWebGL2: isWebGL2, + + drawBuffers: drawBuffers, + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures, + + maxSamples: maxSamples + + }; + +} + +function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const 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; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + +} + +function WebGLCubeMaps( renderer ) { + + let cubemaps = new WeakMap(); + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function get( texture ) { + + if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubemaps.has( texture ) ) { + + const cubemap = cubemaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height / 2 ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubemaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemap = cubemaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubemaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function dispose() { + + cubemaps = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class OrthographicCamera extends Camera { + + constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) { + + super(); + + this.isOrthographicCamera = true; + + this.type = 'OrthographicCamera'; + + this.zoom = 1; + this.view = null; + + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + + this.near = near; + this.far = far; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + return this; + + } + + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + 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 ); + + return data; + + } + +} + +const LOD_MIN = 4; + +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; + +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; + +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; + +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( 1, 1, 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( - 1, 1, - 1 ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ]; + +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting + * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view +*/ + +class PMREMGenerator { + + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._compileMaterial( this._blurMaterial ); + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100 ) { + + _oldTarget = this._renderer.getRenderTarget(); + + this._setSize( 256 ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + + this._lodPlanes[ i ].dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + encoding: LinearEncoding, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, - 1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); + + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); + + let useSolidColor = false; + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + + for ( let i = 1; i < this._lodPlanes.length; i ++ ) { + + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + + const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; + + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); + + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); + + } + + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); + + } + + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; + + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; + + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + + if ( samples > MAX_SAMPLES ) { + + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + + } + + const weights = []; + let sum = 0; + + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); + + if ( i === 0 ) { + + sum += weight; + + } else if ( i < samples ) { + + sum += 2 * weight; + + } + + } + + for ( let i = 0; i < weights.length; i ++ ) { + + weights[ i ] = weights[ i ] / sum; + + } + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + + if ( poleAxis ) { + + blurUniforms[ 'poleAxis' ].value = poleAxis; + + } + + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + + + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : - 1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: - 1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + +} + +function WebGLCubeUVMaps( renderer ) { + + let cubeUVmaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) { + + texture.needsPMREMUpdate = false; + + let renderTarget = cubeUVmaps.get( texture ); + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + cubeUVmaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( cubeUVmaps.has( texture ) ) { + + return cubeUVmaps.get( texture ).texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + cubeUVmaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemapUV = cubeUVmaps.get( texture ); + + if ( cubemapUV !== undefined ) { + + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); + + } + + } + + function dispose() { + + cubeUVmaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + +} + +function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + let 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; + + 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; + + default: + extension = gl.getExtension( name ); + + } + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function ( capabilities ) { + + if ( capabilities.isWebGL2 ) { + + getExtension( 'EXT_color_buffer_float' ); + + } else { + + getExtension( 'WEBGL_depth_texture' ); + getExtension( 'OES_texture_float' ); + getExtension( 'OES_texture_half_float' ); + getExtension( 'OES_texture_half_float_linear' ); + getExtension( 'OES_standard_derivatives' ); + getExtension( 'OES_element_index_uint' ); + getExtension( 'OES_vertex_array_object' ); + getExtension( 'ANGLE_instanced_arrays' ); + + } + + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + +} + +function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], 34962 ); + + } + + // morph targets + + const morphAttributes = geometry.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = morphAttributes[ name ]; + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + attributes.update( array[ i ], 34962 ); + + } + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } + + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + +} + +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + let extension, methodName; + + if ( isWebGL2 ) { + + extension = gl; + methodName = 'drawElementsInstanced'; + + } else { + + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; + + if ( extension === null ) { + + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; + + } + + } + + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + +} + +function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case 4: + render.triangles += instanceCount * ( count / 3 ); + break; + + case 1: + render.lines += instanceCount * ( count / 2 ); + break; + + case 3: + render.lines += instanceCount * ( count - 1 ); + break; + + case 2: + render.lines += instanceCount * count; + break; + + case 0: + render.points += instanceCount * count; + break; + + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + +} + +function numericalSort( a, b ) { + + return a[ 0 ] - b[ 0 ]; + +} + +function absNumericalSort( a, b ) { + + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + +} + +function WebGLMorphtargets( gl, capabilities, textures ) { + + const influencesList = {}; + const morphInfluences = new Float32Array( 8 ); + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + const workInfluences = []; + + for ( let i = 0; i < 8; i ++ ) { + + workInfluences[ i ] = [ i, 0 ]; + + } + + function update( object, geometry, material, program ) { + + const objectInfluences = object.morphTargetInfluences; + + if ( capabilities.isWebGL2 === true ) { + + // instead of using attributes, the WebGL 2 code path encodes morph targets + // into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + + } else { + + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences + + const length = objectInfluences === undefined ? 0 : objectInfluences.length; + + let influences = influencesList[ geometry.id ]; + + if ( influences === undefined || influences.length !== length ) { + + // initialise list + + influences = []; + + for ( let i = 0; i < length; i ++ ) { + + influences[ i ] = [ i, 0 ]; + + } + + influencesList[ geometry.id ] = influences; + + } + + // Collect influences + + for ( let i = 0; i < length; i ++ ) { + + const influence = influences[ i ]; + + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; + + } + + influences.sort( absNumericalSort ); + + for ( let i = 0; i < 8; i ++ ) { + + if ( i < length && influences[ i ][ 1 ] ) { + + workInfluences[ i ][ 0 ] = influences[ i ][ 0 ]; + workInfluences[ i ][ 1 ] = influences[ i ][ 1 ]; + + } else { + + workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER; + workInfluences[ i ][ 1 ] = 0; + + } + + } + + workInfluences.sort( numericalSort ); + + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < 8; i ++ ) { + + const influence = workInfluences[ i ]; + const index = influence[ 0 ]; + const value = influence[ 1 ]; + + if ( index !== Number.MAX_SAFE_INTEGER && value ) { + + if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) { + + geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + + } + + if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) { + + geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); + + } + + morphInfluences[ i ] = value; + morphInfluencesSum += value; + + } else { + + if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) { + + geometry.deleteAttribute( 'morphTarget' + i ); + + } + + if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) { + + geometry.deleteAttribute( 'morphNormal' + i ); + + } + + morphInfluences[ i ] = 0; + + } + + } + + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + + } + + } + + return { + + update: update + + }; + +} + +function WebGLObjects( gl, geometries, attributes, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + attributes.update( object.instanceMatrix, 34962 ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, 34962 ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + +} + +/** + * 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 )'. + * + * + * 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, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + +const emptyTexture = /*@__PURE__*/ new Texture(); +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + +// --- Utilities --- + +// Array Caches (provide typed arrays for temporary by size) + +const arrayCacheF32 = []; +const arrayCacheI32 = []; + +// Float32Array caches used for uploading Matrix uniforms + +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); + +// Flattening for arrays of vectors and matrices + +function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + +} + +function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + +} + +function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + +} + +// Texture unit allocation + +function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + +} + +// --- Setters --- + +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. + +// Single scalar + +function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single float vector (from flat array or THREE.VectorN) + +function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single matrix (from flat array or THREE.MatrixN) + +function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + +} + +// Single integer / boolean + +function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single integer / boolean vector (from flat array or THREE.VectorN) + +function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single unsigned integer + +function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single unsigned integer vector (from flat array or THREE.VectorN) + +function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + + +// Single texture (2D / Cube) + +function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2D( v || emptyTexture, unit ); + +} + +function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + +} + +function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + +} + +function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + +} + +// Helper to pick the right setter for the singular case + +function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + +} + + +// Array of scalars + +function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + +} + +// Array of vectors (from flat array or array of THREE.VectorN) + +function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + +} + +function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + +} + +function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + +} + +// Array of matrices (from flat array or array of THREE.MatrixN) + +function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + +} + +function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + +} + +function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + +} + +// Array of integer / boolean + +function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + +} + +// Array of integer / boolean vectors (from flat array) + +function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + +} + +function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + +} + +function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + +} + +// Array of unsigned integer + +function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + +} + +// Array of unsigned integer vectors (from flat array) + +function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + +} + +function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + +} + +function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + +} + + +// Array of textures (2D / 3D / Cube / 2DArray) + +function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + + } + +} + +function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + +} + +function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + +} + +function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + +} + + +// Helper to pick the right setter for a pure (bottom-level) array + +function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + +} + +// --- Uniform Classes --- + +class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + +} + +// --- Top-level --- + +// Parser - builds up the property tree from the path strings + +const RePathPart = /(\w+)(\])?(\[|\.)?/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. + +function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + +} + +function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + +} + +// Root Container + +class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, 35718 ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + +} + +function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + +} + +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + +} + +function getEncodingComponents( encoding ) { + + switch ( encoding ) { + + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + default: + console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding ); + return [ 'Linear', '( value )' ]; + + } + +} + +function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, 35713 ); + const errors = gl.getShaderInfoLog( shader ).trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + +} + +function getTexelEncodingFunction( functionName, encoding ) { + + const components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + +} + +function getToneMappingFunction( functionName, toneMapping ) { + + let toneMappingName; + + switch ( toneMapping ) { + + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + +} + +function generateExtensions( parameters ) { + + const chunks = [ + ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + +} + +function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, 35721 ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === 35674 ) locationSize = 2; + if ( info.type === 35675 ) locationSize = 3; + if ( info.type === 35676 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +function includeReplacer( match, include ) { + + const string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;'; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + customExtensions, + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', + + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', + + ' #ifdef USE_MORPHNORMALS', + + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', + + ' #else', + + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', + + ' #endif', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + customExtensions, + + generatePrecision( parameters ), + + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + 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.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + 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 && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( 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.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + 'precision mediump sampler2DArray;', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, 35714 ) === false ) { + + runnable = false; + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + this.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + cachedUniforms = new WebGLUniforms( gl, program ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + return cachedAttributes; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + + const isWebGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const vertexTextures = capabilities.vertexTextures; + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + + const useAlphaTest = material.alphaTest > 0; + const useClearcoat = material.clearcoat > 0; + const useIridescence = material.iridescence > 0; + + const parameters = { + + isWebGL2: isWebGL2, + + shaderID: shaderID, + shaderName: material.type, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + instancing: object.isInstancedMesh === true, + instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ), + map: !! material.map, + matcap: !! material.matcap, + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + lightMap: !! material.lightMap, + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + + decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ), + + clearcoat: useClearcoat, + clearcoatMap: useClearcoat && !! material.clearcoatMap, + clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap, + clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap, + + iridescence: useIridescence, + iridescenceMap: useIridescence && !! material.iridescenceMap, + iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap, + + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + specularIntensityMap: !! material.specularIntensityMap, + specularColorMap: !! material.specularColorMap, + + opaque: material.transparent === false && material.blending === NormalBlending, + + alphaMap: !! material.alphaMap, + alphaTest: useAlphaTest, + + gradientMap: !! material.gradientMap, + + sheen: material.sheen > 0, + sheenColorMap: !! material.sheenColorMap, + sheenRoughnessMap: !! material.sheenRoughnessMap, + + transmission: material.transmission > 0, + transmissionMap: !! material.transmissionMap, + thicknessMap: !! material.thicknessMap, + + combine: material.combine, + + vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: !! material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: !! material.depthPacking, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, + + rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ), + rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ), + rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputEncoding ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputEncoding ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.combine ); + array.push( parameters.vertexUvs ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.isWebGL2 ) + _programLayers.enable( 0 ); + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 1 ); + if ( parameters.instancing ) + _programLayers.enable( 2 ); + if ( parameters.instancingColor ) + _programLayers.enable( 3 ); + if ( parameters.map ) + _programLayers.enable( 4 ); + if ( parameters.matcap ) + _programLayers.enable( 5 ); + if ( parameters.envMap ) + _programLayers.enable( 6 ); + if ( parameters.lightMap ) + _programLayers.enable( 7 ); + if ( parameters.aoMap ) + _programLayers.enable( 8 ); + if ( parameters.emissiveMap ) + _programLayers.enable( 9 ); + if ( parameters.bumpMap ) + _programLayers.enable( 10 ); + if ( parameters.normalMap ) + _programLayers.enable( 11 ); + if ( parameters.objectSpaceNormalMap ) + _programLayers.enable( 12 ); + if ( parameters.tangentSpaceNormalMap ) + _programLayers.enable( 13 ); + if ( parameters.clearcoat ) + _programLayers.enable( 14 ); + if ( parameters.clearcoatMap ) + _programLayers.enable( 15 ); + if ( parameters.clearcoatRoughnessMap ) + _programLayers.enable( 16 ); + if ( parameters.clearcoatNormalMap ) + _programLayers.enable( 17 ); + if ( parameters.iridescence ) + _programLayers.enable( 18 ); + if ( parameters.iridescenceMap ) + _programLayers.enable( 19 ); + if ( parameters.iridescenceThicknessMap ) + _programLayers.enable( 20 ); + if ( parameters.displacementMap ) + _programLayers.enable( 21 ); + if ( parameters.specularMap ) + _programLayers.enable( 22 ); + if ( parameters.roughnessMap ) + _programLayers.enable( 23 ); + if ( parameters.metalnessMap ) + _programLayers.enable( 24 ); + if ( parameters.gradientMap ) + _programLayers.enable( 25 ); + if ( parameters.alphaMap ) + _programLayers.enable( 26 ); + if ( parameters.alphaTest ) + _programLayers.enable( 27 ); + if ( parameters.vertexColors ) + _programLayers.enable( 28 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 29 ); + if ( parameters.vertexUvs ) + _programLayers.enable( 30 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 31 ); + if ( parameters.uvsVertexOnly ) + _programLayers.enable( 32 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.skinning ) + _programLayers.enable( 4 ); + if ( parameters.morphTargets ) + _programLayers.enable( 5 ); + if ( parameters.morphNormals ) + _programLayers.enable( 6 ); + if ( parameters.morphColors ) + _programLayers.enable( 7 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 8 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 9 ); + if ( parameters.physicallyCorrectLights ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.specularIntensityMap ) + _programLayers.enable( 15 ); + if ( parameters.specularColorMap ) + _programLayers.enable( 16 ); + if ( parameters.transmission ) + _programLayers.enable( 17 ); + if ( parameters.transmissionMap ) + _programLayers.enable( 18 ); + if ( parameters.thicknessMap ) + _programLayers.enable( 19 ); + if ( parameters.sheen ) + _programLayers.enable( 20 ); + if ( parameters.sheenColorMap ) + _programLayers.enable( 21 ); + if ( parameters.sheenRoughnessMap ) + _programLayers.enable( 22 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 23 ); + if ( parameters.opaque ) + _programLayers.enable( 24 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + +function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + + + +let nextVersion = 0; + +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + +} + +function WebGLLights( extensions, capabilities ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + directionalLength: - 1, + pointLength: - 1, + spotLength: - 1, + rectAreaLength: - 1, + hemiLength: - 1, + + numDirectionalShadows: - 1, + numPointShadows: - 1, + numSpotShadows: - 1, + numSpotMaps: - 1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights, physicallyCorrectLights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + // artist-friendly light intensity scaling factor + const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + + if ( light.isAmbientLight ) { + + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( capabilities.isWebGL2 ) { + + // WebGL 2 + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + // WebGL 1 + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } else { + + console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' ); + + } + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps ) { + + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + +} + +function WebGLRenderState( extensions, capabilities ) { + + const lights = new WebGLLights( extensions, capabilities ); + + const lightsArray = []; + const shadowsArray = []; + + function init() { + + lightsArray.length = 0; + shadowsArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function setupLights( physicallyCorrectLights ) { + + lights.setup( lightsArray, physicallyCorrectLights ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + + lights: lights + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow + }; + +} + +function WebGLRenderStates( extensions, capabilities ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions, capabilities ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +class MeshDepthMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDepthMaterial = true; + + this.type = 'MeshDepthMaterial'; + + this.depthPacking = BasicDepthPacking; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.depthPacking = source.depthPacking; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + return this; + + } + +} + +class MeshDistanceMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshDistanceMaterial = true; + + this.type = 'MeshDistanceMaterial'; + + this.referencePosition = new Vector3(); + this.nearDistance = 1; + this.farDistance = 1000; + + this.map = null; + + this.alphaMap = null; + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.referencePosition.copy( source.referencePosition ); + this.nearDistance = source.nearDistance; + this.farDistance = source.farDistance; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + return this; + + } + +} + +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + +function WebGLShadowMap( _renderer, _objects, _capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = _capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide, [ TwoPassDoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + const currentRenderTarget = _renderer.getRenderTarget(); + const activeCubeFace = _renderer.getActiveCubeFace(); + const activeMipmapLevel = _renderer.getActiveMipmapLevel(); + + const _state = _renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + if ( shadow.map === null ) { + + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + '.shadowMap'; + + shadow.camera.updateProjectionMatrix(); + + } + + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + + const viewportCount = shadow.getViewportCount(); + + for ( let vp = 0; vp < viewportCount; vp ++ ) { + + const viewport = shadow.getViewport( vp ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + shadow.updateMatrices( light, vp ); + + _frustum = shadow.getFrustum(); + + renderObject( scene, camera, shadow.camera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + scope.needsUpdate = false; + + _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = _objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // vertical pass + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.mapPass ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + result.referencePosition.setFromMatrixPosition( light.matrixWorld ); + result.nearDistance = shadowCameraNear; + result.farDistance = shadowCameraFar; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = _objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); + + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + +} + +function WebGLState( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( 2929 ); + + } else { + + disable( 2929 ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( 512 ); + break; + + case AlwaysDepth: + + gl.depthFunc( 519 ); + break; + + case LessDepth: + + gl.depthFunc( 513 ); + break; + + case LessEqualDepth: + + gl.depthFunc( 515 ); + break; + + case EqualDepth: + + gl.depthFunc( 514 ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( 518 ); + break; + + case GreaterDepth: + + gl.depthFunc( 516 ); + break; + + case NotEqualDepth: + + gl.depthFunc( 517 ); + break; + + default: + + gl.depthFunc( 515 ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + gl.clearDepth( depth ); + currentDepthClear = depth; + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( 2960 ); + + } else { + + disable( 2960 ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( 35661 ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( 7938 ); + + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( 3088 ); + const viewportParam = gl.getParameter( 2978 ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const texture = gl.createTexture(); + + gl.bindTexture( type, texture ); + gl.texParameteri( type, 10241, 9728 ); + gl.texParameteri( type, 10240, 9728 ); + + for ( let i = 0; i < count; i ++ ) { + + gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data ); + + } + + return texture; + + } + + const emptyTextures = {}; + emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 ); + emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 ); + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( 2929 ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( 2884 ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + if ( isWebGL2 ) { + + // 36009 is equivalent to 36160 + + if ( target === 36009 ) { + + currentBoundFramebuffers[ 36160 ] = framebuffer; + + } + + if ( target === 36160 ) { + + currentBoundFramebuffers[ 36009 ] = framebuffer; + + } + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = 36064 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== 36064 ) { + + drawBuffers[ 0 ] = 36064; + + needsUpdate = true; + + } + + } + + } else { + + if ( drawBuffers[ 0 ] !== 1029 ) { + + drawBuffers[ 0 ] = 1029; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + if ( capabilities.isWebGL2 ) { + + gl.drawBuffers( drawBuffers ); + + } else { + + extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers ); + + } + + } + + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: 32774, + [ SubtractEquation ]: 32778, + [ ReverseSubtractEquation ]: 32779 + }; + + if ( isWebGL2 ) { + + equationToGL[ MinEquation ] = 32775; + equationToGL[ MaxEquation ] = 32776; + + } else { + + const extension = extensions.get( 'EXT_blend_minmax' ); + + if ( extension !== null ) { + + equationToGL[ MinEquation ] = extension.MIN_EXT; + equationToGL[ MaxEquation ] = extension.MAX_EXT; + + } + + } + + const factorToGL = { + [ ZeroFactor ]: 0, + [ OneFactor ]: 1, + [ SrcColorFactor ]: 768, + [ SrcAlphaFactor ]: 770, + [ SrcAlphaSaturateFactor ]: 776, + [ DstColorFactor ]: 774, + [ DstAlphaFactor ]: 772, + [ OneMinusSrcColorFactor ]: 769, + [ OneMinusSrcAlphaFactor ]: 771, + [ OneMinusDstColorFactor ]: 775, + [ OneMinusDstAlphaFactor ]: 773 + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( 3042 ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( 3042 ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( 32774 ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( 1, 771, 1, 771 ); + break; + + case AdditiveBlending: + gl.blendFunc( 1, 1 ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( 0, 769, 0, 1 ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( 0, 768, 0, 770 ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( 770, 771, 1, 771 ); + break; + + case AdditiveBlending: + gl.blendFunc( 770, 1 ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( 0, 769, 0, 1 ); + break; + + case MultiplyBlending: + gl.blendFunc( 0, 768 ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( 2884 ) + : enable( 2884 ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( 32926 ) + : disable( 32926 ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( 2304 ); + + } else { + + gl.frontFace( 2305 ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( 2884 ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( 1029 ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( 1028 ); + + } else { + + gl.cullFace( 1032 ); + + } + + } + + } else { + + disable( 2884 ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( 32823 ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + gl.polygonOffset( factor, units ); + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + } + + } else { + + disable( 32823 ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( 3089 ); + + } else { + + disable( 3089 ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = 33984 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D.apply( gl, arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( 3042 ); + gl.disable( 2884 ); + gl.disable( 2929 ); + gl.disable( 32823 ); + gl.disable( 3089 ); + gl.disable( 2960 ); + gl.disable( 32926 ); + + gl.blendEquation( 32774 ); + gl.blendFunc( 1, 0 ); + gl.blendFuncSeparate( 1, 0, 1, 0 ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( 513 ); + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( 519, 0, 0xffffffff ); + gl.stencilOp( 7680, 7680, 7680 ); + gl.clearStencil( 0 ); + + gl.cullFace( 1029 ); + gl.frontFace( 2305 ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( 33984 ); + + gl.bindFramebuffer( 36160, null ); + + if ( isWebGL2 === true ) { + + gl.bindFramebuffer( 36009, null ); + gl.bindFramebuffer( 36008, null ); + + } + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + // reset internals + + enabledCapabilities = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + +} + +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const isWebGL2 = capabilities.isWebGL2; + const maxTextures = capabilities.maxTextures; + const maxCubemapSize = capabilities.maxCubemapSize; + const maxTextureSize = capabilities.maxTextureSize; + const maxSamples = capabilities.maxSamples; + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _videoTextures = new WeakMap(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { + + let scale = 1; + + // handle case if texture exceeds max size + + if ( image.width > maxSize || image.height > maxSize ) { + + scale = maxSize / Math.max( image.width, image.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 || needsPowerOfTwo === true ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; + + const width = floor( scale * image.width ); + const height = floor( scale * image.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function isPowerOfTwo$1( image ) { + + return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ); + + } + + function textureNeedsPowerOfTwo( texture ) { + + if ( isWebGL2 ) return false; + + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + + } + + function textureNeedsGenerateMipmaps( texture, supportsMips ) { + + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) { + + if ( isWebGL2 === false ) return glFormat; + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let internalFormat = glFormat; + + if ( glFormat === 6403 ) { + + if ( glType === 5126 ) internalFormat = 33326; + if ( glType === 5131 ) internalFormat = 33325; + if ( glType === 5121 ) internalFormat = 33321; + + } + + if ( glFormat === 33319 ) { + + if ( glType === 5126 ) internalFormat = 33328; + if ( glType === 5131 ) internalFormat = 33327; + if ( glType === 5121 ) internalFormat = 33323; + + } + + if ( glFormat === 6408 ) { + + if ( glType === 5126 ) internalFormat = 34836; + if ( glType === 5131 ) internalFormat = 34842; + if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856; + if ( glType === 32819 ) internalFormat = 32854; + if ( glType === 32820 ) internalFormat = 32855; + + } + + if ( internalFormat === 33325 || internalFormat === 33326 || + internalFormat === 33327 || internalFormat === 33328 || + internalFormat === 34842 || internalFormat === 34836 ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getMipLevels( texture, image, supportsMips ) { + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // Fallback filters for non-power-of-2 textures + + function filterFallback( f ) { + + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + + return 9728; + + } + + return 9729; + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglTexture !== undefined ) { + + _gl.deleteTexture( textureProperties.__webglTexture ); + + info.memory.textures --; + + } + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + if ( renderTarget.isWebGLMultipleRenderTargets ) { + + for ( let i = 0, il = texture.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( texture[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( texture[ i ] ); + + } + + } + + properties.remove( texture ); + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= maxTextures ) { + + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.encoding ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } + + state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: 10497, + [ ClampToEdgeWrapping ]: 33071, + [ MirroredRepeatWrapping ]: 33648 + }; + + const filterToGL = { + [ NearestFilter ]: 9728, + [ NearestMipmapNearestFilter ]: 9984, + [ NearestMipmapLinearFilter ]: 9986, + + [ LinearFilter ]: 9729, + [ LinearMipmapNearestFilter ]: 9985, + [ LinearMipmapLinearFilter ]: 9987 + }; + + function setTextureParameters( textureType, texture, supportsMips ) { + + if ( supportsMips ) { + + _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); + + } else { + + _gl.texParameteri( textureType, 10242, 33071 ); + _gl.texParameteri( textureType, 10243, 33071 ); + + if ( textureType === 32879 || textureType === 35866 ) { + + _gl.texParameteri( textureType, 32882, 33071 ); + + } + + 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.' ); + + } + + _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); + + 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.' ); + + } + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2 + if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only + + 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; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create Source <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = 3553; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866; + if ( texture.isData3DTexture ) textureType = 32879; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( 33984 + slot ); + + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); + + const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false; + let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ); + + let glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture ); + + setTextureParameters( textureType, texture, supportsMips ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const levels = getMipLevels( texture, image, supportsMips ); + + if ( texture.isDepthTexture ) { + + // populate depth texture with dummy data + + glInternalFormat = 6402; + + if ( isWebGL2 ) { + + if ( texture.type === FloatType ) { + + glInternalFormat = 36012; + + } else if ( texture.type === UnsignedIntType ) { + + glInternalFormat = 33190; + + } else if ( texture.type === UnsignedInt248Type ) { + + glInternalFormat = 35056; + + } else { + + glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D + + } + + } else { + + if ( texture.type === FloatType ) { + + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); + + } + + } + + // validation checks for WebGL 1 + + if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + + texture.type = UnsignedIntType; + glType = utils.convert( texture.type ); + + } + + } + + if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { + + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = 34041; + + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { + + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); + + } + + } + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( 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 + + if ( mipmaps.length > 0 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 ); + + } else { + + state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } else { + + state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } else { + + state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else { + + // regular Texture (image, video, canvas) + + // 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 && supportsMips ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap ); + + } else { + + state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height ); + + } + + state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image ); + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( 33984 + slot ); + + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + _gl.pixelStorei( 37443, 0 ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo$1( image ) || isWebGL2, + glFormat = utils.convert( texture.format, texture.encoding ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + + const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + let levels = getMipLevels( texture, image, supportsMips ); + + setTextureParameters( 34067, texture, supportsMips ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } else { + + state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } else { + + state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } else { + + state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } else { + + state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } else { + + state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } else { + + state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + // We assume images for cube map have the same size. + generateMipmap( 34067 ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) { + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const renderTargetProperties = properties.get( renderTarget ); + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + if ( textureTarget === 32879 || textureTarget === 35866 ) { + + state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( 36160, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753 + + _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 ); + + } + + state.bindFramebuffer( 36160, null ); + + } + + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + + _gl.bindRenderbuffer( 36161, renderbuffer ); + + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + + let glInternalFormat = 33189; + + if ( isMultisample || useMultisampledRTT( renderTarget ) ) { + + const depthTexture = renderTarget.depthTexture; + + if ( depthTexture && depthTexture.isDepthTexture ) { + + if ( depthTexture.type === FloatType ) { + + glInternalFormat = 36012; + + } else if ( depthTexture.type === UnsignedIntType ) { + + glInternalFormat = 33190; + + } + + } + + const samples = getRenderTargetSamples( renderTarget ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } else { + + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); + + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); + + } + + + _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); + + } else { + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding ); + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( 36161, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { + + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + + state.bindFramebuffer( 36160, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + + } + + // 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; + + } + + setTexture2D( renderTarget.depthTexture, 0 ); + + const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'Unknown depthTexture format' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } + + } else { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } + + } + + state.bindFramebuffer( 36160, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + if ( renderTarget.isWebGLMultipleRenderTargets !== true ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + if ( isMultipleRenderTargets ) { + + if ( capabilities.drawBuffers ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' ); + + } + + } + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = isMultipleRenderTargets ? texture : [ texture ]; + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.encoding ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( 36161, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( 36160, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( 34067, textureProperties.__webglTexture ); + setTextureParameters( 34067, texture, supportsMips ); + + for ( let i = 0; i < 6; i ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i ); + + } + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( 34067 ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + const textures = renderTarget.texture; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + state.bindTexture( 3553, attachmentProperties.__webglTexture ); + setTextureParameters( 3553, attachment, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 ); + + if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) { + + generateMipmap( 3553 ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = 3553; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + if ( isWebGL2 ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866; + + } else { + + console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' ); + + } + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType ); + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2; + + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ]; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target ); + state.unbindTexture(); + + } + + } + + } + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = 16384; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null ); + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 ); + + } + + } + + state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); + state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + invalidationArray.push( 36064 + i ); + + if ( renderTarget.depthBuffer ) { + + invalidationArray.push( depthStyle ); + + } + + const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false; + + if ( ignoreDepthValues === false ) { + + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + if ( ignoreDepthValues === true ) { + + _gl.invalidateFramebuffer( 36008, [ depthStyle ] ); + _gl.invalidateFramebuffer( 36009, [ depthStyle ] ); + + } + + if ( isMultipleRenderTargets ) { + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + + if ( supportsInvalidateFramebuffer ) { + + _gl.invalidateFramebuffer( 36008, invalidationArray ); + + } + + + } + + state.bindFramebuffer( 36008, null ); + state.bindFramebuffer( 36009, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer ); + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const encoding = texture.encoding; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image; + + if ( encoding !== LinearEncoding ) { + + // sRGB + + if ( encoding === sRGBEncoding ) { + + if ( isWebGL2 === false ) { + + // in WebGL 1, try to use EXT_sRGB extension and unsized formats + + if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) { + + texture.format = _SRGBAFormat; + + // it's not possible to generate mips in WebGL 1 with this extension + + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; + + } else { + + // slow fallback (CPU decode) + + image = ImageUtils.sRGBToLinear( image ); + + } + + } else { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } + + } else { + + console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding ); + + } + + } + + return image; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + +} + +function WebGLUtils( gl, extensions, capabilities ) { + + const isWebGL2 = capabilities.isWebGL2; + + function convert( p, encoding = null ) { + + let extension; + + if ( p === UnsignedByteType ) return 5121; + if ( p === UnsignedShort4444Type ) return 32819; + if ( p === UnsignedShort5551Type ) return 32820; + + if ( p === ByteType ) return 5120; + if ( p === ShortType ) return 5122; + if ( p === UnsignedShortType ) return 5123; + if ( p === IntType ) return 5124; + if ( p === UnsignedIntType ) return 5125; + if ( p === FloatType ) return 5126; + + if ( p === HalfFloatType ) { + + if ( isWebGL2 ) return 5131; + + extension = extensions.get( 'OES_texture_half_float' ); + + if ( extension !== null ) { + + return extension.HALF_FLOAT_OES; + + } else { + + return null; + + } + + } + + if ( p === AlphaFormat ) return 6406; + if ( p === RGBAFormat ) return 6408; + if ( p === LuminanceFormat ) return 6409; + if ( p === LuminanceAlphaFormat ) return 6410; + if ( p === DepthFormat ) return 6402; + if ( p === DepthStencilFormat ) return 34041; + + // WebGL 1 sRGB fallback + + if ( p === _SRGBAFormat ) { + + extension = extensions.get( 'EXT_sRGB' ); + + if ( extension !== null ) { + + return extension.SRGB_ALPHA_EXT; + + } else { + + return null; + + } + + } + + // WebGL2 formats. + + if ( p === RedFormat ) return 6403; + if ( p === RedIntegerFormat ) return 36244; + if ( p === RGFormat ) return 33319; + if ( p === RGIntegerFormat ) return 33320; + if ( p === RGBAIntegerFormat ) return 36249; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( encoding === sRGBEncoding ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + 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; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + 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; + + } else { + + return null; + + } + + } + + // ETC1 + + if ( p === RGB_ETC1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + + if ( extension !== null ) { + + return extension.COMPRESSED_RGB_ETC1_WEBGL; + + } else { + + return null; + + } + + } + + // ETC2 + + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) { + + if ( isWebGL2 ) return 34042; + + extension = extensions.get( 'WEBGL_depth_texture' ); + + if ( extension !== null ) { + + return extension.UNSIGNED_INT_24_8_WEBGL; + + } else { + + return null; + + } + + } + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + +} + +class ArrayCamera extends PerspectiveCamera { + + constructor( array = [] ) { + + super(); + + this.isArrayCamera = true; + + this.cameras = array; + + } + +} + +class Group extends Object3D { + + constructor() { + + super(); + + this.isGroup = true; + + this.type = 'Group'; + + } + +} + +const _moveEvent = { type: 'move' }; + +class WebXRController { + + constructor() { + + this._targetRay = null; + this._grip = null; + this._hand = null; + + } + + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + + } + + return this._hand; + + } + + getTargetRaySpace() { + + if ( this._targetRay === null ) { + + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + + } + + return this._targetRay; + + } + + getGripSpace() { + + if ( this._grip === null ) { + + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + + } + + return this._grip; + + } + + dispatchEvent( event ) { + + if ( this._targetRay !== null ) { + + this._targetRay.dispatchEvent( event ); + + } + + if ( this._grip !== null ) { + + this._grip.dispatchEvent( event ); + + } + + if ( this._hand !== null ) { + + this._hand.dispatchEvent( event ); + + } + + return this; + + } + + connect( inputSource ) { + + if ( inputSource && inputSource.hand ) { + + const hand = this._hand; + + if ( hand ) { + + for ( const inputjoint of inputSource.hand.values() ) { + + // Initialize hand with joints when connected + this._getHandJoint( hand, inputjoint ); + + } + + } + + } + + this.dispatchEvent( { type: 'connected', data: inputSource } ); + + return this; + + } + + disconnect( inputSource ) { + + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + + if ( this._targetRay !== null ) { + + this._targetRay.visible = false; + + } + + if ( this._grip !== null ) { + + this._grip.visible = false; + + } + + if ( this._hand !== null ) { + + this._hand.visible = false; + + } + + return this; + + } + + update( inputSource, frame, referenceSpace ) { + + let inputPose = null; + let gripPose = null; + let handPose = null; + + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + + if ( hand && inputSource.hand ) { + + handPose = true; + + for ( const inputjoint of inputSource.hand.values() ) { + + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + + // The transform of this joint will be updated with the joint pose on each frame + const joint = this._getHandJoint( hand, inputjoint ); + + if ( jointPose !== null ) { + + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.jointRadius = jointPose.radius; + + } + + joint.visible = jointPose !== null; + + } + + // Custom events + + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); + + const distanceToPinch = 0.02; + const threshold = 0.005; + + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); + + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); + + } + + } else { + + if ( grip !== null && inputSource.gripSpace ) { + + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + + if ( gripPose !== null ) { + + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + + if ( gripPose.linearVelocity ) { + + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); + + } else { + + grip.hasLinearVelocity = false; + + } + + if ( gripPose.angularVelocity ) { + + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); + + } else { + + grip.hasAngularVelocity = false; + + } + + } + + } + + } + + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + + } + + if ( targetRay !== null ) { + + targetRay.visible = ( inputPose !== null ); + + } + + if ( grip !== null ) { + + grip.visible = ( gripPose !== null ); + + } + + if ( hand !== null ) { + + hand.visible = ( handPose !== null ); + + } + + return this; + + } + + // private method + + _getHandJoint( hand, inputjoint ) { + + if ( hand.joints[ inputjoint.jointName ] === undefined ) { + + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + + hand.add( joint ); + + } + + return hand.joints[ inputjoint.jointName ]; + + } + +} + +class DepthTexture extends Texture { + + constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + + format = format !== undefined ? format : DepthFormat; + + if ( format !== DepthFormat && format !== DepthStencilFormat ) { + + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + + } + + if ( type === undefined && format === DepthFormat ) type = UnsignedIntType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isDepthTexture = true; + + this.image = { width: width, height: height }; + + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + + this.flipY = false; + this.generateMipmaps = false; + + } + + +} + +class WebXRManager extends EventDispatcher { + + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + const planes = new Set(); + const planesLastChangedTimes = new Map(); + + // + + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + this.cameraAutoUpdate = true; + this.enabled = false; + + this.isPresenting = false; + + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === - 1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + this.getBinding = function () { + + return glBinding; + + }; + + this.getFrame = function () { + + return xrFrame; + + }; + + this.getSession = function () { + + return session; + + }; + + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) { + + const layerInit = { + antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + encoding: renderer.outputEncoding, + stencilBuffer: attributes.stencil + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? 35056 : 33190; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: 32856, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = new XRWebGLBinding( session, gl ); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + encoding: renderer.outputEncoding, + samples: attributes.antialias ? 4 : 0 + } ); + + const renderTargetProperties = renderer.properties.get( newRenderTarget ); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + // Set foveation to maximum. + this.setFoveation( 1.0 ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === - 1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === - 1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; + + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); + + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; + + } + + const parent = camera.parent; + const cameras = cameraVR.cameras; + + updateCamera( cameraVR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale ); + + // update user camera and its children + + camera.matrix.copy( cameraVR.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + + const children = camera.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].updateMatrixWorld( true ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraVR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + }; + + this.getCamera = function () { + + return cameraVR; + + }; + + this.getFoveation = function () { + + if ( glProjLayer !== null ) { + + return glProjLayer.fixedFoveation; + + } + + if ( glBaseLayer !== null ) { + + return glBaseLayer.fixedFoveation; + + } + + return undefined; + + }; + + this.setFoveation = function ( foveation ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = foveation; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = foveation; + + } + + }; + + this.getPlanes = function () { + + return planes; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraVRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraVR's camera list + + if ( views.length !== cameraVR.cameras.length ) { + + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraVR.matrix.copy( camera.matrix ); + + } + + if ( cameraVRNeedsUpdate === true ) { + + cameraVR.cameras.push( camera ); + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } ); + + let planesToRemove = null; + + for ( const plane of planes ) { + + if ( ! frame.detectedPlanes.has( plane ) ) { + + if ( planesToRemove === null ) { + + planesToRemove = []; + + } + + planesToRemove.push( plane ); + + } + + } + + if ( planesToRemove !== null ) { + + for ( const plane of planesToRemove ) { + + planes.delete( plane ); + planesLastChangedTimes.delete( plane ); + scope.dispatchEvent( { type: 'planeremoved', data: plane } ); + + } + + } + + for ( const plane of frame.detectedPlanes ) { + + if ( ! planes.has( plane ) ) { + + planes.add( plane ); + planesLastChangedTimes.set( plane, frame.lastChangedTime ); + scope.dispatchEvent( { type: 'planeadded', data: plane } ); + + } else { + + const lastKnownTime = planesLastChangedTimes.get( plane ); + + if ( plane.lastChangedTime > lastKnownTime ) { + + planesLastChangedTimes.set( plane, plane.lastChangedTime ); + scope.dispatchEvent( { type: 'planechanged', data: plane } ); + + } + + } + + } + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + +} + +function WebGLMaterials( renderer, properties ) { + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + + // artist-friendly light intensity scaling factor + const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1; + + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. displacementMap map + // 4. normal map + // 5. bump map + // 6. roughnessMap map + // 7. metalnessMap map + // 8. alphaMap map + // 9. emissiveMap map + // 10. clearcoat map + // 11. clearcoat normal map + // 12. clearcoat roughnessMap map + // 13. iridescence map + // 14. iridescence thickness map + // 15. specular intensity map + // 16. specular tint map + // 17. transmission map + // 18. thickness map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.specularMap ) { + + uvScaleMap = material.specularMap; + + } else if ( material.displacementMap ) { + + uvScaleMap = material.displacementMap; + + } else if ( material.normalMap ) { + + uvScaleMap = material.normalMap; + + } else if ( material.bumpMap ) { + + uvScaleMap = material.bumpMap; + + } else if ( material.roughnessMap ) { + + uvScaleMap = material.roughnessMap; + + } else if ( material.metalnessMap ) { + + uvScaleMap = material.metalnessMap; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } else if ( material.emissiveMap ) { + + uvScaleMap = material.emissiveMap; + + } else if ( material.clearcoatMap ) { + + uvScaleMap = material.clearcoatMap; + + } else if ( material.clearcoatNormalMap ) { + + uvScaleMap = material.clearcoatNormalMap; + + } else if ( material.clearcoatRoughnessMap ) { + + uvScaleMap = material.clearcoatRoughnessMap; + + } else if ( material.iridescenceMap ) { + + uvScaleMap = material.iridescenceMap; + + } else if ( material.iridescenceThicknessMap ) { + + uvScaleMap = material.iridescenceThicknessMap; + + } else if ( material.specularIntensityMap ) { + + uvScaleMap = material.specularIntensityMap; + + } else if ( material.specularColorMap ) { + + uvScaleMap = material.specularColorMap; + + } else if ( material.transmissionMap ) { + + uvScaleMap = material.transmissionMap; + + } else if ( material.thicknessMap ) { + + uvScaleMap = material.thicknessMap; + + } else if ( material.sheenColorMap ) { + + uvScaleMap = material.sheenColorMap; + + } else if ( material.sheenRoughnessMap ) { + + uvScaleMap = material.sheenRoughnessMap; + + } + + if ( uvScaleMap !== undefined ) { + + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { + + uvScaleMap = uvScaleMap.texture; + + } + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map + + let uv2ScaleMap; + + if ( material.aoMap ) { + + uv2ScaleMap = material.aoMap; + + } else if ( material.lightMap ) { + + uv2ScaleMap = material.lightMap; + + } + + if ( uv2ScaleMap !== undefined ) { + + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { + + uv2ScaleMap = uv2ScaleMap.texture; + + } + + if ( uv2ScaleMap.matrixAutoUpdate === true ) { + + uv2ScaleMap.updateMatrix(); + + } + + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map + + let uvScaleMap; + + if ( material.map ) { + + uvScaleMap = material.map; + + } else if ( material.alphaMap ) { + + uvScaleMap = material.alphaMap; + + } + + if ( uvScaleMap !== undefined ) { + + if ( uvScaleMap.matrixAutoUpdate === true ) { + + uvScaleMap.updateMatrix(); + + } + + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + } + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + } + + const envMap = properties.get( material ).envMap; + + if ( envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + } + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + +} + +function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( 35345, buffer ); + gl.bufferData( 35345, size, usage ); + gl.bindBuffer( 35345, null ); + gl.bindBufferBase( 35345, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === - 1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( 35345, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniform = uniforms[ i ]; + + // partly update the buffer if necessary + + if ( hasUniformChanged( uniform, i, cache ) === true ) { + + const offset = uniform.__offset; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + let arrayOffset = 0; + + for ( let i = 0; i < values.length; i ++ ) { + + const value = values[ i ]; + + const info = getUniformSize( value ); + + if ( typeof value === 'number' ) { + + uniform.__data[ 0 ] = value; + gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data ); + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + uniform.__data[ 0 ] = value.elements[ 0 ]; + uniform.__data[ 1 ] = value.elements[ 1 ]; + uniform.__data[ 2 ] = value.elements[ 2 ]; + uniform.__data[ 3 ] = value.elements[ 0 ]; + uniform.__data[ 4 ] = value.elements[ 3 ]; + uniform.__data[ 5 ] = value.elements[ 4 ]; + uniform.__data[ 6 ] = value.elements[ 5 ]; + uniform.__data[ 7 ] = value.elements[ 0 ]; + uniform.__data[ 8 ] = value.elements[ 6 ]; + uniform.__data[ 9 ] = value.elements[ 7 ]; + uniform.__data[ 10 ] = value.elements[ 8 ]; + uniform.__data[ 11 ] = value.elements[ 0 ]; + + } else { + + value.toArray( uniform.__data, arrayOffset ); + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + gl.bufferSubData( 35345, offset, uniform.__data ); + + } + + } + + gl.bindBuffer( 35345, null ); + + } + + function hasUniformChanged( uniform, index, cache ) { + + const value = uniform.value; + + if ( cache[ index ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' ) { + + cache[ index ] = value; + + } else { + + const values = Array.isArray( value ) ? value : [ value ]; + + const tempValues = []; + + for ( let i = 0; i < values.length; i ++ ) { + + tempValues.push( values[ i ].clone() ); + + } + + cache[ index ] = tempValues; + + } + + return true; + + } else { + + // compare current value with cached entry + + if ( typeof value === 'number' ) { + + if ( cache[ index ] !== value ) { + + cache[ index ] = value; + return true; + + } + + } else { + + const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ]; + const values = Array.isArray( value ) ? value : [ value ]; + + for ( let i = 0; i < cachedObjects.length; i ++ ) { + + const cachedObject = cachedObjects[ i ]; + + if ( cachedObject.equals( values[ i ] ) === false ) { + + cachedObject.copy( values[ i ] ); + return true; + + } + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + let chunkOffset = 0; // offset within a single chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniform = uniforms[ i ]; + + const infos = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let j = 0, jl = values.length; j < jl; j ++ ) { + + const value = values[ j ]; + + const info = getUniformSize( value ); + + infos.boundary += info.boundary; + infos.storage += info.storage; + + } + + // the following two properties will be used for partial buffer updates + + uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // + + if ( i > 0 ) { + + chunkOffset = offset % chunkSize; + + const remainingSizeInChunk = chunkSize - chunkOffset; + + // check for chunk overflow + + if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) { + + // add padding and adjust offset + + offset += ( chunkSize - chunkOffset ); + uniform.__offset = offset; + + } + + } + + offset += infos.storage; + + } + + // ensure correct final padding + + chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' ) { + + // float/int + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + +} + +function createCanvasElement() { + + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; + +} + +function WebGLRenderer( parameters = {} ) { + + this.isWebGLRenderer = true; + + const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(), + _context = parameters.context !== undefined ? parameters.context : null, + + _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, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + + let _alpha; + + if ( _context !== null ) { + + _alpha = _context.getContextAttributes().alpha; + + } else { + + _alpha = parameters.alpha !== undefined ? parameters.alpha : false; + + } + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // public properties + + this.domElement = _canvas; + + // Debug configuration container + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; + + // clearing + + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + + // scene graph + + this.sortObjects = true; + + // user-defined clipping + + this.clippingPlanes = []; + this.localClippingEnabled = false; + + // physically based shading + + this.outputEncoding = LinearEncoding; + + // physical lights + + this.physicallyCorrectLights = false; + + // tone mapping + + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + + // internal state cache + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = - 1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + // + + let _width = _canvas.width; + let _height = _canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // transmission + + let _transmissionRenderTarget = null; + + // camera matrices cache + + const _projScreenMatrix = new Matrix4(); + + const _vector2 = new Vector2(); + const _vector3 = new Vector3(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = _context; + + function getContext( contextNames, contextAttributes ) { + + for ( let i = 0; i < contextNames.length; i ++ ) { + + const contextName = contextNames[ i ]; + const context = _canvas.getContext( contextName, contextAttributes ); + if ( context !== null ) return context; + + } + + return null; + + } + + try { + + const contextAttributes = { + alpha: true, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ]; + + if ( _this.isWebGL1Renderer === true ) { + + contextNames.shift(); + + } + + _gl = getContext( contextNames, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextNames ) ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'Error creating WebGL context.' ); + + } + + } + + } + + // Some experimental-webgl implementations do not have getShaderPrecisionFormat + + if ( _gl.getShaderPrecisionFormat === undefined ) { + + _gl.getShaderPrecisionFormat = function () { + + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + + }; + + } + + } catch ( error ) { + + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + + extensions.init( capabilities ); + + utils = new WebGLUtils( _gl, extensions, capabilities ); + + state = new WebGLState( _gl, extensions, capabilities ); + + info = new WebGLInfo(); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl, capabilities ); + bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions, capabilities ); + background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + + info.programs = programCache.programs; + + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + + } + + initGLContext(); + + // xr + + const xr = new WebXRManager( _this, _gl ); + + this.xr = xr; + + // API + + this.getContext = function () { + + return _gl; + + }; + + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + this.setSize = function ( width, height, updateStyle ) { + + if ( xr.isPresenting ) { + + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle !== false ) { + + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; + + } + + this.setViewport( 0, 0, width, height ); + + }; + + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + + }; + + this.getScissorTest = function () { + + return _scissorTest; + + }; + + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + this.setClearColor = function () { + + background.setClearColor.apply( background, arguments ); + + }; + + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + this.setClearAlpha = function () { + + background.setClearAlpha.apply( background, arguments ); + + }; + + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) bits |= 16384; + if ( depth ) bits |= 256; + if ( stencil ) bits |= 1024; + + _gl.clear( bits ); + + }; + + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + // + + this.dispose = function () { + + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + if ( _transmissionRenderTarget ) { + + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; + + } + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + console.log( 'THREE.WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + console.log( 'THREE.WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( 1 ); + + } else { + + renderer.setMode( 4 ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( 1 ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( 2 ); + + } else { + + renderer.setMode( 3 ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( 0 ); + + } else if ( object.isSprite ) { + + renderer.setMode( 4 ); + + } + + if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + this.compile = function ( scene, camera ) { + + function prepare( material, scene, object ) { + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = TwoPassDoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + currentRenderState = renderStates.get( scene ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + scene.traverse( function ( object ) { + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepare( material2, scene, object ); + + } + + } else { + + prepare( material, scene, object ); + + } + + } + + } ); + + renderStateStack.pop(); + currentRenderState = null; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init(); + + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + // + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + if ( this.info.autoReset === true ) this.info.reset(); + + // + + background.render( currentRenderList, scene ); + + // render scene + + currentRenderState.setupLights( _this.physicallyCorrectLights ); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + renderScene( currentRenderList, scene, camera ); + + } + + // + + if ( _currentRenderTarget !== null ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = - 1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( object.isSkinnedMesh ) { + + // update skeleton only once in a frame + + if ( object.skeleton.frame !== info.render.frame ) { + + object.skeleton.update(); + object.skeleton.frame = info.render.frame; + + } + + } + + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + + if ( sortObjects ) { + + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, scene, camera ) { + + const isWebGL2 = capabilities.isWebGL2; + + if ( _transmissionRenderTarget === null ) { + + _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: ( isWebGL2 && _antialias === true ) ? 4 : 0 + } ); + + } + + _this.getDrawingBufferSize( _vector2 ); + + if ( isWebGL2 ) { + + _transmissionRenderTarget.setSize( _vector2.x, _vector2.y ); + + } else { + + _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) ); + + } + + // + + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( _transmissionRenderTarget ); + _this.clear(); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + renderObjects( opaqueObjects, scene, camera ); + + _this.toneMapping = currentToneMapping; + + textures.updateMultisampleRenderTarget( _transmissionRenderTarget ); + textures.updateRenderTargetMipmap( _transmissionRenderTarget ); + + _this.setRenderTarget( currentRenderTarget ); + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === TwoPassDoubleSide ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = TwoPassDoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + material.onBuild( object, parameters, _this ); + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + const progUniforms = program.getUniforms(); + const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + + materialProperties.currentProgram = program; + materialProperties.uniformsList = uniformsList; + + return program; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputEncoding = parameters.outputEncoding; + materialProperties.instancing = parameters.instancing; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent; + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const 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, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputEncoding !== encoding ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // 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: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + // load material specific uniforms + // (shader material also gets them for the sake of genericity) + + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.isShadowMaterial || + object.isSkinnedMesh ) { + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( capabilities.floatVertexTextures ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + + } else { + + console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' ); + + } + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) { + + morphtargets.update( object, geometry, material, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { + + m_uniforms.envMap.value = envMap; + + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1; + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // 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 + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget ); + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + if ( capabilities.isWebGL2 ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' ); + + } + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture; + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__hasExternalTextures = true; + + if ( renderTargetProperties.__hasExternalTextures ) { + + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + + if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) { + + console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' ); + renderTargetProperties.__useRenderToTexture = false; + + } + + } + + } + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( 36160, null ); + useDefaultFramebuffer = false; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + isCube = true; + + } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + framebuffer = __webglFramebuffer; + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + const framebufferBound = state.bindFramebuffer( 36160, framebuffer ); + + if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer ); + + } + + _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings + + }; + + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( 36160, framebuffer ); + + try { + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) ); + + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! halfFloatSupportedByExt ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( 36160, framebuffer ); + + } + + } + + }; + + this.copyFramebufferToTexture = function ( position, texture, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) { + + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + + textures.setTexture2D( dstTexture, 0 ); + + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + + } else { + + if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); + + } else { + + _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); + + } + + } + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); + + state.unbindTexture(); + + }; + + this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) { + + if ( _this.isWebGL1Renderer ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' ); + return; + + } + + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = 32879; + + } else if ( dstTexture.isDataArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = 35866; + + } else { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' ); + return; + + } + + _gl.pixelStorei( 37440, dstTexture.flipY ); + _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( 3317, dstTexture.unpackAlignment ); + + const unpackRowLen = _gl.getParameter( 3314 ); + const unpackImageHeight = _gl.getParameter( 32878 ); + const unpackSkipPixels = _gl.getParameter( 3316 ); + const unpackSkipRows = _gl.getParameter( 3315 ); + const unpackSkipImages = _gl.getParameter( 32877 ); + + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image; + + _gl.pixelStorei( 3314, image.width ); + _gl.pixelStorei( 32878, image.height ); + _gl.pixelStorei( 3316, sourceBox.min.x ); + _gl.pixelStorei( 3315, sourceBox.min.y ); + _gl.pixelStorei( 32877, sourceBox.min.z ); + + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data ); + + } else { + + if ( srcTexture.isCompressedArrayTexture ) { + + console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' ); + _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image ); + + } + + } + + _gl.pixelStorei( 3314, unpackRowLen ); + _gl.pixelStorei( 32878, unpackImageHeight ); + _gl.pixelStorei( 3316, unpackSkipPixels ); + _gl.pixelStorei( 3315, unpackSkipRows ); + _gl.pixelStorei( 32877, unpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget ); + + state.unbindTexture(); + + }; + + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + +} + +class WebGL1Renderer extends WebGLRenderer {} + +WebGL1Renderer.prototype.isWebGL1Renderer = true; + +class FogExp2 { + + constructor( color, density = 0.00025 ) { + + this.isFogExp2 = true; + + this.name = ''; + + this.color = new Color( color ); + this.density = density; + + } + + clone() { + + return new FogExp2( this.color, this.density ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; + + } + +} + +class Fog { + + constructor( color, near = 1, far = 1000 ) { + + this.isFog = true; + + this.name = ''; + + this.color = new Color( color ); + + this.near = near; + this.far = far; + + } + + clone() { + + return new Fog( this.color, this.near, this.far ); + + } + + toJSON( /* meta */ ) { + + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; + + } + +} + +class Scene extends Object3D { + + constructor() { + + super(); + + this.isScene = true; + + this.type = 'Scene'; + + this.background = null; + this.environment = null; + this.fog = null; + + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + + this.overrideMaterial = null; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness; + if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity; + + return data; + + } + + // @deprecated + + get autoUpdate() { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + return this.matrixWorldAutoUpdate; + + } + + set autoUpdate( value ) { + + console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' ); + this.matrixWorldAutoUpdate = value; + + } + +} + +class InterleavedBuffer { + + constructor( array, stride ) { + + this.isInterleavedBuffer = true; + + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; + + this.version = 0; + + this.uuid = generateUUID(); + + } + + onUploadCallback() {} + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + copy( source ) { + + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + + return this; + + } + + copyAt( index1, attribute, index2 ) { + + index1 *= this.stride; + index2 *= attribute.stride; + + for ( let i = 0, l = this.stride; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + set( value, offset = 0 ) { + + this.array.set( value, offset ); + + return this; + + } + + clone( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + + } + + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); + + return ib; + + } + + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + toJSON( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + // generate UUID for array buffer if necessary + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); + + } + + // + + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + + } + +} + +const _vector$6 = /*@__PURE__*/ new Vector3(); + +class InterleavedBufferAttribute { + + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + + this.isInterleavedBufferAttribute = true; + + this.name = ''; + + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + + this.normalized = normalized; + + } + + get count() { + + return this.data.count; + + } + + get array() { + + return this.data.array; + + } + + set needsUpdate( value ) { + + this.data.needsUpdate = value; + + } + + applyMatrix4( m ) { + + for ( let i = 0, l = this.data.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyMatrix4( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$6.fromBufferAttribute( this, i ); + + _vector$6.transformDirection( m ); + + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); + + } + + return this; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.data.array[ index * this.data.stride + this.offset ] = x; + + return this; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + + return this; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + + return this; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + + return this; + + } + + getX( index ) { + + let x = this.data.array[ index * this.data.stride + this.offset ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + getY( index ) { + + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + getZ( index ) { + + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + getW( index ) { + + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setXY( index, x, y ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + + return this; + + } + + setXYZ( index, x, y, z ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; + + return this; + + } + + clone( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + + } else { + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + + } + + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + + } + + } + + toJSON( data ) { + + if ( data === undefined ) { + + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + // de-interleave data and save it as an ordinary buffer attribute for now + + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; + + } else { + + // save as true interleaved attribute + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + + } + + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + + } + + } + +} + +class SpriteMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isSpriteMaterial = true; + + this.type = 'SpriteMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.rotation = 0; + + this.sizeAttenuation = true; + + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.rotation = source.rotation; + + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +let _geometry; + +const _intersectPoint = /*@__PURE__*/ new Vector3(); +const _worldScale = /*@__PURE__*/ new Vector3(); +const _mvPosition = /*@__PURE__*/ new Vector3(); + +const _alignedPosition = /*@__PURE__*/ new Vector2(); +const _rotatedPosition = /*@__PURE__*/ new Vector2(); +const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _vA = /*@__PURE__*/ new Vector3(); +const _vB = /*@__PURE__*/ new Vector3(); +const _vC = /*@__PURE__*/ new Vector3(); + +const _uvA = /*@__PURE__*/ new Vector2(); +const _uvB = /*@__PURE__*/ new Vector2(); +const _uvC = /*@__PURE__*/ new Vector2(); + +class Sprite extends Object3D { + + constructor( material ) { + + super(); + + this.isSprite = true; + + this.type = 'Sprite'; + + if ( _geometry === undefined ) { + + _geometry = new BufferGeometry(); + + const float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); + + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + + } + + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + + this.center = new Vector2( 0.5, 0.5 ); + + } + + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + + } + + _worldScale.setFromMatrixScale( this.matrixWorld ); + + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + + _worldScale.multiplyScalar( - _mvPosition.z ); + + } + + const rotation = this.material.rotation; + let sin, cos; + + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); + + } + + const center = this.center; + + transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); + + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint ); + + if ( intersect === null ) { + + // check second triangle + transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 1 ); + + intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint ); + if ( intersect === null ) { + + return; + + } + + } + + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.center !== undefined ) this.center.copy( source.center ); + + this.material = source.material; + + return this; + + } + +} + +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + + // to check if rotation is not zero + if ( sin !== undefined ) { + + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + + } else { + + _rotatedPosition.copy( _alignedPosition ); + + } + + + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); + +} + +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); + +class LOD extends Object3D { + + constructor() { + + super(); + + this._currentLevel = 0; + + this.type = 'LOD'; + + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true, + } + } ); + + this.autoUpdate = true; + + } + + copy( source ) { + + super.copy( source, false ); + + const levels = source.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + this.addLevel( level.object.clone(), level.distance, level.hysteresis ); + + } + + this.autoUpdate = source.autoUpdate; + + return this; + + } + + addLevel( object, distance = 0, hysteresis = 0 ) { + + distance = Math.abs( distance ); + + const levels = this.levels; + + let l; + + for ( l = 0; l < levels.length; l ++ ) { + + if ( distance < levels[ l ].distance ) { + + break; + + } + + } + + levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } ); + + this.add( object ); + + return this; + + } + + getCurrentLevel() { + + return this._currentLevel; + + } + + + + getObjectForDistance( distance ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance < levelDistance ) { + + break; + + } + + } + + return levels[ i - 1 ].object; + + } + + return null; + + } + + raycast( raycaster, intersects ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + _v1$2.setFromMatrixPosition( this.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); + + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + + } + + } + + update( camera ) { + + const levels = this.levels; + + if ( levels.length > 1 ) { + + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); + + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; + + levels[ 0 ].object.visible = true; + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance >= levelDistance ) { + + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; + + } else { + + break; + + } + + } + + this._currentLevel = i - 1; + + for ( ; i < l; i ++ ) { + + levels[ i ].object.visible = false; + + } + + } + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.autoUpdate === false ) data.object.autoUpdate = false; + + data.object.levels = []; + + const levels = this.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + } ); + + } + + return data; + + } + +} + +const _basePosition = /*@__PURE__*/ new Vector3(); + +const _skinIndex = /*@__PURE__*/ new Vector4(); +const _skinWeight = /*@__PURE__*/ new Vector4(); + +const _vector$5 = /*@__PURE__*/ new Vector3(); +const _matrix = /*@__PURE__*/ new Matrix4(); + +class SkinnedMesh extends Mesh { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isSkinnedMesh = true; + + this.type = 'SkinnedMesh'; + + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); + + this.skeleton = source.skeleton; + + return this; + + } + + bind( skeleton, bindMatrix ) { + + this.skeleton = skeleton; + + if ( bindMatrix === undefined ) { + + this.updateMatrixWorld( true ); + + this.skeleton.calculateInverses(); + + bindMatrix = this.matrixWorld; + + } + + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); + + } + + pose() { + + this.skeleton.pose(); + + } + + normalizeSkinWeights() { + + const vector = new Vector4(); + + const skinWeight = this.geometry.attributes.skinWeight; + + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + + vector.fromBufferAttribute( skinWeight, i ); + + const scale = 1.0 / vector.manhattanLength(); + + if ( scale !== Infinity ) { + + vector.multiplyScalar( scale ); + + } else { + + vector.set( 1, 0, 0, 0 ); // do something reasonable + + } + + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + + } + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.bindMode === 'attached' ) { + + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + + } else if ( this.bindMode === 'detached' ) { + + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + + } else { + + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + + } + + } + + boneTransform( index, target ) { + + const skeleton = this.skeleton; + const geometry = this.geometry; + + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + + _basePosition.copy( target ).applyMatrix4( this.bindMatrix ); + + target.set( 0, 0, 0 ); + + for ( let i = 0; i < 4; i ++ ) { + + const weight = _skinWeight.getComponent( i ); + + if ( weight !== 0 ) { + + const boneIndex = _skinIndex.getComponent( i ); + + _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + + target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight ); + + } + + } + + return target.applyMatrix4( this.bindMatrixInverse ); + + } + +} + +class Bone extends Object3D { + + constructor() { + + super(); + + this.isBone = true; + + this.type = 'Bone'; + + } + +} + +class DataTexture extends Texture { + + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isDataTexture = true; + + this.image = { data: data, width: width, height: height }; + + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + + } + +} + +const _offsetMatrix = /*@__PURE__*/ new Matrix4(); +const _identityMatrix = /*@__PURE__*/ new Matrix4(); + +class Skeleton { + + constructor( bones = [], boneInverses = [] ) { + + this.uuid = generateUUID(); + + this.bones = bones.slice( 0 ); + this.boneInverses = boneInverses; + this.boneMatrices = null; + + this.boneTexture = null; + this.boneTextureSize = 0; + + this.frame = - 1; + + this.init(); + + } + + init() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + + this.boneMatrices = new Float32Array( bones.length * 16 ); + + // calculate inverse bone matrices if necessary + + if ( boneInverses.length === 0 ) { + + this.calculateInverses(); + + } else { + + // handle special case + + if ( bones.length !== boneInverses.length ) { + + console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + + this.boneInverses = []; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + this.boneInverses.push( new Matrix4() ); + + } + + } + + } + + } + + calculateInverses() { + + this.boneInverses.length = 0; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const inverse = new Matrix4(); + + if ( this.bones[ i ] ) { + + inverse.copy( this.bones[ i ].matrixWorld ).invert(); + + } + + this.boneInverses.push( inverse ); + + } + + } + + pose() { + + // recover the bind-time world matrices + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + + } + + } + + // compute the local matrices, positions, rotations and scales + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + if ( bone.parent && bone.parent.isBone ) { + + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); + + } else { + + bone.matrix.copy( bone.matrixWorld ); + + } + + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + + } + + } + + } + + update() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + + // flatten bone matrices to array + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + // compute the offset between the current and the original transform + + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); + + } + + if ( boneTexture !== null ) { + + boneTexture.needsUpdate = true; + + } + + } + + clone() { + + return new Skeleton( this.bones, this.boneInverses ); + + } + + computeBoneTexture() { + + // 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) + + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); + + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values + + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; + + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + this.boneTextureSize = size; + + return this; + + } + + getBoneByName( name ) { + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone.name === name ) { + + return bone; + + } + + } + + return undefined; + + } + + dispose( ) { + + if ( this.boneTexture !== null ) { + + this.boneTexture.dispose(); + + this.boneTexture = null; + + } + + } + + fromJSON( json, bones ) { + + this.uuid = json.uuid; + + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; + + if ( bone === undefined ) { + + console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); + + } + + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + + } + + this.init(); + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; + + data.uuid = this.uuid; + + const bones = this.bones; + const boneInverses = this.boneInverses; + + for ( let i = 0, l = bones.length; i < l; i ++ ) { + + const bone = bones[ i ]; + data.bones.push( bone.uuid ); + + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); + + } + + return data; + + } + +} + +class InstancedBufferAttribute extends BufferAttribute { + + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { + + super( array, itemSize, normalized ); + + this.isInstancedBufferAttribute = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.meshPerAttribute = this.meshPerAttribute; + + data.isInstancedBufferAttribute = true; + + return data; + + } + +} + +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _instanceIntersects = []; + +const _identity = /*@__PURE__*/ new Matrix4(); +const _mesh = /*@__PURE__*/ new Mesh(); + +class InstancedMesh extends Mesh { + + constructor( geometry, material, count ) { + + super( geometry, material ); + + this.isInstancedMesh = true; + + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + this.instanceColor = null; + + this.count = count; + + this.frustumCulled = false; + + for ( let i = 0; i < count; i ++ ) { + + this.setMatrixAt( i, _identity ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.instanceMatrix.copy( source.instanceMatrix ); + + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + + this.count = source.count; + + return this; + + } + + getColorAt( index, color ) { + + color.fromArray( this.instanceColor.array, index * 3 ); + + } + + getMatrixAt( index, matrix ) { + + matrix.fromArray( this.instanceMatrix.array, index * 16 ); + + } + + raycast( raycaster, intersects ) { + + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + + _mesh.geometry = this.geometry; + _mesh.material = this.material; + + if ( _mesh.material === undefined ) return; + + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + + // calculate the world matrix for each instance + + this.getMatrixAt( instanceId, _instanceLocalMatrix ); + + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + + // the mesh represents this single instance + + _mesh.matrixWorld = _instanceWorldMatrix; + + _mesh.raycast( raycaster, _instanceIntersects ); + + // process the result of raycast + + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); + + } + + _instanceIntersects.length = 0; + + } + + } + + setColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 ); + + } + + color.toArray( this.instanceColor.array, index * 3 ); + + } + + setMatrixAt( index, matrix ) { + + matrix.toArray( this.instanceMatrix.array, index * 16 ); + + } + + updateMorphTargets() { + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +class LineBasicMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isLineBasicMaterial = true; + + this.type = 'LineBasicMaterial'; + + this.color = new Color( 0xffffff ); + + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _start$1 = /*@__PURE__*/ new Vector3(); +const _end$1 = /*@__PURE__*/ new Vector3(); +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$1 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); + +class Line extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + + super(); + + this.isLine = true; + + this.type = 'Line'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; + + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + + _start$1.fromBufferAttribute( positionAttribute, i - 1 ); + _end$1.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start$1.distanceTo( _end$1 ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; + + // + + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + + vStart.fromBufferAttribute( positionAttribute, a ); + vEnd.fromBufferAttribute( positionAttribute, b ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + vStart.fromBufferAttribute( positionAttribute, i ); + vEnd.fromBufferAttribute( positionAttribute, i + 1 ); + + const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + + if ( distSq > localThresholdSq ) continue; + + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( interRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) continue; + + intersects.push( { + + 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 + + } ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); + +class LineSegments extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineSegments = true; + + this.type = 'LineSegments'; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); + + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + +} + +class LineLoop extends Line { + + constructor( geometry, material ) { + + super( geometry, material ); + + this.isLineLoop = true; + + this.type = 'LineLoop'; + + } + +} + +class PointsMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isPointsMaterial = true; + + this.type = 'PointsMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + + this.alphaMap = null; + + this.size = 1; + this.sizeAttenuation = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix = /*@__PURE__*/ new Matrix4(); +const _ray = /*@__PURE__*/ new Ray(); +const _sphere = /*@__PURE__*/ new Sphere(); +const _position$2 = /*@__PURE__*/ new Vector3(); + +class Points extends Object3D { + + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + + super(); + + this.isPoints = true; + + this.type = 'Points'; + + this.geometry = geometry; + this.material = material; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = source.material; + this.geometry = source.geometry; + + return this; + + } + + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i ++ ) { + + const a = index.getX( i ); + + _position$2.fromBufferAttribute( positionAttribute, a ); + + testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end; i < l; i ++ ) { + + _position$2.fromBufferAttribute( positionAttribute, i ); + + testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } + + } + + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); + + if ( rayPointDistanceSq < localThresholdSq ) { + + const intersectPoint = new Vector3(); + + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object + + } ); + + } + +} + +class VideoTexture extends Texture { + + constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isVideoTexture = true; + + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + + this.generateMipmaps = false; + + const scope = this; + + function updateVideo() { + + scope.needsUpdate = true; + video.requestVideoFrameCallback( updateVideo ); + + } + + if ( 'requestVideoFrameCallback' in video ) { + + video.requestVideoFrameCallback( updateVideo ); + + } + + } + + clone() { + + return new this.constructor( this.image ).copy( this ); + + } + + update() { + + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; + + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + + this.needsUpdate = true; + + } + + } + +} + +class FramebufferTexture extends Texture { + + constructor( width, height, format ) { + + super( { width, height } ); + + this.isFramebufferTexture = true; + + this.format = format; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.generateMipmaps = false; + + this.needsUpdate = true; + + } + +} + +class CompressedTexture extends Texture { + + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + + this.isCompressedTexture = true; + + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; + + // 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; + + } + +} + +class CompressedArrayTexture extends CompressedTexture { + + constructor( mipmaps, width, height, depth, format, type ) { + + super( mipmaps, width, height, format, type ); + + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + + } + +} + +class CanvasTexture extends Texture { + + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.isCanvasTexture = true; + + this.needsUpdate = true; + + } + +} + +/** + * Extensible curve object. + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ + +class Curve { + + constructor() { + + this.type = 'Curve'; + + this.arcLengthDivisions = 200; + + } + + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + + getPoint( /* t, optionalTarget */ ) { + + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; + + } + + // Get point at relative position in curve according to arc length + // - u [0 .. 1] + + getPointAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); + + } + + // Get sequence of points using getPoint( t ) + + getPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPoint( d / divisions ) ); + + } + + return points; + + } + + // Get sequence of points using getPointAt( u ) + + getSpacedPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); + + } + + return points; + + } + + // Get total curve arc length + + getLength() { + + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; + + } + + // Get list of cumulative segment lengths + + getLengths( divisions = this.arcLengthDivisions ) { + + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; + + } + + this.needsUpdate = false; + + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; + + cache.push( 0 ); + + for ( let 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() { + + this.needsUpdate = true; + this.getLengths(); + + } + + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + + getUtoTmapping( u, distance ) { + + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if ( distance ) { + + targetArcLength = distance; + + } else { + + targetArcLength = u * arcLengths[ il - 1 ]; + + } + + // binary search for the index with largest value smaller than target u distance + + let 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; + + if ( arcLengths[ i ] === targetArcLength ) { + + return i / ( il - 1 ); + + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + + // add that fractional amount to t + + const 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( t, optionalTarget ) { + + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + + // Capping in case of danger + + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); + + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); + + return tangent; + + } + + getTangentAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); + + } + + computeFrenetFrames( segments, closed ) { + + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + + const normal = new Vector3(); + + const tangents = []; + const normals = []; + const binormals = []; + + const vec = new Vector3(); + const mat = new Matrix4(); + + // compute the tangent vectors for each segment on the curve + + for ( let i = 0; i <= segments; i ++ ) { + + const u = i / segments; + + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + + } + + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component + + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); + + if ( tx <= min ) { + + min = tx; + normal.set( 1, 0, 0 ); + + } + + if ( ty <= min ) { + + min = ty; + normal.set( 0, 1, 0 ); + + } + + if ( tz <= min ) { + + normal.set( 0, 0, 1 ); + + } + + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + + + // compute the slowly-varying normal and binormal vectors for each segment on the curve + + for ( let i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( let i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + } + + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( source ) { + + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; + + } + + toJSON() { + + const data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; + + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + + return data; + + } + + fromJSON( json ) { + + this.arcLengthDivisions = json.arcLengthDivisions; + + return this; + + } + +} + +class EllipseCurve extends Curve { + + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + + super(); + + this.isEllipseCurve = true; + + this.type = 'EllipseCurve'; + + this.aX = aX; + this.aY = aY; + + this.xRadius = xRadius; + this.yRadius = yRadius; + + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + + this.aClockwise = aClockwise; + + this.aRotation = aRotation; + + } + + getPoint( t, optionalTarget ) { + + const point = optionalTarget || new Vector2(); + + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + + if ( deltaAngle < Number.EPSILON ) { + + if ( samePoints ) { + + deltaAngle = 0; + + } else { + + deltaAngle = twoPi; + + } + + } + + if ( this.aClockwise === true && ! samePoints ) { + + if ( deltaAngle === twoPi ) { + + deltaAngle = - twoPi; + + } else { + + deltaAngle = deltaAngle - twoPi; + + } + + } + + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); + + if ( this.aRotation !== 0 ) { + + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); + + const tx = x - this.aX; + const 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 point.set( x, y ); + + } + + copy( source ) { + + super.copy( source ); + + this.aX = source.aX; + this.aY = source.aY; + + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + + this.aClockwise = source.aClockwise; + + this.aRotation = source.aRotation; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.aX = this.aX; + data.aY = this.aY; + + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + + data.aClockwise = this.aClockwise; + + data.aRotation = this.aRotation; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.aX = json.aX; + this.aY = json.aY; + + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + + this.aClockwise = json.aClockwise; + + this.aRotation = json.aRotation; + + return this; + + } + +} + +class ArcCurve extends EllipseCurve { + + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + this.isArcCurve = true; + + this.type = 'ArcCurve'; + + } + +} + +/** + * 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 + */ + + +/* +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. +*/ + +function CubicPoly() { + + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * 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. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + + } + + return { + + initCatmullRom: function ( x0, x1, x2, x3, tension ) { + + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + + }, + + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; + + init( x1, x2, t1, t2 ); + + }, + + calc: function ( t ) { + + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + + } + + }; + +} + +// + +const tmp = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); + +class CatmullRomCurve3 extends Curve { + + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + + super(); + + this.isCatmullRomCurve3 = true; + + this.type = 'CatmullRomCurve3'; + + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const points = this.points; + const l = points.length; + + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; + + if ( this.closed ) { + + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + + } else if ( weight === 0 && intPoint === l - 1 ) { + + intPoint = l - 2; + weight = 1; + + } + + let p0, p3; // 4 points (p1 & p2 defined below) + + if ( this.closed || intPoint > 0 ) { + + p0 = points[ ( intPoint - 1 ) % l ]; + + } else { + + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; + + } + + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; + + if ( this.closed || intPoint + 2 < l ) { + + p3 = points[ ( intPoint + 2 ) % l ]; + + } else { + + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; + + } + + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; + + 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.curveType === 'catmullrom' ) { + + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + + } + + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); + + } + + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + + return this; + + } + +} + +/** + * Bezier Curves formulas obtained from + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve + */ + +function CatmullRom( t, p0, p1, p2, p3 ) { + + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + +} + +// + +function QuadraticBezierP0( t, p ) { + + const k = 1 - t; + return k * k * p; + +} + +function QuadraticBezierP1( t, p ) { + + return 2 * ( 1 - t ) * t * p; + +} + +function QuadraticBezierP2( t, p ) { + + return t * t * p; + +} + +function QuadraticBezier( t, p0, p1, p2 ) { + + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); + +} + +// + +function CubicBezierP0( t, p ) { + + const k = 1 - t; + return k * k * k * p; + +} + +function CubicBezierP1( t, p ) { + + const k = 1 - t; + return 3 * k * k * t * p; + +} + +function CubicBezierP2( t, p ) { + + return 3 * ( 1 - t ) * t * t * p; + +} + +function CubicBezierP3( t, p ) { + + return t * t * t * p; + +} + +function CubicBezier( t, p0, p1, p2, p3 ) { + + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); + +} + +class CubicBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + + super(); + + this.isCubicBezierCurve = true; + + this.type = 'CubicBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class CubicBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + + super(); + + this.isCubicBezierCurve3 = true; + + this.type = 'CubicBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +class LineCurve extends Curve { + + constructor( v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isLineCurve = true; + + this.type = 'LineCurve'; + + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget ) { + + const tangent = optionalTarget || new Vector2(); + + tangent.copy( this.v2 ).sub( this.v1 ).normalize(); + + return tangent; + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class LineCurve3 extends Curve { + + constructor( v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isLineCurve3 = true; + + this.type = 'LineCurve3'; + + this.v1 = v1; + this.v2 = v2; + + } + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve extends Curve { + + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + this.isQuadraticBezierCurve = true; + + this.type = 'QuadraticBezierCurve'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class QuadraticBezierCurve3 extends Curve { + + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + this.isQuadraticBezierCurve3 = true; + + this.type = 'QuadraticBezierCurve3'; + + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +class SplineCurve extends Curve { + + constructor( points = [] ) { + + super(); + + this.isSplineCurve = true; + + this.type = 'SplineCurve'; + + this.points = points; + + } + + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const points = this.points; + const p = ( points.length - 1 ) * t; + + const intPoint = Math.floor( p ); + const weight = p - intPoint; + + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); + + } + + return this; + + } + +} + +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); + +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ + +class CurvePath extends Curve { + + constructor() { + + super(); + + this.type = 'CurvePath'; + + this.curves = []; + this.autoClose = false; // Automatically closes the path + + } + + add( curve ) { + + this.curves.push( curve ); + + } + + closePath() { + + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + + if ( ! startPoint.equals( endPoint ) ) { + + this.curves.push( new LineCurve( endPoint, startPoint ) ); + + } + + } + + // 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( t, optionalTarget ) { + + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + + // To think about boundaries points. + + while ( i < curveLengths.length ) { + + if ( curveLengths[ i ] >= d ) { + + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; + + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt( u, optionalTarget ); + + } + + 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; + + } + + copy( source ) { + + super.copy( source ); + + this.curves = []; + + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + + const curve = source.curves[ i ]; + + this.curves.push( curve.clone() ); + + } + + this.autoClose = source.autoClose; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.autoClose = this.autoClose; + data.curves = []; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.autoClose = json.autoClose; + this.curves = []; + + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + + } + + return this; + + } + +} + +class Path extends CurvePath { + + constructor( points ) { + + super(); + + this.type = 'Path'; + + this.currentPoint = new Vector2(); + + if ( points ) { + + this.setFromPoints( points ); + + } + + } + + setFromPoints( points ) { + + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } + + return this; + + } + + moveTo( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + return this; + + } + + lineTo( x, y ) { + + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + const 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 ); + + return this; + + } + + splineThru( pts /*Array of Vector*/ ) { + + const npts = [ this.currentPoint.clone() ].concat( pts ); + + const curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + return this; + + } + + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + return this; + + } + + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const 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 + const firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; + + } + + copy( source ) { + + super.copy( source ); + + this.currentPoint.copy( source.currentPoint ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; + + } + +} + +class LatheGeometry extends BufferGeometry { + + constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + + super(); + + this.type = 'LatheGeometry'; + + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + segments = Math.floor( segments ); + + // clamp phiLength so it's in range of [ 0, 2PI ] + + phiLength = clamp( phiLength, 0, Math.PI * 2 ); + + // buffers + + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + + // helper variables + + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + + // pre-compute normals for initial "meridian" + + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + + switch ( j ) { + + case 0: // special handling for 1st vertex on path + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + prevNormal.copy( normal ); + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + break; + + case ( points.length - 1 ): // special handling for last Vertex on path + + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); + + break; + + default: // default handling for all vertices in between + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + curNormal.copy( normal ); + + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + prevNormal.copy( curNormal ); + + } + + } + + // generate vertices, uvs and normals + + for ( let i = 0; i <= segments; i ++ ) { + + const phi = phiStart + i * inverseSegments * phiLength; + + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); + + for ( let 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.push( vertex.x, vertex.y, vertex.z ); + + // uv + + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + + uvs.push( uv.x, uv.y ); + + // normal + + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; + + normals.push( x, y, z ); + + } + + } + + // indices + + for ( let i = 0; i < segments; i ++ ) { + + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + + const base = j + i * points.length; + + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + + // faces + + indices.push( a, b, d ); + indices.push( c, d, b ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + + } + + static fromJSON( data ) { + + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); + + } + +} + +class CapsuleGeometry extends LatheGeometry { + + constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) { + + const path = new Path(); + path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 ); + path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 ); + + super( path.getPoints( capSegments ), radialSegments ); + + this.type = 'CapsuleGeometry'; + + this.parameters = { + radius: radius, + height: length, + capSegments: capSegments, + radialSegments: radialSegments, + }; + + } + + static fromJSON( data ) { + + return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments ); + + } + +} + +class CircleGeometry extends BufferGeometry { + + constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CircleGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + segments = Math.max( 3, segments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + const segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( let i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); + + } + +} + +class CylinderGeometry extends BufferGeometry { + + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CylinderGeometry'; + + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + const scope = this; + + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + + // generate geometry + + generateTorso(); + + if ( openEnded === false ) { + + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generateTorso() { + + const normal = new Vector3(); + const vertex = new Vector3(); + + let groupCount = 0; + + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; + + // generate vertices, normals and uvs + + for ( let y = 0; y <= heightSegments; y ++ ) { + + const indexRow = []; + + const v = y / heightSegments; + + // calculate the radius of the current row + + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + + const theta = u * thetaLength + thetaStart; + + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, 1 - v ); + + // save index of vertex in respective row + + indexRow.push( index ++ ); + + } + + // now save vertices of the row in our index array + + indexArray.push( indexRow ); + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + for ( let y = 0; y < heightSegments; y ++ ) { + + // we use the index array to access the correct indices + + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // update group counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, 0 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + function generateCap( top ) { + + // save the index of the first center vertex + const centerIndexStart = index; + + const uv = new Vector2(); + const vertex = new Vector3(); + + let groupCount = 0; + + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : - 1; + + // 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 + + for ( let x = 1; x <= radialSegments; x ++ ) { + + // vertex + + vertices.push( 0, halfHeight * sign, 0 ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uvs.push( 0.5, 0.5 ); + + // increase index + + index ++; + + } + + // save the index of the last center vertex + const centerIndexEnd = index; + + // now we generate the surrounding vertices, normals and uvs + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); + + // increase index + + index ++; + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + + if ( top === true ) { + + // face top + + indices.push( i, i + 1, c ); + + } else { + + // face bottom + + indices.push( i + 1, i, c ); + + } + + groupCount += 3; + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + } + + static fromJSON( data ) { + + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +class ConeGeometry extends CylinderGeometry { + + constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super( 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 + }; + + } + + static fromJSON( data ) { + + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +class PolyhedronGeometry extends BufferGeometry { + + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { + + super(); + + this.type = 'PolyhedronGeometry'; + + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; + + // default buffer data + + const vertexBuffer = []; + const uvBuffer = []; + + // the subdivision creates the vertex buffer data + + subdivide( detail ); + + // all vertices should lie on a conceptual sphere with a given radius + + applyRadius( radius ); + + // finally, create the uv data + + generateUVs(); + + // build non-indexed geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + + if ( detail === 0 ) { + + this.computeVertexNormals(); // flat normals + + } else { + + this.normalizeNormals(); // smooth normals + + } + + // helper functions + + function subdivide( detail ) { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + // iterate over all faces and apply a subdivision with the given detail value + + for ( let i = 0; i < indices.length; i += 3 ) { + + // get the vertices of the face + + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); + + // perform subdivision + + subdivideFace( a, b, c, detail ); + + } + + } + + function subdivideFace( a, b, c, detail ) { + + const cols = detail + 1; + + // we use this multidimensional array as a data structure for creating the subdivision + + const v = []; + + // construct all of the vertices for this subdivision + + for ( let i = 0; i <= cols; i ++ ) { + + v[ i ] = []; + + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); + + const rows = cols - i; + + for ( let j = 0; j <= rows; j ++ ) { + + if ( j === 0 && i === cols ) { + + v[ i ][ j ] = aj; + + } else { + + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + + } + + } + + } + + // construct all of the faces + + for ( let i = 0; i < cols; i ++ ) { + + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + + const k = Math.floor( j / 2 ); + + if ( j % 2 === 0 ) { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); + + } else { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + + } + + } + + } + + } + + function applyRadius( radius ) { + + const vertex = new Vector3(); + + // iterate over the entire buffer and apply the radius to each vertex + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + vertex.normalize().multiplyScalar( radius ); + + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; + + } + + } + + function generateUVs() { + + const vertex = new Vector3(); + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); + + } + + correctUVs(); + + correctSeam(); + + } + + function correctSeam() { + + // handle case when face straddles the seam, see #3269 + + for ( let i = 0; i < uvBuffer.length; i += 6 ) { + + // uv data of a single face + + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; + + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); + + // 0.9 is somewhat arbitrary + + if ( max > 0.9 && min < 0.1 ) { + + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + + } + + } + + } + + function pushVertex( vertex ) { + + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + + } + + function getVertexByIndex( index, vertex ) { + + const stride = index * 3; + + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; + + } + + function correctUVs() { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + const centroid = new Vector3(); + + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { + + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + + const azi = azimuth( centroid ); + + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); + + } + + } + + function correctUV( uv, stride, vector, azimuth ) { + + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + + uvBuffer[ stride ] = uv.x - 1; + + } + + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + + } + + } + + // Angle around the Y axis, counter-clockwise when looking from above. + + function azimuth( vector ) { + + return Math.atan2( vector.z, - vector.x ); + + } + + + // Angle above the XZ plane. + + function inclination( vector ) { + + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + + } + + } + + static fromJSON( data ) { + + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details ); + + } + +} + +class DodecahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'DodecahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new DodecahedronGeometry( data.radius, data.detail ); + + } + +} + +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); + +class EdgesGeometry extends BufferGeometry { + + constructor( geometry = null, thresholdAngle = 1 ) { + + super(); + + this.type = 'EdgesGeometry'; + + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; + + if ( geometry !== null ) { + + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); + + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); + + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { + + if ( indexAttr ) { + + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); + + } else { + + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; + + } + + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); + + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + + continue; + + } + + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { + + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; + + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); + + } + + edgeData[ reverseHash ] = null; + + } else if ( ! ( hash in edgeData ) ) { + + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { + + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), + + }; + + } + + } + + } + + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { + + if ( edgeData[ key ] ) { + + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); + + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); + + } + + } + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + +} + +class Shape extends Path { + + constructor( points ) { + + super( points ); + + this.uuid = generateUUID(); + + this.type = 'Shape'; + + this.holes = []; + + } + + getPointsHoles( divisions ) { + + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + + } + + return holesPts; + + } + + // get points of shape and holes (keypoints based on segments parameter) + + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; + + } + + copy( source ) { + + super.copy( source ); + + this.holes = []; + + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + + const hole = source.holes[ i ]; + + this.holes.push( hole.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.uuid = this.uuid; + data.holes = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.uuid = json.uuid; + this.holes = []; + + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); + + } + + return this; + + } + +} + +/** + * Port from https://github.com/mapbox/earcut (v2.2.4) + */ + +const Earcut = { + + triangulate: function ( data, holeIndices, dim = 2 ) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length; + let outerNode = linkedList( data, 0, outerLen, dim, true ); + const triangles = []; + + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; + + let minX, minY, maxX, maxY, x, y, invSize; + + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { + + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; + + for ( let i = dim; i < outerLen; i += dim ) { + + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 32767 / invSize : 0; + + } + + earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 ); + + return triangles; + + } + +}; + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { + + let i, last; + + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } else { + + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); + + } + + if ( last && equals( last, last.next ) ) { + + removeNode( last ); + last = last.next; + + } + + return last; + +} + +// eliminate colinear or duplicate points +function filterPoints( start, end ) { + + if ( ! start ) return start; + if ( ! end ) end = start; + + let p = start, + again; + do { + + again = false; + + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; + + } else { + + p = p.next; + + } + + } while ( again || p !== end ); + + return end; + +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + + if ( ! ear ) return; + + // interlink polygon nodes in z-order + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); + + let stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { + + prev = ear.prev; + next = ear.next; + + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + + // cut off the triangle + triangles.push( prev.i / dim | 0 ); + triangles.push( ear.i / dim | 0 ); + triangles.push( next.i / dim | 0 ); + + removeNode( ear ); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { + + // try filtering points and slicing again + if ( ! pass ) { + + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); + + // if this didn't work, try curing all small self-intersections locally + + } else if ( pass === 1 ) { + + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); + + // as a last resort, try splitting the remaining polygon into two + + } else if ( pass === 2 ) { + + splitEarcut( ear, triangles, dim, minX, minY, invSize ); + + } + + break; + + } + + } + +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + let p = c.next; + while ( p !== a ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; + + } + + return true; + +} + +function isEarHashed( ear, minX, minY, invSize ) { + + const a = ear.prev, + b = ear, + c = ear.next; + + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ), + y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ), + x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ), + y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy ); + + // z-order range for the current triangle bbox; + const minZ = zOrder( x0, y0, minX, minY, invSize ), + maxZ = zOrder( x1, y1, minX, minY, invSize ); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { + + if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; + + } + + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { + + if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; + + } + + return true; + +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { + + let p = start; + do { + + const a = p.prev, + b = p.next.next; + + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + + triangles.push( a.i / dim | 0 ); + triangles.push( p.i / dim | 0 ); + triangles.push( b.i / dim | 0 ); + + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); + + p = start = b; + + } + + p = p.next; + + } while ( p !== start ); + + return filterPoints( p ); + +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + + let b = a.next.next; + while ( b !== a.prev ) { + + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + + // split the polygon in two by the diagonal + let c = splitPolygon( a, b ); + + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); + + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize, 0 ); + earcutLinked( c, triangles, dim, minX, minY, invSize, 0 ); + return; + + } + + b = b.next; + + } + + a = a.next; + + } while ( a !== start ); + +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { + + const queue = []; + let i, len, start, end, list; + + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { + + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); + + } + + queue.sort( compareX ); + + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { + + outerNode = eliminateHole( queue[ i ], outerNode ); + + } + + return outerNode; + +} + +function compareX( a, b ) { + + return a.x - b.x; + +} + +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole( hole, outerNode ) { + + const bridge = findHoleBridge( hole, outerNode ); + if ( ! bridge ) { + + return outerNode; + + } + + const bridgeReverse = splitPolygon( bridge, hole ); + + // filter collinear points around the cuts + filterPoints( bridgeReverse, bridgeReverse.next ); + return filterPoints( bridge, bridge.next ); + +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { + + let p = outerNode, + qx = - Infinity, + m; + + const hx = hole.x, hy = hole.y; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { + + const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { + + qx = x; + m = p.x < p.next.x ? p : p.next; + if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint + + } + + } + + p = p.next; + + } while ( p !== outerNode ); + + if ( ! m ) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m, + mx = m.x, + my = m.y; + let tanMin = Infinity, tan; + + p = m; + + do { + + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { + + m = p; + tanMin = tan; + + } + + } + + p = p.next; + + } while ( p !== stop ); + + return m; + +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { + + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; + +} + +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { + + let p = start; + do { + + if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + + } while ( p !== start ); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked( p ); + +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { + + let i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + + p = list; + list = null; + tail = null; + numMerges = 0; + + while ( p ) { + + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { + + pSize ++; + q = q.nextZ; + if ( ! q ) break; + + } + + qSize = inSize; + + while ( pSize > 0 || ( qSize > 0 && q ) ) { + + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + + e = p; + p = p.nextZ; + pSize --; + + } else { + + e = q; + q = q.nextZ; + qSize --; + + } + + if ( tail ) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + + } + + p = q; + + } + + tail.nextZ = null; + inSize *= 2; + + } while ( numMerges > 1 ); + + return list; + +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { + + // coords are transformed into non-negative 15-bit integer range + x = ( x - minX ) * invSize | 0; + y = ( y - minY ) * invSize | 0; + + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; + + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; + + return x | ( y << 1 ); + +} + +// find the leftmost node of a polygon ring +function getLeftmost( start ) { + + let p = start, + leftmost = start; + do { + + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; + + } while ( p !== start ); + + return leftmost; + +} + +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + + return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) && + ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) && + ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py ); + +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { + + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case + +} + +// signed area of a triangle +function area( p, q, r ) { + + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); + +} + +// check if two points are equal +function equals( p1, p2 ) { + + return p1.x === p2.x && p1.y === p2.y; + +} + +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { + + const o1 = sign( area( p1, q1, p2 ) ); + const o2 = sign( area( p1, q1, q2 ) ); + const o3 = sign( area( p2, q2, p1 ) ); + const o4 = sign( area( p2, q2, q1 ) ); + + if ( o1 !== o2 && o3 !== o4 ) return true; // general case + + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { + + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); + +} + +function sign( num ) { + + return num > 0 ? 1 : num < 0 ? - 1 : 0; + +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { + + let p = a; + do { + + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; + + } while ( p !== a ); + + return false; + +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { + + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { + + let p = a, + inside = false; + const px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { + + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; + + } while ( p !== a ); + + return inside; + +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { + + const a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { + + const p = new Node( i, x, y ); + + if ( ! last ) { + + p.prev = p; + p.next = p; + + } else { + + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + + } + + return p; + +} + +function removeNode( p ) { + + p.next.prev = p.prev; + p.prev.next = p.next; + + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; + +} + +function Node( i, x, y ) { + + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + +} + +function signedArea( data, start, end, dim ) { + + let sum = 0; + for ( let i = start, j = end - dim; i < end; i += dim ) { + + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; + + } + + return sum; + +} + +class ShapeUtils { + + // calculate area of the contour polygon + + static area( contour ) { + + const n = contour.length; + let a = 0.0; + + for ( let 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; + + } + + static isClockWise( pts ) { + + return ShapeUtils.area( pts ) < 0; + + } + + static triangulateShape( contour, holes ) { + + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + + removeDupEndPts( contour ); + addContour( vertices, contour ); + + // + + let holeIndex = contour.length; + + holes.forEach( removeDupEndPts ); + + for ( let i = 0; i < holes.length; i ++ ) { + + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); + + } + + // + + const triangles = Earcut.triangulate( vertices, holeIndices ); + + // + + for ( let i = 0; i < triangles.length; i += 3 ) { + + faces.push( triangles.slice( i, i + 3 ) ); + + } + + return faces; + + } + +} + +function removeDupEndPts( points ) { + + const l = points.length; + + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + + points.pop(); + + } + +} + +function addContour( vertices, contour ) { + + for ( let i = 0; i < contour.length; i ++ ) { + + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); + + } + +} + +/** + * 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 + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ + +class ExtrudeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) { + + super(); + + this.type = 'ExtrudeGeometry'; + + this.parameters = { + shapes: shapes, + options: options + }; + + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + + const scope = this; + + const verticesArray = []; + const uvArray = []; + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + addShape( shape ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + this.computeVertexNormals(); + + // functions + + function addShape( shape ) { + + const placeholder = []; + + // options + + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + + const extrudePath = options.extrudePath; + + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + + // + + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + + if ( extrudePath ) { + + extrudePts = extrudePath.getSpacedPoints( steps ); + + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion + + // SETUP TNB variables + + // TODO1 - have a .isClosed in spline? + + splineTube = extrudePath.computeFrenetFrames( steps, false ); + + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } + + // Safeguards if bevels are not enabled + + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + + } + + // Variables initialization + + const shapePoints = shape.extractPoints( curveSegments ); + + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + + const reverse = ! ShapeUtils.isClockWise( vertices ); + + if ( reverse ) { + + vertices = vertices.reverse(); + + // Maybe we should also check if holes are in the opposite direction, just to be safe ... + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + if ( ShapeUtils.isClockWise( ahole ) ) { + + holes[ h ] = ahole.reverse(); + + } + + } + + } + + + const faces = ShapeUtils.triangulateShape( vertices, holes ); + + /* Vertices */ + + const contour = vertices; // vertices has all points but contour has only points of circumference + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + vertices = vertices.concat( ahole ); + + } + + + function scalePt2( pt, vec, size ) { + + if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' ); + + return vec.clone().multiplyScalar( size ).add( pt ); + + } + + const vlen = vertices.length, flen = faces.length; + + + // Find directions for point movement + + + 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. + + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html + + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; + + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + + // not collinear + + // length of vectors for normalizing + + const v_prev_len = Math.sqrt( v_prev_lensq ); + const 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 + + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + const 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 ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } + + } else { + + // handle special case of collinear edges + + let direction_eq = false; // assumes: opposite + + if ( v_prev_x > Number.EPSILON ) { + + if ( v_next_x > Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( v_prev_x < - Number.EPSILON ) { + + if ( v_next_x < - Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + + direction_eq = true; + + } + + } + + } + + 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 ); + + } 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 ); + + } + + } + + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + + } + + + const contourMovements = []; + + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) + + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + + } + + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + oneHoleMovements = []; + + for ( let 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; + + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + + } + + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); + + } + + + // Loop bevelSegments, 1 for the front, 1 for the back + + for ( let b = 0; b < bevelSegments; b ++ ) { + + //for ( b = bevelSegments; b > 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + + } + + } + + } + + const bs = bevelSize + bevelOffset; + + // Back facing vertices + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, 0 ); + + } else { + + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + // Add stepped vertices... + // Including front facing vertices + + for ( let s = 1; s <= steps; s ++ ) { + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth / steps * s ); + + } else { + + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + } + + + // Add bevel segments planes + + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } + + } + + /* Faces */ + + // Top and bottom faces + + buildLidFaces(); + + // Sides faces + + buildSideFaces(); + + + ///// Internal functions + + function buildLidFaces() { + + const start = verticesArray.length / 3; + + if ( bevelEnabled ) { + + let layer = 0; // steps + 1 + let offset = vlen * layer; + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + + } + + layer = steps + bevelSegments * 2; + offset = vlen * layer; + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + + } + + } else { + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + + } + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + + } + + } + + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; + + } + + + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + + + } + + function sidewalls( contour, layeroffset ) { + + let i = contour.length; + + while ( -- i >= 0 ) { + + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; + + //console.log('b', i,j, i-1, k,vertices.length); + + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); + + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } + + } + + } + + function v( x, y, z ) { + + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); + + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + + } + + function f4( a, b, c, d ) { + + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + const options = this.parameters.options; + + return toJSON$1( shapes, options, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + const extrudePath = data.options.extrudePath; + + if ( extrudePath !== undefined ) { + + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + + } + + return new ExtrudeGeometry( geometryShapes, data.options ); + + } + +} + +const WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + + }, + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { + + 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 ) + ]; + + } else { + + 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 ) + ]; + + } + + } + +}; + +function toJSON$1( shapes, options, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + data.options = Object.assign( {}, options ); + + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + + return data; + +} + +class IcosahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + + const 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 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'IcosahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new IcosahedronGeometry( data.radius, data.detail ); + + } + +} + +class OctahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; + + const 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 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'OctahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new OctahedronGeometry( data.radius, data.detail ); + + } + +} + +class RingGeometry extends BufferGeometry { + + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'RingGeometry'; + + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // some helper variables + + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= phiSegments; j ++ ) { + + for ( let i = 0; i <= thetaSegments; i ++ ) { + + // values are generate from the inside of the ring to the outside + + const segment = thetaStart + i / thetaSegments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uv + + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // increase the radius for next row of vertices + + radius += radiusStep; + + } + + // indices + + for ( let j = 0; j < phiSegments; j ++ ) { + + const thetaSegmentLevel = j * ( thetaSegments + 1 ); + + for ( let i = 0; i < thetaSegments; i ++ ) { + + const segment = i + thetaSegmentLevel; + + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); + + } + +} + +class ShapeGeometry extends BufferGeometry { + + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) { + + super(); + + this.type = 'ShapeGeometry'; + + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let groupStart = 0; + let groupCount = 0; + + // allow single and array values for "shapes" parameter + + if ( Array.isArray( shapes ) === false ) { + + addShape( shapes ); + + } else { + + for ( let i = 0; i < shapes.length; i ++ ) { + + addShape( shapes[ i ] ); + + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + + groupStart += groupCount; + groupCount = 0; + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + + // helper functions + + function addShape( shape ) { + + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); + + let shapeVertices = points.shape; + const shapeHoles = points.holes; + + // check direction of vertices + + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + + shapeVertices = shapeVertices.reverse(); + + } + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + + shapeHoles[ i ] = shapeHole.reverse(); + + } + + } + + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + + // join vertices of inner and outer paths to a single array + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); + + } + + // vertices, normals, uvs + + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + + const vertex = shapeVertices[ i ]; + + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs + + } + + // indices + + for ( let i = 0, l = faces.length; i < l; i ++ ) { + + const face = faces[ i ]; + + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; + + indices.push( a, b, c ); + groupCount += 3; + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + } + + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + return new ShapeGeometry( geometryShapes, data.curveSegments ); + + } + +} + +function toJSON( shapes, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + return data; + +} + +class SphereGeometry extends BufferGeometry { + + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + + super(); + + this.type = 'SphereGeometry'; + + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + + let index = 0; + const grid = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // generate vertices, normals and uvs + + for ( let iy = 0; iy <= heightSegments; iy ++ ) { + + const verticesRow = []; + + const v = iy / heightSegments; + + // special case for the poles + + let uOffset = 0; + + if ( iy == 0 && thetaStart == 0 ) { + + uOffset = 0.5 / widthSegments; + + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + + uOffset = - 0.5 / widthSegments; + + } + + for ( let ix = 0; ix <= widthSegments; ix ++ ) { + + const u = ix / widthSegments; + + // vertex + + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, 1 - v ); + + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); + + } + + // indices + + for ( let iy = 0; iy < heightSegments; iy ++ ) { + + for ( let ix = 0; ix < widthSegments; ix ++ ) { + + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); + + } + +} + +class TetrahedronGeometry extends PolyhedronGeometry { + + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; + + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'TetrahedronGeometry'; + + this.parameters = { + radius: radius, + detail: detail + }; + + } + + static fromJSON( data ) { + + return new TetrahedronGeometry( data.radius, data.detail ); + + } + +} + +class TorusGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) { + + super(); + + this.type = 'TorusGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; + + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= radialSegments; j ++ ) { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + + // 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= radialSegments; j ++ ) { + + for ( let i = 1; i <= tubularSegments; i ++ ) { + + // indices + + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + static fromJSON( data ) { + + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); + + } + +} + +class TorusKnotGeometry extends BufferGeometry { + + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + + super(); + + this.type = 'TorusKnotGeometry'; + + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; + + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + + const P1 = new Vector3(); + const P2 = new Vector3(); + + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); + + // generate vertices, normals and uvs + + for ( let i = 0; i <= tubularSegments; ++ i ) { + + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment + + const u = i / tubularSegments * p * Math.PI * 2; + + // 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 ); + + // calculate orthonormal basis + + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); + + // normalize B, N. T can be ignored, we don't use it + + B.normalize(); + N.normalize(); + + for ( let j = 0; j <= radialSegments; ++ j ) { + + // 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. + + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); + + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve + + 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 ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // 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.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + // indices + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // this function calculates the current position on the torus curve + + function calculatePositionOnCurve( u, p, q, radius, position ) { + + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const 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; + + } + + } + + static fromJSON( data ) { + + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); + + } + +} + +class TubeGeometry extends BufferGeometry { + + constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + + super(); + + this.type = 'TubeGeometry'; + + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; + + const frames = path.computeFrenetFrames( tubularSegments, closed ); + + // expose internals + + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + + // buffer + + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + + // create buffer data + + generateBufferData(); + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // functions + + function generateBufferData() { + + for ( let i = 0; i < tubularSegments; i ++ ) { + + generateSegment( i ); + + } + + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + + generateSegment( ( closed === false ) ? tubularSegments : 0 ); + + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries + + generateUVs(); + + // finally create faces + + generateIndices(); + + } + + function generateSegment( i ) { + + // we use getPointAt to sample evenly distributed points from the given path + + P = path.getPointAt( i / tubularSegments, P ); + + // retrieve corresponding normal and binormal + + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; + + // generate normals and vertices for the current segment + + for ( let j = 0; j <= radialSegments; j ++ ) { + + const v = j / radialSegments * Math.PI * 2; + + const sin = Math.sin( v ); + const cos = - Math.cos( v ); + + // normal + + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // vertex + + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + } + + } + + function generateIndices() { + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + } + + function generateUVs() { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + for ( let j = 0; j <= radialSegments; j ++ ) { + + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + + uvs.push( uv.x, uv.y ); + + } + + } + + } + + } + + toJSON() { + + const data = super.toJSON(); + + data.path = this.parameters.path.toJSON(); + + return data; + + } + + static fromJSON( data ) { + + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + + } + +} + +class WireframeGeometry extends BufferGeometry { + + constructor( geometry = null ) { + + super(); + + this.type = 'WireframeGeometry'; + + this.parameters = { + geometry: geometry + }; + + if ( geometry !== null ) { + + // buffer + + const vertices = []; + const edges = new Set(); + + // helper variables + + const start = new Vector3(); + const end = new Vector3(); + + if ( geometry.index !== null ) { + + // indexed BufferGeometry + + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + + if ( groups.length === 0 ) { + + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + + } + + // create a data structure that contains all edges without duplicates + + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + + const group = groups[ o ]; + + const groupStart = group.start; + const groupCount = group.count; + + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { + + for ( let j = 0; j < 3; j ++ ) { + + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + } else { + + // non-indexed BufferGeometry + + const position = geometry.attributes.position; + + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + + for ( let j = 0; j < 3; j ++ ) { + + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + +} + +function isUniqueEdge( start, end, edges ) { + + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge + + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { + + return false; + + } else { + + edges.add( hash1 ); + edges.add( hash2 ); + return true; + + } + +} + +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry +}); + +class ShadowMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isShadowMaterial = true; + + this.type = 'ShadowMaterial'; + + this.color = new Color( 0x000000 ); + this.transparent = true; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.fog = source.fog; + + return this; + + } + +} + +class RawShaderMaterial extends ShaderMaterial { + + constructor( parameters ) { + + super( parameters ); + + this.isRawShaderMaterial = true; + + this.type = 'RawShaderMaterial'; + + } + +} + +class MeshStandardMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshStandardMaterial = true; + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 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.0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + 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; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + + constructor( parameters ) { + + super(); + + this.isMeshPhysicalMaterial = true; + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.type = 'MeshPhysicalMaterial'; + + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; + + this.ior = 1.5; + + Object.defineProperty( this, 'reflectivity', { + get: function () { + + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); + + }, + set: function ( reflectivity ) { + + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); + + } + } ); + + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [ 100, 400 ]; + this.iridescenceThicknessMap = null; + + this.sheenColor = new Color( 0x000000 ); + this.sheenColorMap = null; + this.sheenRoughness = 1.0; + this.sheenRoughnessMap = null; + + this.transmissionMap = null; + + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color( 1, 1, 1 ); + + this.specularIntensity = 1.0; + this.specularIntensityMap = null; + this.specularColor = new Color( 1, 1, 1 ); + this.specularColorMap = null; + + this._sheen = 0.0; + this._clearcoat = 0; + this._iridescence = 0; + this._transmission = 0; + + this.setValues( parameters ); + + } + + get sheen() { + + return this._sheen; + + } + + set sheen( value ) { + + if ( this._sheen > 0 !== value > 0 ) { + + this.version ++; + + } + + this._sheen = value; + + } + + get clearcoat() { + + return this._clearcoat; + + } + + set clearcoat( value ) { + + if ( this._clearcoat > 0 !== value > 0 ) { + + this.version ++; + + } + + this._clearcoat = value; + + } + + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + + get transmission() { + + return this._transmission; + + } + + set transmission( value ) { + + if ( this._transmission > 0 !== value > 0 ) { + + this.version ++; + + } + + this._transmission = value; + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.ior = source.ior; + + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); + + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; + + return this; + + } + +} + +class MeshPhongMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshPhongMaterial = true; + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshToonMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshToonMaterial = true; + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + this.color = new Color( 0xffffff ); + + this.map = null; + this.gradientMap = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + this.gradientMap = source.gradientMap; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshNormalMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshNormalMaterial = true; + + this.type = 'MeshNormalMaterial'; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.flatShading = false; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + return this; + + } + +} + +class MeshLambertMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshLambertMaterial = true; + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + 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'; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class MeshMatcapMaterial extends Material { + + constructor( parameters ) { + + super(); + + this.isMeshMatcapMaterial = true; + + this.defines = { 'MATCAP': '' }; + + this.type = 'MeshMatcapMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.matcap = null; + + this.map = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.alphaMap = null; + + this.flatShading = false; + + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.defines = { 'MATCAP': '' }; + + this.color.copy( source.color ); + + this.matcap = source.matcap; + + this.map = source.map; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +class LineDashedMaterial extends LineBasicMaterial { + + constructor( parameters ) { + + super(); + + this.isLineDashedMaterial = true; + + this.type = 'LineDashedMaterial'; + + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + } + +} + +// same as Array.prototype.slice, but also works on typed arrays +function arraySlice( array, from, to ) { + + if ( isTypedArray( array ) ) { + + // in ios9 array.subarray(from, undefined) will return empty array + // but array.subarray(from) or array.subarray(from, len) is correct + return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + + } + + return array.slice( from, to ); + +} + +// converts an array to a specific type +function convertArray( array, type, forceClone ) { + + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; + + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + + return new type( array ); // create typed array + + } + + return Array.prototype.slice.call( array ); // create Array + +} + +function isTypedArray( object ) { + + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); + +} + +// returns an array by which times and values can be sorted +function getKeyframeOrder( times ) { + + function compareTime( i, j ) { + + return times[ i ] - times[ j ]; + + } + + const n = times.length; + const result = new Array( n ); + for ( let i = 0; i !== n; ++ i ) result[ i ] = i; + + result.sort( compareTime ); + + return result; + +} + +// uses the array previously returned by 'getKeyframeOrder' to sort data +function sortedArray( values, stride, order ) { + + const nValues = values.length; + const result = new values.constructor( nValues ); + + for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + + const srcOffset = order[ i ] * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + result[ dstOffset ++ ] = values[ srcOffset + j ]; + + } + + } + + return result; + +} + +// function for parsing AOS keyframe formats +function flattenJSON( jsonKeys, times, values, valuePropertyName ) { + + let i = 1, key = jsonKeys[ 0 ]; + + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + + key = jsonKeys[ i ++ ]; + + } + + if ( key === undefined ) return; // no data + + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data + + if ( Array.isArray( value ) ) { + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push.apply( values, value ); // push all elements + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else if ( value.toArray !== undefined ) { + + // ...assume THREE.Math-ish + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + value.toArray( values, values.length ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else { + + // otherwise push as-is + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push( value ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } + +} + +function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { + + const clip = sourceClip.clone(); + + clip.name = name; + + const tracks = []; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); + + const times = []; + const values = []; + + for ( let j = 0; j < track.times.length; ++ j ) { + + const frame = track.times[ j ] * fps; + + if ( frame < startFrame || frame >= endFrame ) continue; + + times.push( track.times[ j ] ); + + for ( let k = 0; k < valueSize; ++ k ) { + + values.push( track.values[ j * valueSize + k ] ); + + } + + } + + if ( times.length === 0 ) continue; + + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); + + } + + clip.tracks = tracks; + + // find minimum .times value across all tracks in the trimmed clip + + let minStartTime = Infinity; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + + minStartTime = clip.tracks[ i ].times[ 0 ]; + + } + + } + + // shift all tracks such that clip begins at t=0 + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + clip.tracks[ i ].shift( - 1 * minStartTime ); + + } + + clip.resetDuration(); + + return clip; + +} + +function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + + if ( fps <= 0 ) fps = 30; + + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { + + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; + + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { + + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; + + } ); + + if ( targetTrack === undefined ) continue; + + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + referenceOffset = referenceValueSize / 3; + + } + + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + targetOffset = targetValueSize / 3; + + } + + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { + + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex ); + + } else { + + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex ); + + } + + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { + + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); + + } + + // Subtract the reference value from all of the track values + + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { + + const valueStart = j * targetValueSize + targetOffset; + + if ( referenceTrackType === 'quaternion' ) { + + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + + } else { + + const valueEnd = targetValueSize - targetOffset * 2; + + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { + + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + + } + + } + + } + + } + + targetClip.blendMode = AdditiveAnimationBlendMode; + + return targetClip; + +} + +var AnimationUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arraySlice: arraySlice, + convertArray: convertArray, + flattenJSON: flattenJSON, + getKeyframeOrder: getKeyframeOrder, + isTypedArray: isTypedArray, + makeClipAdditive: makeClipAdditive, + sortedArray: sortedArray, + subclip: subclip +}); + +/** + * 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 + * + */ + +class Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + + this.settings = null; + this.DefaultSettings_ = {}; + + } + + evaluate( t ) { + + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; + + validate_interval: { + + seek: { + + let right; + + linear_scan: { + + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { + + for ( let giveUpAt = i1 + 2; ; ) { + + if ( t1 === undefined ) { + + if ( t < t0 ) break forward_scan; + + // after end + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t0 = t1; + t1 = pp[ ++ i1 ]; + + if ( t < t1 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // 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? + + const t1global = pp[ 1 ]; + + if ( t < t1global ) { + + i1 = 2; // + 1, using the scan for the details + t0 = t1global; + + } + + // linear reverse scan + + for ( let giveUpAt = i1 - 2; ; ) { + + if ( t0 === undefined ) { + + // before start + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t1 = t0; + t0 = pp[ -- i1 - 1 ]; + + if ( t >= t0 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; + + } + + // the interval is valid + + break validate_interval; + + } // linear scan + + // binary search + + while ( i1 < right ) { + + const mid = ( i1 + right ) >>> 1; + + if ( t < pp[ mid ] ) { + + right = mid; + + } else { + + i1 = mid + 1; + + } + + } + + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; + + // check boundary cases, again + + if ( t0 === undefined ) { + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( t1 === undefined ) { + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + } // seek + + this._cachedIndex = i1; + + this.intervalChanged_( i1, t0, t1 ); + + } // validate_interval + + return this.interpolate_( i1, t0, t, t1 ); + + } + + getSettings_() { + + return this.settings || this.DefaultSettings_; + + } + + copySampleValue_( index ) { + + // copies a sample value to the result buffer + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = values[ offset + i ]; + + } + + return result; + + } + + // Template methods for derived classes: + + interpolate_( /* i1, t0, t, t1 */ ) { + + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer + + } + + intervalChanged_( /* i1, t0, t1 */ ) { + + // empty + + } + +} + +/** + * 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. + */ + +class CubicInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; + + this.DefaultSettings_ = { + + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + + }; + + } + + intervalChanged_( i1, t0, t1 ) { + + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, + + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; + + if ( tPrev === undefined ) { + + switch ( this.getSettings_().endingStart ) { + + case ZeroSlopeEnding: + + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; + + } + + } + + if ( tNext === undefined ) { + + switch ( this.getSettings_().endingEnd ) { + + case ZeroSlopeEnding: + + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; + + } + + } + + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; + + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + + } + + interpolate_( i1, t0, t, t1 ) { + + const 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; + + // evaluate polynomials + + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + + // combine data linearly + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; + + } + + return result; + + } + +} + +class LinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + offset1 = i1 * stride, + offset0 = offset1 - stride, + + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; + + } + + return result; + + } + +} + +/** + * + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + */ + +class DiscreteInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1 /*, t0, t, t1 */ ) { + + return this.copySampleValue_( i1 - 1 ); + + } + +} + +class KeyframeTrack { + + constructor( name, times, values, interpolation ) { + + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + + this.name = name; + + this.times = convertArray( times, this.TimeBufferType ); + this.values = convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + } + + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): + + static toJSON( track ) { + + const trackType = track.constructor; + + let json; + + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { + + json = trackType.toJSON( track ); + + } else { + + // by default, we assume the data can be serialized as-is + json = { + + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) + + }; + + const interpolation = track.getInterpolation(); + + if ( interpolation !== track.DefaultInterpolation ) { + + json.interpolation = interpolation; + + } + + } + + json.type = track.ValueTypeName; // mandatory + + return json; + + } + + InterpolantFactoryMethodDiscrete( result ) { + + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodLinear( result ) { + + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + setInterpolation( interpolation ) { + + let factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + } + + if ( factoryMethod === undefined ) { + + const 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( 'THREE.KeyframeTrack:', message ); + return this; + + } + + this.createInterpolant = factoryMethod; + + return this; + + } + + getInterpolation() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + } + + } + + getValueSize() { + + return this.values.length / this.times.length; + + } + + // move all keyframes either forwards or backwards in time + shift( timeOffset ) { + + if ( timeOffset !== 0.0 ) { + + const times = this.times; + + for ( let 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( timeScale ) { + + if ( timeScale !== 1.0 ) { + + const times = this.times; + + for ( let 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( startTime, endTime ) { + + const times = this.times, + nKeys = times.length; + + let 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; + + } + + const stride = this.getValueSize(); + this.times = arraySlice( times, from, to ); + this.values = 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() { + + let valid = true; + + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; + + } + + const times = this.times, + values = this.values, + + nKeys = times.length; + + if ( nKeys === 0 ) { + + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; + + } + + let prevTime = null; + + for ( let i = 0; i !== nKeys; i ++ ) { + + const currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; + + } + + if ( prevTime !== null && prevTime > currTime ) { + + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( isTypedArray( values ) ) { + + for ( let i = 0, n = values.length; i !== n; ++ i ) { + + const value = values[ i ]; + + if ( isNaN( value ) ) { + + console.error( 'THREE.KeyframeTrack: 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() { + + // times or values may be shared with other tracks, so overwriting is unsafe + const times = arraySlice( this.times ), + values = arraySlice( this.values ), + stride = this.getValueSize(), + + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + + lastIndex = times.length - 1; + + let writeIndex = 1; + + for ( let i = 1; i < lastIndex; ++ i ) { + + let keep = false; + + const time = times[ i ]; + const timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + + if ( ! smoothInterpolation ) { + + // remove unnecessary keyframes same as their neighbors + + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( let j = 0; j !== stride; ++ j ) { + + const value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } else { + + keep = true; + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + const readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + } + + ++ writeIndex; + + } + + } + + // flush last keyframe (compaction looks ahead) + + if ( lastIndex > 0 ) { + + times[ writeIndex ] = times[ lastIndex ]; + + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + ++ writeIndex; + + } + + if ( writeIndex !== times.length ) { + + this.times = arraySlice( times, 0, writeIndex ); + this.values = arraySlice( values, 0, writeIndex * stride ); + + } else { + + this.times = times; + this.values = values; + + } + + return this; + + } + + clone() { + + const times = arraySlice( this.times, 0 ); + const values = arraySlice( this.values, 0 ); + + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); + + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; + + return track; + + } + +} + +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +/** + * A Track of Boolean keyframe values. + */ +class BooleanKeyframeTrack extends KeyframeTrack {} + +BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track of keyframe values that represent color. + */ +class ColorKeyframeTrack extends KeyframeTrack {} + +ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + +/** + * A Track of numeric keyframe values. + */ +class NumberKeyframeTrack extends KeyframeTrack {} + +NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + +/** + * Spherical linear unit quaternion interpolant. + */ + +class QuaternionLinearInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + alpha = ( t - t0 ) / ( t1 - t0 ); + + let offset = i1 * stride; + + for ( let end = offset + stride; offset !== end; offset += 4 ) { + + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); + + } + + return result; + + } + +} + +/** + * A Track of quaternion keyframe values. + */ +class QuaternionKeyframeTrack extends KeyframeTrack { + + InterpolantFactoryMethodLinear( result ) { + + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + +} + +QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; +// ValueBufferType is inherited +QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track that interpolates Strings + */ +class StringKeyframeTrack extends KeyframeTrack {} + +StringKeyframeTrack.prototype.ValueTypeName = 'string'; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A Track of vectored keyframe values. + */ +class VectorKeyframeTrack extends KeyframeTrack {} + +VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + +class AnimationClip { + + constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) { + + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + + this.uuid = generateUUID(); + + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { + + this.resetDuration(); + + } + + } + + + static parse( json ) { + + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); + + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + + } + + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; + + return clip; + + } + + static toJSON( clip ) { + + const tracks = [], + clipTracks = clip.tracks; + + const json = { + + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode + + }; + + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + + } + + return json; + + } + + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + + for ( let i = 0; i < numMorphTargets; i ++ ) { + + let times = []; + let values = []; + + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); + + values.push( 0, 1, 0 ); + + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); + + // 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 ] ); + + } + + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + + } + + return new this( name, - 1, tracks ); + + } + + static findByName( objectOrClipArray, name ) { + + let clipArray = objectOrClipArray; + + if ( ! Array.isArray( objectOrClipArray ) ) { + + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + + } + + for ( let i = 0; i < clipArray.length; i ++ ) { + + if ( clipArray[ i ].name === name ) { + + return clipArray[ i ]; + + } + + } + + return null; + + } + + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + + const animationToMorphTargets = {}; + + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; + + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); + + if ( parts && parts.length > 1 ) { + + const name = parts[ 1 ]; + + let animationMorphTargets = animationToMorphTargets[ name ]; + + if ( ! animationMorphTargets ) { + + animationToMorphTargets[ name ] = animationMorphTargets = []; + + } + + animationMorphTargets.push( morphTarget ); + + } + + } + + const clips = []; + + for ( const name in animationToMorphTargets ) { + + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + + } + + return clips; + + } + + // parse the animation.hierarchy format + static parseAnimation( animation, bones ) { + + if ( ! animation ) { + + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; + + } + + const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { + + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { + + const times = []; + const values = []; + + flattenJSON( animationKeys, times, values, propertyName ); + + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { + + destTracks.push( new trackType( trackName, times, values ) ); + + } + + } + + }; + + const tracks = []; + + const clipName = animation.name || 'default'; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + + // automatic length determination in AnimationClip. + let duration = animation.length || - 1; + + const hierarchyTracks = animation.hierarchy || []; + + for ( let h = 0; h < hierarchyTracks.length; h ++ ) { + + const animationKeys = hierarchyTracks[ h ].keys; + + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; + + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { + + // figure out all morph targets used in this track + const morphTargetNames = {}; + + let k; + + for ( k = 0; k < animationKeys.length; k ++ ) { + + if ( animationKeys[ k ].morphTargets ) { + + for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + + } + + } + + } + + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( const morphTargetName in morphTargetNames ) { + + const times = []; + const values = []; + + for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { + + const animationKey = animationKeys[ k ]; + + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + + } + + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + + } + + duration = morphTargetNames.length * fps; + + } else { + + // ...assume skeletal animation + + const boneName = '.bones[' + bones[ h ].name + ']'; + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); + + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); + + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); + + } + + } + + if ( tracks.length === 0 ) { + + return null; + + } + + const clip = new this( clipName, duration, tracks, blendMode ); + + return clip; + + } + + resetDuration() { + + const tracks = this.tracks; + let duration = 0; + + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { + + const track = this.tracks[ i ]; + + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + + } + + this.duration = duration; + + return this; + + } + + trim() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].trim( 0, this.duration ); + + } + + return this; + + } + + validate() { + + let valid = true; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + valid = valid && this.tracks[ i ].validate(); + + } + + return valid; + + } + + optimize() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].optimize(); + + } + + return this; + + } + + clone() { + + const tracks = []; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + tracks.push( this.tracks[ i ].clone() ); + + } + + return new this.constructor( this.name, this.duration, tracks, this.blendMode ); + + } + + toJSON() { + + return this.constructor.toJSON( this ); + + } + +} + +function getTrackTypeForValueTypeName( typeName ) { + + switch ( typeName.toLowerCase() ) { + + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': + + return NumberKeyframeTrack; + + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': + + return VectorKeyframeTrack; + + case 'color': + + return ColorKeyframeTrack; + + case 'quaternion': + + return QuaternionKeyframeTrack; + + case 'bool': + case 'boolean': + + return BooleanKeyframeTrack; + + case 'string': + + return StringKeyframeTrack; + + } + + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); + +} + +function parseKeyframeTrack( json ) { + + if ( json.type === undefined ) { + + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + + } + + const trackType = getTrackTypeForValueTypeName( json.type ); + + if ( json.times === undefined ) { + + const times = [], values = []; + + 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 { + + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); + + } + +} + +const Cache = { + + enabled: false, + + files: {}, + + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + get: function ( key ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + clear: function () { + + this.files = {}; + + } + +}; + +class LoadingManager { + + constructor( onLoad, onProgress, onError ) { + + const scope = this; + + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor + + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } + + } + + isLoading = true; + + }; + + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); + + } + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + + } + + }; + + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + + } + + }; + + this.resolveURL = function ( url ) { + + if ( urlModifier ) { + + return urlModifier( url ); + + } + + return url; + + }; + + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + + return this; + + }; + + this.addHandler = function ( regex, loader ) { + + handlers.push( regex, loader ); + + return this; + + }; + + this.removeHandler = function ( regex ) { + + const index = handlers.indexOf( regex ); + + if ( index !== - 1 ) { + + handlers.splice( index, 2 ); + + } + + return this; + + }; + + this.getHandler = function ( file ) { + + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; + + if ( regex.global ) regex.lastIndex = 0; // see #17920 + + if ( regex.test( file ) ) { + + return loader; + + } + + } + + return null; + + }; + + } + +} + +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +class Loader { + + constructor( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + this.crossOrigin = 'anonymous'; + this.withCredentials = false; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; + + } + + load( /* url, onLoad, onProgress, onError */ ) {} + + loadAsync( url, onProgress ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.load( url, resolve, onProgress, reject ); + + } ); + + } + + parse( /* data */ ) {} + + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + setWithCredentials( value ) { + + this.withCredentials = value; + return this; + + } + + setPath( path ) { + + this.path = path; + return this; + + } + + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + setRequestHeader( requestHeader ) { + + this.requestHeader = requestHeader; + return this; + + } + +} + +const loading = {}; + +class HttpError extends Error { + + constructor( message, response ) { + + super( message ); + this.response = response; + + } + +} + +class FileLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + this.manager.itemStart( url ); + + setTimeout( () => { + + if ( onLoad ) onLoad( cached ); + + this.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + // Check if request is duplicate + + if ( loading[ url ] !== undefined ) { + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + return; + + } + + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, + } ); + + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + // An abort controller could be added within a future PR + } ); + + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; + + // start the fetch + fetch( req ) + .then( response => { + + if ( response.status === 200 || response.status === 0 ) { + + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. + + if ( response.status === 0 ) { + + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); + + } + + // Workaround: Checking if response.body === undefined for Alipay browser #23548 + + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { + + return response; + + } + + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + + // Nginx needs X-File-Size check + // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content + const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { + + readData(); + + function readData() { + + reader.read().then( ( { done, value } ) => { + + if ( done ) { + + controller.close(); + + } else { + + loaded += value.byteLength; + + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); + + } + + controller.enqueue( value ); + readData(); + + } + + } ); + + } + + } + + } ); + + return new Response( stream ); + + } else { + + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); + + } + + } ) + .then( response => { + + switch ( responseType ) { + + case 'arraybuffer': + + return response.arrayBuffer(); + + case 'blob': + + return response.blob(); + + case 'document': + + return response.text() + .then( text => { + + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); + + } ); + + case 'json': + + return response.json(); + + default: + + if ( mimeType === undefined ) { + + return response.text(); + + } else { + + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); + + } + + } + + } ) + .then( data => { + + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, data ); + + const callbacks = loading[ url ]; + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); + + } + + } ) + .catch( err => { + + // Abort errors and other errors are handled the same + + const callbacks = loading[ url ]; + + if ( callbacks === undefined ) { + + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; + + } + + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); + + } + + this.manager.itemError( url ); + + } ) + .finally( () => { + + this.manager.itemEnd( url ); + + } ); + + this.manager.itemStart( url ); + + } + + setResponseType( value ) { + + this.responseType = value; + return this; + + } + + setMimeType( value ) { + + this.mimeType = value; + return this; + + } + +} + +class AnimationLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const animations = []; + + for ( let i = 0; i < json.length; i ++ ) { + + const clip = AnimationClip.parse( json[ i ] ); + + animations.push( clip ); + + } + + return animations; + + } + +} + +/** + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + +class CompressedTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const images = []; + + const texture = new CompressedTexture(); + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( url[ i ], function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + + loaded += 1; + + if ( loaded === 6 ) { + + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; + + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, onProgress, onError ); + + } + + if ( Array.isArray( url ) ) { + + for ( let i = 0, il = url.length; i < il; ++ i ) { + + loadTexture( i ); + + } + + } else { + + // compressed cubemap texture stored in a single DDS file + + loader.load( url, function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + if ( texDatas.isCubemap ) { + + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + + for ( let f = 0; f < faces; f ++ ) { + + images[ f ] = { mipmaps: [] }; + + for ( let 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; + + } + + } + + texture.image = images; + + } else { + + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + + } + + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + }, onProgress, onError ); + + } + + return texture; + + } + +} + +class ImageLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const image = createElementNS( 'img' ); + + function onImageLoad() { + + removeEventListeners(); + + Cache.add( url, this ); + + if ( onLoad ) onLoad( this ); + + scope.manager.itemEnd( url ); + + } + + function onImageError( event ) { + + removeEventListeners(); + + if ( onError ) onError( event ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } + + function removeEventListeners() { + + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); + + } + + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); + + if ( url.slice( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + + } + + scope.manager.itemStart( url ); + + image.src = url; + + return image; + + } + +} + +class CubeTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( urls, onLoad, onProgress, onError ) { + + const texture = new CubeTexture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( urls[ i ], function ( image ) { + + texture.images[ i ] = image; + + loaded ++; + + if ( loaded === 6 ) { + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, undefined, onError ); + + } + + for ( let i = 0; i < urls.length; ++ i ) { + + loadTexture( i ); + + } + + return texture; + + } + +} + +/** + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ + +class DataTextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const texture = new DataTexture(); + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { + + const texData = scope.parse( buffer ); + + if ( ! texData ) return; + + if ( texData.image !== undefined ) { + + texture.image = texData.image; + + } else if ( texData.data !== undefined ) { + + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + + } + + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + + if ( texData.encoding !== undefined ) { + + texture.encoding = texData.encoding; + + } + + if ( texData.flipY !== undefined ) { + + texture.flipY = texData.flipY; + + } + + if ( texData.format !== undefined ) { + + texture.format = texData.format; + + } + + if ( texData.type !== undefined ) { + + texture.type = texData.type; + + } + + if ( texData.mipmaps !== undefined ) { + + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... + + } + + if ( texData.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + if ( texData.generateMipmaps !== undefined ) { + + texture.generateMipmaps = texData.generateMipmaps; + + } + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture, texData ); + + }, onProgress, onError ); + + + return texture; + + } + +} + +class TextureLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const texture = new Texture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + loader.load( url, function ( image ) { + + texture.image = image; + texture.needsUpdate = true; + + if ( onLoad !== undefined ) { + + onLoad( texture ); + + } + + }, onProgress, onError ); + + return texture; + + } + +} + +class Light extends Object3D { + + constructor( color, intensity = 1 ) { + + super(); + + this.isLight = true; + + this.type = 'Light'; + + this.color = new Color( color ); + this.intensity = intensity; + + } + + dispose() { + + // Empty here in base class; some subclasses override. + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.color.copy( source.color ); + this.intensity = source.intensity; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + + 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; + + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +class HemisphereLight extends Light { + + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.groundColor = new Color( groundColor ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; + + } + +} + +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3(); +const _lookTarget$1 = /*@__PURE__*/ new Vector3(); + +class LightShadow { + + constructor( camera ) { + + this.camera = camera; + + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + + this.mapSize = new Vector2( 512, 512 ); + + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + + this.autoUpdate = true; + this.needsUpdate = false; + + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); + + this._viewportCount = 1; + + this._viewports = [ + + new Vector4( 0, 0, 1, 1 ) + + ]; + + } + + getViewportCount() { + + return this._viewportCount; + + } + + getFrustum() { + + return this._frustum; + + } + + updateMatrices( light ) { + + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + + _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld$1 ); + + _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget$1 ); + shadowCamera.updateMatrixWorld(); + + _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 ); + + 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( _projScreenMatrix$1 ); + + } + + getViewport( viewportIndex ) { + + return this._viewports[ viewportIndex ]; + + } + + getFrameExtents() { + + return this._frameExtents; + + } + + dispose() { + + if ( this.map ) { + + this.map.dispose(); + + } + + if ( this.mapPass ) { + + this.mapPass.dispose(); + + } + + } + + copy( source ) { + + this.camera = source.camera.clone(); + + this.bias = source.bias; + this.radius = source.radius; + + this.mapSize.copy( source.mapSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + toJSON() { + + const object = {}; + + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.normalBias !== 0 ) object.normalBias = this.normalBias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; + + return object; + + } + +} + +class SpotLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + + this.isSpotLightShadow = true; + + this.focus = 1; + + } + + updateMatrices( light ) { + + const camera = this.camera; + + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); + + } + + super.updateMatrices( light ); + + } + + copy( source ) { + + super.copy( source ); + + this.focus = source.focus; + + return this; + + } + +} + +class SpotLight extends Light { + + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) { + + super( color, intensity ); + + this.isSpotLight = true; + + this.type = 'SpotLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + + this.map = null; + + this.shadow = new SpotLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + + this.target = source.target.clone(); + + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +class PointLightShadow extends LightShadow { + + constructor() { + + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + + this.isPointLightShadow = true; + + this._frameExtents = new Vector2( 4, 2 ); + + this._viewportCount = 6; + + this._viewports = [ + // 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 + + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; + + this._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 ) + ]; + + this._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 ) + ]; + + } + + updateMatrices( light, viewportIndex = 0 ) { + + const camera = this.camera; + const shadowMatrix = this.matrix; + + const far = light.distance || camera.far; + + if ( far !== camera.far ) { + + camera.far = far; + camera.updateProjectionMatrix(); + + } + + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); + + _lookTarget.copy( camera.position ); + _lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); + + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( _projScreenMatrix ); + + } + +} + +class PointLight extends Light { + + constructor( color, intensity, distance = 0, decay = 2 ) { + + super( color, intensity ); + + this.isPointLight = true; + + this.type = 'PointLight'; + + this.distance = distance; + this.decay = decay; + + this.shadow = new PointLightShadow(); + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.decay = source.decay; + + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +class DirectionalLightShadow extends LightShadow { + + constructor() { + + super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); + + this.isDirectionalLightShadow = true; + + } + +} + +class DirectionalLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isDirectionalLight = true; + + this.type = 'DirectionalLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + this.target = new Object3D(); + + this.shadow = new DirectionalLightShadow(); + + } + + dispose() { + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + + return this; + + } + +} + +class AmbientLight extends Light { + + constructor( color, intensity ) { + + super( color, intensity ); + + this.isAmbientLight = true; + + this.type = 'AmbientLight'; + + } + +} + +class RectAreaLight extends Light { + + constructor( color, intensity, width = 10, height = 10 ) { + + super( color, intensity ); + + this.isRectAreaLight = true; + + this.type = 'RectAreaLight'; + + this.width = width; + this.height = height; + + } + + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); + + } + + copy( source ) { + + super.copy( source ); + + this.width = source.width; + this.height = source.height; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.width = this.width; + data.object.height = this.height; + + return data; + + } + +} + +/** + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ + +// 3-band SH defined by 9 coefficients + +class SphericalHarmonics3 { + + constructor() { + + this.isSphericalHarmonics3 = true; + + this.coefficients = []; + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients.push( new Vector3() ); + + } + + } + + set( coefficients ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].copy( coefficients[ i ] ); + + } + + return this; + + } + + zero() { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].set( 0, 0, 0 ); + + } + + return this; + + } + + // get the radiance in the direction of the normal + // target is a Vector3 + getAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; + + } + + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + + return target; + + } + + add( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].add( sh.coefficients[ i ] ); + + } + + return this; + + } + + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + + } + + return this; + + } + + scale( s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; + + } + + lerp( sh, alpha ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + + } + + return this; + + } + + equals( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { + + return false; + + } + + } + + return true; + + } + + copy( sh ) { + + return this.set( sh.coefficients ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + fromArray( array, offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + + } + + return this; + + } + + toArray( array = [], offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); + + } + + return array; + + } + + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt( normal, shBasis ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + // band 0 + shBasis[ 0 ] = 0.282095; + + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; + + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); + + } + +} + +class LightProbe extends Light { + + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + + super( undefined, intensity ); + + this.isLightProbe = true; + + this.sh = sh; + + } + + copy( source ) { + + super.copy( source ); + + this.sh.copy( source.sh ); + + return this; + + } + + fromJSON( json ) { + + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.sh = this.sh.toArray(); + + return data; + + } + +} + +class MaterialLoader extends Loader { + + constructor( manager ) { + + super( manager ); + this.textures = {}; + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const textures = this.textures; + + function getTexture( name ) { + + if ( textures[ name ] === undefined ) { + + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + + } + + return textures[ name ]; + + } + + const material = MaterialLoader.createMaterialFromType( json.type ); + + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined && material.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.sheen !== undefined ) material.sheen = json.sheen; + if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.iridescence !== undefined ) material.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) material.transmission = json.transmission; + if ( json.thickness !== undefined ) material.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor ); + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide; + 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.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; + + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; + + if ( json.rotation !== undefined ) material.rotation = json.rotation; + + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; + + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; + + if ( json.dithering !== undefined ) material.dithering = json.dithering; + + if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha; + + if ( json.visible !== undefined ) material.visible = json.visible; + + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; + + if ( json.userData !== undefined ) material.userData = json.userData; + + if ( json.vertexColors !== undefined ) { + + if ( typeof json.vertexColors === 'number' ) { + + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; + + } else { + + material.vertexColors = json.vertexColors; + + } + + } + + // Shader Material + + if ( json.uniforms !== undefined ) { + + for ( const name in json.uniforms ) { + + const uniform = json.uniforms[ name ]; + + material.uniforms[ name ] = {}; + + switch ( uniform.type ) { + + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; + + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; + + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; + + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; + + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; + + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; + + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; + + default: + material.uniforms[ name ].value = uniform.value; + + } + + } + + } + + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; + + if ( json.extensions !== undefined ) { + + for ( const key in json.extensions ) { + + material.extensions[ key ] = json.extensions[ key ]; + + } + + } + + // 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 = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); + + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); + + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { + + let normalScale = json.normalScale; + + if ( Array.isArray( normalScale ) === false ) { + + // Blender exporter used to export a scalar. See #7459 + + normalScale = [ normalScale, normalScale ]; + + } + + material.normalScale = new Vector2().fromArray( normalScale ); + + } + + if ( json.displacementMap !== undefined ) material.displacementMap = 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 = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap ); + if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap ); + + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; + + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; + + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + + if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap ); + if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap ); + + if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap ); + if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap ); + + if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap ); + if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap ); + + return material; + + } + + setTextures( value ) { + + this.textures = value; + return this; + + } + + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + + return new materialLib[ type ](); + + } + +} + +class LoaderUtils { + + static decodeText( array ) { + + if ( typeof TextDecoder !== 'undefined' ) { + + return new TextDecoder().decode( array ); + + } + + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. + + let s = ''; + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); + + } + + try { + + // merges multi-byte utf-8 characters. + + return decodeURIComponent( escape( s ) ); + + } catch ( e ) { // see #16358 + + return s; + + } + + } + + static extractUrlBase( url ) { + + const index = url.lastIndexOf( '/' ); + + if ( index === - 1 ) return './'; + + return url.slice( 0, index + 1 ); + + } + + static resolveURL( url, path ) { + + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; + + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); + + } + + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; + + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; + + } + +} + +class InstancedBufferGeometry extends BufferGeometry { + + constructor() { + + super(); + + this.isInstancedBufferGeometry = true; + + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; + + } + + copy( source ) { + + super.copy( source ); + + this.instanceCount = source.instanceCount; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.instanceCount = this.instanceCount; + + data.isInstancedBufferGeometry = true; + + return data; + + } + +} + +class BufferGeometryLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + parse( json ) { + + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + + function getInterleavedBuffer( json, uuid ) { + + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; + + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; + + interleavedBufferMap[ uuid ] = ib; + + return ib; + + } + + function getArrayBuffer( json, uuid ) { + + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; + + const ab = new Uint32Array( arrayBuffer ).buffer; + + arrayBufferMap[ uuid ] = ab; + + return ab; + + } + + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + + const index = json.data.index; + + if ( index !== undefined ) { + + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + + } + + const attributes = json.data.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); + + if ( attribute.updateRange !== undefined ) { + + bufferAttribute.updateRange.offset = attribute.updateRange.offset; + bufferAttribute.updateRange.count = attribute.updateRange.count; + + } + + geometry.setAttribute( key, bufferAttribute ); + + } + + const morphAttributes = json.data.morphAttributes; + + if ( morphAttributes ) { + + for ( const key in morphAttributes ) { + + const attributeArray = morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); + + } + + geometry.morphAttributes[ key ] = array; + + } + + } + + const morphTargetsRelative = json.data.morphTargetsRelative; + + if ( morphTargetsRelative ) { + + geometry.morphTargetsRelative = true; + + } + + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + + if ( groups !== undefined ) { + + for ( let i = 0, n = groups.length; i !== n; ++ i ) { + + const group = groups[ i ]; + + geometry.addGroup( group.start, group.count, group.materialIndex ); + + } + + } + + const boundingSphere = json.data.boundingSphere; + + if ( boundingSphere !== undefined ) { + + const center = new Vector3(); + + if ( boundingSphere.center !== undefined ) { + + center.fromArray( boundingSphere.center ); + + } + + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + + } + + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; + + return geometry; + + } + +} + +class ObjectLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + let json = null; + + try { + + json = JSON.parse( text ); + + } catch ( error ) { + + if ( onError !== undefined ) onError( error ); + + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + + return; + + } + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) ); + + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; + + } + + scope.parse( json, onLoad ); + + }, onProgress, onError ); + + } + + async loadAsync( url, onProgress ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + + const text = await loader.loadAsync( url, onProgress ); + + const json = JSON.parse( text ); + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); + + } + + return await scope.parseAsync( json ); + + } + + parse( json, onLoad ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = this.parseImages( json.images, function () { + + if ( onLoad !== undefined ) onLoad( object ); + + } ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + // + + if ( onLoad !== undefined ) { + + let hasImages = false; + + for ( const uuid in images ) { + + if ( images[ uuid ].data instanceof HTMLImageElement ) { + + hasImages = true; + break; + + } + + } + + if ( hasImages === false ) onLoad( object ); + + } + + return object; + + } + + async parseAsync( json ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = await this.parseImagesAsync( json.images ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + + return object; + + } + + parseShapes( json ) { + + const shapes = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const shape = new Shape().fromJSON( json[ i ] ); + + shapes[ shape.uuid ] = shape; + + } + + } + + return shapes; + + } + + parseSkeletons( json, object ) { + + const skeletons = {}; + const bones = {}; + + // generate bone lookup table + + object.traverse( function ( child ) { + + if ( child.isBone ) bones[ child.uuid ] = child; + + } ); + + // create skeletons + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + + skeletons[ skeleton.uuid ] = skeleton; + + } + + } + + return skeletons; + + } + + parseGeometries( json, shapes ) { + + const geometries = {}; + + if ( json !== undefined ) { + + const bufferGeometryLoader = new BufferGeometryLoader(); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + let geometry; + const data = json[ i ]; + + switch ( data.type ) { + + case 'BufferGeometry': + case 'InstancedBufferGeometry': + + geometry = bufferGeometryLoader.parse( data ); + break; + + default: + + if ( data.type in Geometries ) { + + geometry = Geometries[ data.type ].fromJSON( data, shapes ); + + } else { + + console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` ); + + } + + } + + geometry.uuid = data.uuid; + + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; + + geometries[ data.uuid ] = geometry; + + } + + } + + return geometries; + + } + + parseMaterials( json, textures ) { + + const cache = {}; // MultiMaterial + const materials = {}; + + if ( json !== undefined ) { + + const loader = new MaterialLoader(); + loader.setTextures( textures ); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( cache[ data.uuid ] === undefined ) { + + cache[ data.uuid ] = loader.parse( data ); + + } + + materials[ data.uuid ] = cache[ data.uuid ]; + + } + + } + + return materials; + + } + + parseAnimations( json ) { + + const animations = {}; + + if ( json !== undefined ) { + + for ( let i = 0; i < json.length; i ++ ) { + + const data = json[ i ]; + + const clip = AnimationClip.parse( data ); + + animations[ clip.uuid ] = clip; + + } + + } + + return animations; + + } + + parseImages( json, onLoad ) { + + const scope = this; + const images = {}; + + let loader; + + function loadImage( url ) { + + scope.manager.itemStart( url ); + + return loader.load( url, function () { + + scope.manager.itemEnd( url ); + + }, undefined, function () { + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + } + + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return loadImage( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + const manager = new LoadingManager( onLoad ); + + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + + } + + } + + } + + return images; + + } + + async parseImagesAsync( json ) { + + const scope = this; + const images = {}; + + let loader; + + async function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return await loader.loadAsync( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = await deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new Source( imageArray ); + + } else { + + // load single image + + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new Source( deserializedImage ); + + } + + } + + } + + return images; + + } + + parseTextures( json, images ) { + + function parseConstant( value, type ) { + + if ( typeof value === 'number' ) return value; + + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; + + } + + const textures = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( data.image === undefined ) { + + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + + } + + if ( images[ data.image ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + + } + + const source = images[ data.image ]; + const image = source.data; + + let texture; + + if ( Array.isArray( image ) ) { + + texture = new CubeTexture(); + + if ( image.length === 6 ) texture.needsUpdate = true; + + } else { + + if ( image && image.data ) { + + texture = new DataTexture(); + + } else { + + texture = new Texture(); + + } + + if ( image ) texture.needsUpdate = true; // textures can have undefined image data + + } + + texture.source = source; + + texture.uuid = data.uuid; + + if ( data.name !== undefined ) texture.name = data.name; + + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; + + if ( data.wrap !== undefined ) { + + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + + } + + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; + + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + + if ( data.flipY !== undefined ) texture.flipY = data.flipY; + + if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps; + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + + if ( data.userData !== undefined ) texture.userData = data.userData; + + textures[ data.uuid ] = texture; + + } + + } + + return textures; + + } + + parseObject( data, geometries, materials, textures, animations ) { + + let object; + + function getGeometry( name ) { + + if ( geometries[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + + } + + return geometries[ name ]; + + } + + function getMaterial( name ) { + + if ( name === undefined ) return undefined; + + if ( Array.isArray( name ) ) { + + const array = []; + + for ( let i = 0, l = name.length; i < l; i ++ ) { + + const uuid = name[ i ]; + + if ( materials[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + + } + + array.push( materials[ uuid ] ); + + } + + return array; + + } + + if ( materials[ name ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined material', name ); + + } + + return materials[ name ]; + + } + + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { + + console.warn( 'THREE.ObjectLoader: Undefined texture', uuid ); + + } + + return textures[ uuid ]; + + } + + let geometry, material; + + switch ( data.type ) { + + case 'Scene': + + object = new Scene(); + + if ( data.background !== undefined ) { + + if ( Number.isInteger( data.background ) ) { + + object.background = new Color( data.background ); + + } else { + + object.background = getTexture( data.background ); + + } + + } + + if ( data.environment !== undefined ) { + + object.environment = getTexture( data.environment ); + + } + + if ( data.fog !== undefined ) { + + if ( data.fog.type === 'Fog' ) { + + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + + } else if ( data.fog.type === 'FogExp2' ) { + + object.fog = new FogExp2( data.fog.color, data.fog.density ); + + } + + } + + if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; + if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + + break; + + case 'PerspectiveCamera': + + 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 ); + + break; + + case 'OrthographicCamera': + + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + + break; + + case 'AmbientLight': + + object = new AmbientLight( data.color, data.intensity ); + + break; + + case 'DirectionalLight': + + object = new DirectionalLight( data.color, data.intensity ); + + break; + + case 'PointLight': + + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + + break; + + case 'RectAreaLight': + + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + + break; + + case 'SpotLight': + + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + + break; + + case 'HemisphereLight': + + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + + break; + + case 'LightProbe': + + object = new LightProbe().fromJSON( data ); + + break; + + case 'SkinnedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new SkinnedMesh( geometry, material ); + + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + + break; + + case 'Mesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new Mesh( geometry, material ); + + break; + + case 'InstancedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); + + break; + + case 'LOD': + + object = new LOD(); + + break; + + case 'Line': + + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineLoop': + + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineSegments': + + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'PointCloud': + case 'Points': + + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'Sprite': + + object = new Sprite( getMaterial( data.material ) ); + + break; + + case 'Group': + + object = new Group(); + + break; + + case 'Bone': + + object = new Bone(); + + break; + + default: + + object = new Object3D(); + + } + + object.uuid = data.uuid; + + if ( data.name !== undefined ) object.name = data.name; + + if ( data.matrix !== undefined ) { + + object.matrix.fromArray( data.matrix ); + + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.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.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + 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; + + if ( data.shadow ) { + + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + + } + + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; + + if ( data.children !== undefined ) { + + const children = data.children; + + for ( let i = 0; i < children.length; i ++ ) { + + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); + + } + + } + + if ( data.animations !== undefined ) { + + const objectAnimations = data.animations; + + for ( let i = 0; i < objectAnimations.length; i ++ ) { + + const uuid = objectAnimations[ i ]; + + object.animations.push( animations[ uuid ] ); + + } + + } + + if ( data.type === 'LOD' ) { + + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + + const levels = data.levels; + + for ( let l = 0; l < levels.length; l ++ ) { + + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); + + if ( child !== undefined ) { + + object.addLevel( child, level.distance, level.hysteresis ); + + } + + } + + } + + return object; + + } + + bindSkeletons( object, skeletons ) { + + if ( Object.keys( skeletons ).length === 0 ) return; + + object.traverse( function ( child ) { + + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + + const skeleton = skeletons[ child.skeleton ]; + + if ( skeleton === undefined ) { + + console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton ); + + } else { + + child.bind( skeleton, child.bindMatrix ); + + } + + } + + } ); + + } + +} + +const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping +}; + +const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; + +const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; + +class ImageBitmapLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + this.isImageBitmapLoader = true; + + if ( typeof createImageBitmap === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + + } + + if ( typeof fetch === 'undefined' ) { + + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + + } + + this.options = { premultiplyAlpha: 'none' }; + + } + + setOptions( options ) { + + this.options = options; + + return this; + + } + + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; + + fetch( url, fetchOptions ).then( function ( res ) { + + return res.blob(); + + } ).then( function ( blob ) { + + return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) ); + + } ).then( function ( imageBitmap ) { + + Cache.add( url, imageBitmap ); + + if ( onLoad ) onLoad( imageBitmap ); + + scope.manager.itemEnd( url ); + + } ).catch( function ( e ) { + + if ( onError ) onError( e ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + scope.manager.itemStart( url ); + + } + +} + +let _context; + +class AudioContext { + + static getContext() { + + if ( _context === undefined ) { + + _context = new ( window.AudioContext || window.webkitAudioContext )(); + + } + + return _context; + + } + + static setContext( value ) { + + _context = value; + + } + +} + +class AudioLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { + + try { + + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); + + const context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { + + onLoad( audioBuffer ); + + } ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + +} + +class HemisphereLightProbe extends LightProbe { + + constructor( skyColor, groundColor, intensity = 1 ) { + + super( undefined, intensity ); + + this.isHemisphereLightProbe = true; + + const color1 = new Color().set( skyColor ); + const color2 = new Color().set( groundColor ); + + const sky = new Vector3( color1.r, color1.g, color1.b ); + const ground = new Vector3( color2.r, color2.g, color2.b ); + + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + const c0 = Math.sqrt( Math.PI ); + const c1 = c0 * Math.sqrt( 0.75 ); + + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + + } + +} + +class AmbientLightProbe extends LightProbe { + + constructor( color, intensity = 1 ) { + + super( undefined, intensity ); + + this.isAmbientLightProbe = true; + + const color1 = new Color().set( color ); + + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + + } + +} + +const _eyeRight = /*@__PURE__*/ new Matrix4(); +const _eyeLeft = /*@__PURE__*/ new Matrix4(); +const _projectionMatrix = /*@__PURE__*/ new Matrix4(); + +class StereoCamera { + + constructor() { + + this.type = 'StereoCamera'; + + this.aspect = 1; + + this.eyeSep = 0.064; + + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; + + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; + + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + + } + + update( camera ) { + + const cache = this._cache; + + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + + if ( needsUpdate ) { + + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ + + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; + + // translate xOffset + + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; + + // for left eye + + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraL.projectionMatrix.copy( _projectionMatrix ); + + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + + } + +} + +class Clock { + + constructor( autoStart = true ) { + + this.autoStart = autoStart; + + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + + this.running = false; + + } + + start() { + + this.startTime = now(); + + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + + } + + stop() { + + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + + } + + getElapsedTime() { + + this.getDelta(); + return this.elapsedTime; + + } + + getDelta() { + + let diff = 0; + + if ( this.autoStart && ! this.running ) { + + this.start(); + return 0; + + } + + if ( this.running ) { + + const newTime = now(); + + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; + + this.elapsedTime += diff; + + } + + return diff; + + } + +} + +function now() { + + return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + +} + +const _position$1 = /*@__PURE__*/ new Vector3(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); +const _scale$1 = /*@__PURE__*/ new Vector3(); +const _orientation$1 = /*@__PURE__*/ new Vector3(); + +class AudioListener extends Object3D { + + constructor() { + + super(); + + this.type = 'AudioListener'; + + this.context = AudioContext.getContext(); + + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); + + this.filter = null; + + this.timeDelta = 0; + + // private + + this._clock = new Clock(); + + } + + getInput() { + + return this.gain; + + } + + removeFilter() { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; + + } + + return this; + + } + + getFilter() { + + return this.filter; + + } + + setFilter( value ) { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + + } else { + + this.gain.disconnect( this.context.destination ); + + } + + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); + + return this; + + } + + getMasterVolume() { + + return this.gain.gain.value; + + } + + setMasterVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + const listener = this.context.listener; + const up = this.up; + + this.timeDelta = this._clock.getDelta(); + + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); + + _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 ); + + if ( listener.positionX ) { + + // code path for Chrome (see #14393) + + const endTime = this.context.currentTime + this.timeDelta; + + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); + + } else { + + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z ); + + } + + } + +} + +class Audio extends Object3D { + + constructor( listener ) { + + super(); + + this.type = 'Audio'; + + this.listener = listener; + this.context = listener.context; + + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); + + this.autoplay = false; + + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = 'empty'; + + this._startedAt = 0; + this._progress = 0; + this._connected = false; + + this.filters = []; + + } + + getOutput() { + + return this.gain; + + } + + setNodeSource( audioNode ) { + + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; + + } + + setMediaElementSource( mediaElement ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); + + return this; + + } + + setMediaStreamSource( mediaStream ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); + + return this; + + } + + setBuffer( audioBuffer ) { + + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; + + } + + play( delay = 0 ) { + + if ( this.isPlaying === true ) { + + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; + + } + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._startedAt = this.context.currentTime + delay; + + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); + + this.isPlaying = true; + + this.source = source; + + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); + + return this.connect(); + + } + + pause() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + if ( this.isPlaying === true ) { + + // update current progress + + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + + if ( this.loop === true ) { + + // ensure _progress does not exceed duration with looped audios + + this._progress = this._progress % ( this.duration || this.buffer.duration ); + + } + + this.source.stop(); + this.source.onended = null; + + this.isPlaying = false; + + } + + return this; + + } + + stop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this._progress = 0; + + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + + return this; + + } + + connect() { + + if ( this.filters.length > 0 ) { + + this.source.connect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].connect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + + } else { + + this.source.connect( this.getOutput() ); + + } + + this._connected = true; + + return this; + + } + + disconnect() { + + if ( this.filters.length > 0 ) { + + this.source.disconnect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + + } else { + + this.source.disconnect( this.getOutput() ); + + } + + this._connected = false; + + return this; + + } + + getFilters() { + + return this.filters; + + } + + setFilters( value ) { + + if ( ! value ) value = []; + + if ( this._connected === true ) { + + this.disconnect(); + this.filters = value.slice(); + this.connect(); + + } else { + + this.filters = value.slice(); + + } + + return this; + + } + + setDetune( value ) { + + this.detune = value; + + if ( this.source.detune === undefined ) return; // only set detune when available + + if ( this.isPlaying === true ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getDetune() { + + return this.detune; + + } + + getFilter() { + + return this.getFilters()[ 0 ]; + + } + + setFilter( filter ) { + + return this.setFilters( filter ? [ filter ] : [] ); + + } + + setPlaybackRate( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.playbackRate = value; + + if ( this.isPlaying === true ) { + + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + getPlaybackRate() { + + return this.playbackRate; + + } + + onEnded() { + + this.isPlaying = false; + + } + + getLoop() { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; + + } + + return this.loop; + + } + + setLoop( value ) { + + if ( this.hasPlaybackControl === false ) { + + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; + + } + + this.loop = value; + + if ( this.isPlaying === true ) { + + this.source.loop = this.loop; + + } + + return this; + + } + + setLoopStart( value ) { + + this.loopStart = value; + + return this; + + } + + setLoopEnd( value ) { + + this.loopEnd = value; + + return this; + + } + + getVolume() { + + return this.gain.gain.value; + + } + + setVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + +} + +const _position = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); +const _scale = /*@__PURE__*/ new Vector3(); +const _orientation = /*@__PURE__*/ new Vector3(); + +class PositionalAudio extends Audio { + + constructor( listener ) { + + super( listener ); + + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); + + } + + disconnect() { + + super.disconnect(); + + this.panner.disconnect( this.gain ); + + } + + getOutput() { + + return this.panner; + + } + + getRefDistance() { + + return this.panner.refDistance; + + } + + setRefDistance( value ) { + + this.panner.refDistance = value; + + return this; + + } + + getRolloffFactor() { + + return this.panner.rolloffFactor; + + } + + setRolloffFactor( value ) { + + this.panner.rolloffFactor = value; + + return this; + + } + + getDistanceModel() { + + return this.panner.distanceModel; + + } + + setDistanceModel( value ) { + + this.panner.distanceModel = value; + + return this; + + } + + getMaxDistance() { + + return this.panner.maxDistance; + + } + + setMaxDistance( value ) { + + this.panner.maxDistance = value; + + return this; + + } + + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + + this.matrixWorld.decompose( _position, _quaternion, _scale ); + + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); + + const panner = this.panner; + + if ( panner.positionX ) { + + // code path for Chrome and Firefox (see #14393) + + const endTime = this.context.currentTime + this.listener.timeDelta; + + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); + + } else { + + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); + + } + + } + +} + +class AudioAnalyser { + + constructor( audio, fftSize = 2048 ) { + + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); + + } + + + getFrequencyData() { + + this.analyser.getByteFrequencyData( this.data ); + + return this.data; + + } + + getAverageFrequency() { + + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; + + } + + return value / data.length; + + } + +} + +class PropertyMixer { + + constructor( binding, typeName, valueSize ) { + + this.binding = binding; + this.valueSize = valueSize; + + let mixFunction, + mixFunctionAdditive, + setIdentity; + + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // 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 + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results + + switch ( typeName ) { + + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; + + case 'string': + case 'bool': + mixFunction = this._select; + + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; + + setIdentity = this._setAdditiveIdentityOther; + + this.buffer = new Array( valueSize * 5 ); + break; + + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + + this.buffer = new Float64Array( valueSize * 5 ); + + } + + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + this.useCount = 0; + this.referenceCount = 0; + + } + + // accumulate data in the 'incoming' region into 'accu' + accumulate( 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 + + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; + + let currentWeight = this.cumulativeWeight; + + if ( currentWeight === 0 ) { + + // accuN := incoming * weight + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ offset + i ] = buffer[ i ]; + + } + + currentWeight = weight; + + } else { + + // accuN := accuN + incoming * weight + + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); + + } + + this.cumulativeWeight = currentWeight; + + } + + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive( weight ) { + + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; + + if ( this.cumulativeWeightAdditive === 0 ) { + + // add = identity + + this._setIdentity(); + + } + + // add := add + incoming * weight + + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; + + } + + // apply the state of 'accu' to the binding when accus differ + apply( accuIndex ) { + + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, + + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, + + binding = this.binding; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + if ( weight < 1 ) { + + // accuN := accuN + original * ( 1 - cumulativeWeight ) + + const originalValueOffset = stride * this._origIndex; + + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); + + } + + if ( weightAdditive > 0 ) { + + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + + } + + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + + if ( buffer[ i ] !== buffer[ i + stride ] ) { + + // value has changed -> update scene graph + + binding.setValue( buffer, offset ); + break; + + } + + } + + } + + // remember the state of the bound property and copy it to both accus + saveOriginalState() { + + const binding = this.binding; + + const buffer = this.buffer, + stride = this.valueSize, + + originalValueOffset = stride * this._origIndex; + + binding.getValue( buffer, originalValueOffset ); + + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + + } + + // Add to identity for additive + this._setIdentity(); + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + } + + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { + + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); + + } + + _setAdditiveIdentityNumeric() { + + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + + for ( let i = startIndex; i < endIndex; i ++ ) { + + this.buffer[ i ] = 0; + + } + + } + + _setAdditiveIdentityQuaternion() { + + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + + } + + _setAdditiveIdentityOther() { + + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + + for ( let i = 0; i < this.valueSize; i ++ ) { + + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + + } + + } + + + // mix functions + + _select( buffer, dstOffset, srcOffset, t, stride ) { + + if ( t >= 0.5 ) { + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } + + } + + } + + _slerp( buffer, dstOffset, srcOffset, t ) { + + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + + } + + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + const workOffset = this._workIndex * stride; + + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + + } + + _lerp( buffer, dstOffset, srcOffset, t, stride ) { + + const s = 1 - t; + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + + } + + } + + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + + } + + } + +} + +// Characters [].:/ are reserved for track binding syntax. +const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + +const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); + +const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; + +class Composite { + + constructor( targetGroup, path, optionalParsedPath ) { + + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); + + } + + getValue( array, offset ) { + + this.bind(); // bind all binding + + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); + + } + + setValue( array, offset ) { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].setValue( array, offset ); + + } + + } + + bind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].bind(); + + } + + } + + unbind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].unbind(); + + } + + } + +} + +// 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. +class PropertyBinding { + + constructor( rootNode, path, parsedPath ) { + + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + + this.rootNode = rootNode; + + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + + } + + + static create( root, path, parsedPath ) { + + if ( ! ( root && root.isAnimationObjectGroup ) ) { + + return new PropertyBinding( root, path, parsedPath ); + + } else { + + return new PropertyBinding.Composite( root, path, parsedPath ); + + } + + } + + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName( name ) { + + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + + } + + static parseTrackName( trackName ) { + + const matches = _trackRe.exec( trackName ); + + if ( matches === null ) { + + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + + } + + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; + + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + + if ( lastDot !== undefined && lastDot !== - 1 ) { + + const objectName = results.nodeName.substring( lastDot + 1 ); + + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; + + } + + } + + if ( results.propertyName === null || results.propertyName.length === 0 ) { + + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + + } + + return results; + + } + + static findNode( root, nodeName ) { + + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + + return root; + + } + + // search into skeleton bones. + if ( root.skeleton ) { + + const bone = root.skeleton.getBoneByName( nodeName ); + + if ( bone !== undefined ) { + + return bone; + + } + + } + + // search into node subtree. + if ( root.children ) { + + const searchNodeSubtree = function ( children ) { + + for ( let i = 0; i < children.length; i ++ ) { + + const childNode = children[ i ]; + + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + + return childNode; + + } + + const result = searchNodeSubtree( childNode.children ); + + if ( result ) return result; + + } + + return null; + + }; + + const subTreeNode = searchNodeSubtree( root.children ); + + if ( subTreeNode ) { + + return subTreeNode; + + } + + } + + return null; + + } + + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} + + // Getters + + _getValue_direct( buffer, offset ) { + + buffer[ offset ] = this.targetObject[ this.propertyName ]; + + } + + _getValue_array( buffer, offset ) { + + const source = this.resolvedProperty; + + for ( let i = 0, n = source.length; i !== n; ++ i ) { + + buffer[ offset ++ ] = source[ i ]; + + } + + } + + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + + } + + _getValue_toArray( buffer, offset ) { + + this.resolvedProperty.toArray( buffer, offset ); + + } + + // Direct + + _setValue_direct( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + + } + + _setValue_direct_setNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // EntireArray + + _setValue_array( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + } + + _setValue_array_setNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.needsUpdate = true; + + } + + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // ArrayElement + + _setValue_arrayElement( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + + } + + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // HasToFromArray + + _setValue_fromArray( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + + } + + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; + + } + + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + _getValue_unbound( targetArray, offset ) { + + this.bind(); + this.getValue( targetArray, offset ); + + } + + _setValue_unbound( sourceArray, offset ) { + + this.bind(); + this.setValue( sourceArray, offset ); + + } + + // create getter / setter pair for a property in the scene graph + bind() { + + let targetObject = this.node; + const parsedPath = this.parsedPath; + + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + + if ( ! targetObject ) { + + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + + this.node = targetObject; + + } + + // 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 ) { + + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; + + } + + if ( objectName ) { + + let objectIndex = parsedPath.objectIndex; + + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { + + case 'materials': + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.materials ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; + + } + + targetObject = targetObject.material.materials; + + break; + + case 'bones': + + if ( ! targetObject.skeleton ) { + + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; + + } + + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. + + targetObject = targetObject.skeleton.bones; + + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { + + if ( targetObject[ i ].name === objectIndex ) { + + objectIndex = i; + break; + + } + + } + + break; + + case 'map': + + if ( 'map' in targetObject ) { + + targetObject = targetObject.map; + break; + + } + + if ( ! targetObject.material ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.map ) { + + console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; + + } + + targetObject = targetObject.material.map; + break; + + default: + + if ( targetObject[ objectName ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; + + } + + targetObject = targetObject[ objectName ]; + + } + + + if ( objectIndex !== undefined ) { + + if ( targetObject[ objectIndex ] === undefined ) { + + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; + + } + + targetObject = targetObject[ objectIndex ]; + + } + + } + + // resolve property + const nodeProperty = targetObject[ propertyName ]; + + if ( nodeProperty === undefined ) { + + const nodeName = parsedPath.nodeName; + + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; + + } + + // determine versioning scheme + let versioning = this.Versioning.None; + + this.targetObject = targetObject; + + if ( targetObject.needsUpdate !== undefined ) { // material + + versioning = this.Versioning.NeedsUpdate; + + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + + versioning = this.Versioning.MatrixWorldNeedsUpdate; + + } + + // determine how the property gets bound + let 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. + + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; + + } + + if ( ! targetObject.geometry.morphAttributes ) { + + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + + } + + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + + } + + } + + bindingType = this.BindingType.ArrayElement; + + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + + // must use copy for Object3D.Euler/Quaternion + + bindingType = this.BindingType.HasFromToArray; + + this.resolvedProperty = nodeProperty; + + } else if ( Array.isArray( nodeProperty ) ) { + + bindingType = this.BindingType.EntireArray; + + this.resolvedProperty = nodeProperty; + + } else { + + this.propertyName = propertyName; + + } + + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + + } + + unbind() { + + this.node = null; + + // 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; + + } + +} + +PropertyBinding.Composite = Composite; + +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; + +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; + +PropertyBinding.prototype.GetterByBindingType = [ + + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, + +]; + +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, + + ], [ + + // EntireArray + + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, + + ], [ + + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, + + ], [ + + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, + + ] + +]; + +/** + * + * 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. + */ + +class AnimationObjectGroup { + + constructor() { + + this.isAnimationObjectGroup = true; + + this.uuid = generateUUID(); + + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); + + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite + + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + indices[ arguments[ i ].uuid ] = 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 + + const scope = this; + + this.stats = { + + objects: { + get total() { + + return scope._objects.length; + + }, + get inUse() { + + return this.total - scope.nCachedObjects_; + + } + }, + get bindingsPerObject() { + + return scope._bindings.length; + + } + + }; + + } + + add() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; + + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; + + if ( index === undefined ) { + + // unknown object -> add it to the ACTIVE region + + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + + } + + } else if ( index < nCachedObjects ) { + + knownObject = objects[ index ]; + + // move existing object to the ACTIVE region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; + + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; + + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; + + let binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = lastCached; + + if ( binding === undefined ) { + + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist + + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + + } + + bindingsForPath[ firstActiveIndex ] = binding; + + } + + } else if ( objects[ index ] !== knownObject ) { + + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); + + } // else the object is already where we want it to be + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + remove() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined && index >= nCachedObjects ) { + + // move existing object into the CACHED region + + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; + + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; + + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; + + } + + } + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // remove & forget + uncache() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined ) { + + delete indicesByUUID[ uuid ]; + + if ( index < nCachedObjects ) { + + // object is cached, shrink the CACHED region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + // 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(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; + + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); + + } + + } else { + + // object is active, just swap with the last and pop + + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + if ( lastIndex > 0 ) { + + indicesByUUID[ lastObject.uuid ] = index; + + } + + objects[ index ] = lastObject; + objects.pop(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ]; + + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); + + } + + } // cached or active + + } // if object is known + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // Internal interface used by befriended PropertyBinding.Composite: + + subscribe_( path, parsedPath ) { + + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group + + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; + + if ( index !== undefined ) return bindings[ index ]; + + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); + + index = bindings.length; + + indicesByPath[ path ] = index; + + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); + + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + + } + + return bindingsForPath; + + } + + unsubscribe_( path ) { + + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' + + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; + + if ( index !== undefined ) { + + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; + + indicesByPath[ lastBindingsPath ] = index; + + bindings[ index ] = lastBindings; + bindings.pop(); + + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); + + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); + + } + + } + +} + +class AnimationAction { + + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); + + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + + for ( let i = 0; i !== nTracks; ++ i ) { + + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; + + } + + this._interpolantSettings = interpolantSettings; + + this._interpolants = interpolants; // bound by the mixer + + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); + + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager + + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + + this.loop = LoopRepeat; + this._loopCount = - 1; + + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; + + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; + + this.timeScale = 1; + this._effectiveTimeScale = 1; + + this.weight = 1; + this._effectiveWeight = 1; + + this.repetitions = Infinity; // no. of repetitions when looping + + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight + + this.clampWhenFinished = false;// keep feeding the last frame? + + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end + + } + + // State & Scheduling + + play() { + + this._mixer._activateAction( this ); + + return this; + + } + + stop() { + + this._mixer._deactivateAction( this ); + + return this.reset(); + + } + + reset() { + + 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(); + + } + + isRunning() { + + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); + + } + + // return true when play has been called + isScheduled() { + + return this._mixer._isActiveAction( this ); + + } + + startAt( time ) { + + this._startTime = time; + + return this; + + } + + setLoop( mode, repetitions ) { + + this.loop = mode; + this.repetitions = repetitions; + + return this; + + } + + // Weight + + // 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( weight ) { + + this.weight = weight; + + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; + + return this.stopFading(); + + } + + // return the weight considering fading and .enabled + getEffectiveWeight() { + + return this._effectiveWeight; + + } + + fadeIn( duration ) { + + return this._scheduleFading( duration, 0, 1 ); + + } + + fadeOut( duration ) { + + return this._scheduleFading( duration, 1, 0 ); + + } + + crossFadeFrom( fadeOutAction, duration, warp ) { + + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); + + if ( warp ) { + + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, + + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; + + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); + + } + + return this; + + } + + crossFadeTo( fadeInAction, duration, warp ) { + + return fadeInAction.crossFadeFrom( this, duration, warp ); + + } + + stopFading() { + + const weightInterpolant = this._weightInterpolant; + + if ( weightInterpolant !== null ) { + + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); + + } + + return this; + + } + + // Time Scale Control + + // set the time scale 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( timeScale ) { + + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + + return this.stopWarping(); + + } + + // return the time scale considering warping and .paused + getEffectiveTimeScale() { + + return this._effectiveTimeScale; + + } + + setDuration( duration ) { + + this.timeScale = this._clip.duration / duration; + + return this.stopWarping(); + + } + + syncWith( action ) { + + this.time = action.time; + this.timeScale = action.timeScale; + + return this.stopWarping(); + + } + + halt( duration ) { + + return this.warp( this._effectiveTimeScale, 0, duration ); + + } + + warp( startTimeScale, endTimeScale, duration ) { + + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; + + let interpolant = this._timeScaleInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + times[ 1 ] = now + duration; + + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; + + return this; + + } + + stopWarping() { + + const timeScaleInterpolant = this._timeScaleInterpolant; + + if ( timeScaleInterpolant !== null ) { + + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + + } + + return this; + + } + + // Object Accessors + + getMixer() { + + return this._mixer; + + } + + getClip() { + + return this._clip; + + } + + getRoot() { + + return this._localRoot || this._mixer._root; + + } + + // Interna + + _update( time, deltaTime, timeDirection, accuIndex ) { + + // called by the mixer + + if ( ! this.enabled ) { + + // call ._updateWeight() to update ._effectiveWeight + + this._updateWeight( time ); + return; + + } + + const startTime = this._startTime; + + if ( startTime !== null ) { + + // check for scheduled start of action + + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { + + deltaTime = 0; + + } else { + + + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; + + } + + } + + // apply time scale and advance time + + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); + + // note: _updateTime may disable the action resulting in + // an effective weight of 0 + + const weight = this._updateWeight( time ); + + if ( weight > 0 ) { + + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + + switch ( this.blendMode ) { + + case AdditiveAnimationBlendMode: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); + + } + + break; + + case NormalAnimationBlendMode: + default: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); + + } + + } + + } + + } + + _updateWeight( time ) { + + let weight = 0; + + if ( this.enabled ) { + + weight = this.weight; + const interpolant = this._weightInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + weight *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopFading(); + + if ( interpolantValue === 0 ) { + + // faded out, disable + this.enabled = false; + + } + + } + + } + + } + + this._effectiveWeight = weight; + return weight; + + } + + _updateTimeScale( time ) { + + let timeScale = 0; + + if ( ! this.paused ) { + + timeScale = this.timeScale; + + const interpolant = this._timeScaleInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + timeScale *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopWarping(); + + if ( timeScale === 0 ) { + + // motion has halted, pause + this.paused = true; + + } else { + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + } + + } + + } + + this._effectiveTimeScale = timeScale; + return timeScale; + + } + + _updateTime( deltaTime ) { + + const duration = this._clip.duration; + const loop = this.loop; + + let time = this.time + deltaTime; + let loopCount = this._loopCount; + + const pingPong = ( loop === LoopPingPong ); + + if ( deltaTime === 0 ) { + + if ( loopCount === - 1 ) return time; + + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + + } + + if ( loop === LoopOnce ) { + + if ( loopCount === - 1 ) { + + // just started + + this._loopCount = 0; + this._setEndings( true, true, false ); + + } + + handle_stop: { + + if ( time >= duration ) { + + time = duration; + + } else if ( time < 0 ) { + + time = 0; + + } else { + + this.time = time; + + break handle_stop; + + } + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); + + } + + } else { // repetitive Repeat or PingPong + + if ( loopCount === - 1 ) { + + // just started + + if ( deltaTime >= 0 ) { + + loopCount = 0; + + this._setEndings( true, this.repetitions === 0, pingPong ); + + } else { + + // 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 ( time >= duration || time < 0 ) { + + // wrap around + + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; + + loopCount += Math.abs( loopDelta ); + + const pending = this.repetitions - loopCount; + + if ( pending <= 0 ) { + + // have to stop (switch state, clamp time, fire event) + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + time = deltaTime > 0 ? duration : 0; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); + + } else { + + // keep running + + if ( pending === 1 ) { + + // entering the last round + + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); + + } else { + + this._setEndings( false, false, pingPong ); + + } + + this._loopCount = loopCount; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); + + } + + } else { + + this.time = time; + + } + + if ( pingPong && ( loopCount & 1 ) === 1 ) { + + // invert time for the "pong round" + + return duration - time; + + } + + } + + return time; + + } + + _setEndings( atStart, atEnd, pingPong ) { + + const settings = this._interpolantSettings; + + if ( pingPong ) { + + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + + } else { + + // assuming for LoopOnce atStart == atEnd == true + + if ( atStart ) { + + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingStart = WrapAroundEnding; + + } + + if ( atEnd ) { + + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingEnd = WrapAroundEnding; + + } + + } + + } + + _scheduleFading( duration, weightNow, weightThen ) { + + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; + + return this; + + } + +} + +const _controlInterpolantsResultBuffer = new Float32Array( 1 ); + + +class AnimationMixer extends EventDispatcher { + + constructor( root ) { + + super(); + + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1.0; + + } + + _bindAction( action, prototypeAction ) { + + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; + + let bindingsByName = bindingsByRoot[ rootUuid ]; + + if ( bindingsByName === undefined ) { + + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; + + } + + for ( let i = 0; i !== nTracks; ++ i ) { + + const track = tracks[ i ], + trackName = track.name; + + let binding = bindingsByName[ trackName ]; + + if ( binding !== undefined ) { + + ++ binding.referenceCount; + bindings[ i ] = binding; + + } else { + + binding = bindings[ i ]; + + if ( binding !== undefined ) { + + // existing binding, make sure the cache knows + + if ( binding._cacheIndex === null ) { + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + } + + continue; + + } + + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; + + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + bindings[ i ] = binding; + + } + + interpolants[ i ].resultBuffer = binding.buffer; + + } + + } + + _activateAction( action ) { + + if ( ! this._isActiveAction( action ) ) { + + if ( action._cacheIndex === null ) { + + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind + + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; + + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); + + this._addInactiveAction( action, clipUuid, rootUuid ); + + } + + const bindings = action._propertyBindings; + + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( binding.useCount ++ === 0 ) { + + this._lendBinding( binding ); + binding.saveOriginalState(); + + } + + } + + this._lendAction( action ); + + } + + } + + _deactivateAction( action ) { + + if ( this._isActiveAction( action ) ) { + + const bindings = action._propertyBindings; + + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.useCount === 0 ) { + + binding.restoreOriginalState(); + this._takeBackBinding( binding ); + + } + + } + + this._takeBackAction( action ); + + } + + } + + // Memory manager + + _initMemoryManager() { + + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; + + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } + + + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; + + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + + + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; + + const scope = this; + + this.stats = { + + 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; + + } + } + + }; + + } + + // Memory management for AnimationAction objects + + _isActiveAction( action ) { + + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + + } + + _addInactiveAction( action, clipUuid, rootUuid ) { + + const actions = this._actions, + actionsByClip = this._actionsByClip; + + let actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip === undefined ) { + + actionsForClip = { + + knownActions: [ action ], + actionByRoot: {} + + }; + + action._byClipCacheIndex = 0; + + actionsByClip[ clipUuid ] = actionsForClip; + + } else { + + const knownActions = actionsForClip.knownActions; + + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); + + } + + action._cacheIndex = actions.length; + actions.push( action ); + + actionsForClip.actionByRoot[ rootUuid ] = action; + + } + + _removeInactiveAction( action ) { + + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + action._cacheIndex = null; + + + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, + + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], + + byClipCacheIndex = action._byClipCacheIndex; + + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); + + action._byClipCacheIndex = null; + + + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; + + delete actionByRoot[ rootUuid ]; + + if ( knownActionsForClip.length === 0 ) { + + delete actionsByClip[ clipUuid ]; + + } + + this._removeInactiveBindingsForAction( action ); + + } + + _removeInactiveBindingsForAction( action ) { + + const bindings = action._propertyBindings; + + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.referenceCount === 0 ) { + + this._removeInactiveBinding( binding ); + + } + + } + + } + + _lendAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s + + const actions = this._actions, + prevIndex = action._cacheIndex, + + lastActiveIndex = this._nActiveActions ++, + + firstInactiveAction = actions[ lastActiveIndex ]; + + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; + + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; + + } + + _takeBackAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a + + const actions = this._actions, + prevIndex = action._cacheIndex, + + firstInactiveIndex = -- this._nActiveActions, + + lastActiveAction = actions[ firstInactiveIndex ]; + + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; + + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; + + } + + // Memory management for PropertyMixer objects + + _addInactiveBinding( binding, rootUuid, trackName ) { + + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; + + let bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName === undefined ) { + + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; + + } + + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); + + } + + _removeInactiveBinding( binding ) { + + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], + + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; + + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); + + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { + + delete bindingsByRoot[ rootUuid ]; + + } + + } + + _lendBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + lastActiveIndex = this._nActiveBindings ++, + + firstInactiveBinding = bindings[ lastActiveIndex ]; + + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; + + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; + + } + + _takeBackBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + firstInactiveIndex = -- this._nActiveBindings, + + lastActiveBinding = bindings[ firstInactiveIndex ]; + + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; + + } + + + // Memory management of Interpolants for weight and time scale + + _lendControlInterpolant() { + + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; + + let interpolant = interpolants[ lastActiveIndex ]; + + if ( interpolant === undefined ) { + + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); + + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; + + } + + return interpolant; + + } + + _takeBackControlInterpolant( interpolant ) { + + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, + + firstInactiveIndex = -- this._nActiveControlInterpolants, + + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; + + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; + + } + + // 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( clip, optionalRoot, blendMode ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid; + + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; + + if ( blendMode === undefined ) { + + if ( clipObject !== null ) { + + blendMode = clipObject.blendMode; + + } else { + + blendMode = NormalAnimationBlendMode; + + } + + } + + if ( actionsForClip !== undefined ) { + + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + + return existingAction; + + } + + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; + + // 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 + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); + + this._bindAction( newAction, prototypeAction ); + + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); + + return newAction; + + } + + // get an existing action + existingAction( clip, optionalRoot ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid, + + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, + + clipUuid = clipObject ? clipObject.uuid : clip, + + actionsForClip = this._actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + return actionsForClip.actionByRoot[ rootUuid ] || null; + + } + + return null; + + } + + // deactivates all previously scheduled actions + stopAllAction() { + + const actions = this._actions, + nActions = this._nActiveActions; + + for ( let i = nActions - 1; i >= 0; -- i ) { + + actions[ i ].stop(); + + } + + return this; + + } + + // advance the time and update apply the animation + update( deltaTime ) { + + deltaTime *= this.timeScale; + + const actions = this._actions, + nActions = this._nActiveActions, + + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), + + accuIndex = this._accuIndex ^= 1; + + // run active actions + + for ( let i = 0; i !== nActions; ++ i ) { + + const action = actions[ i ]; + + action._update( time, deltaTime, timeDirection, accuIndex ); + + } + + // update scene graph + + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { + + bindings[ i ].apply( accuIndex ); + + } + + return this; + + } + + // Allows you to seek to a specific time in an animation. + setTime( timeInSeconds ) { + + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { + + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. + + } + + // return this mixer's root target object + getRoot() { + + return this._root; + + } + + // free all resources specific to a particular clip + uncacheClip( clip ) { + + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away + + const actionsToRemove = actionsForClip.knownActions; + + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + + const action = actionsToRemove[ i ]; + + this._deactivateAction( action ); + + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; + + action._cacheIndex = null; + action._byClipCacheIndex = null; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + this._removeInactiveBindingsForAction( action ); + + } + + delete actionsByClip[ clipUuid ]; + + } + + } + + // free all resources specific to a particular root target object + uncacheRoot( root ) { + + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; + + for ( const clipUuid in actionsByClip ) { + + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; + + if ( action !== undefined ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName !== undefined ) { + + for ( const trackName in bindingByName ) { + + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); + + } + + } + + } + + // remove a targeted clip from the cache + uncacheAction( clip, optionalRoot ) { + + const action = this.existingAction( clip, optionalRoot ); + + if ( action !== null ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + +} + +class Uniform { + + constructor( value ) { + + this.value = value; + + } + + clone() { + + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + + } + +} + +let id = 0; + +class UniformsGroup extends EventDispatcher { + + constructor() { + + super(); + + this.isUniformsGroup = true; + + Object.defineProperty( this, 'id', { value: id ++ } ); + + this.name = ''; + + this.usage = StaticDrawUsage; + this.uniforms = []; + + } + + add( uniform ) { + + this.uniforms.push( uniform ); + + return this; + + } + + remove( uniform ) { + + const index = this.uniforms.indexOf( uniform ); + + if ( index !== - 1 ) this.uniforms.splice( index, 1 ); + + return this; + + } + + setName( name ) { + + this.name = name; + + return this; + + } + + setUsage( value ) { + + this.usage = value; + + return this; + + } + + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + return this; + + } + + copy( source ) { + + this.name = source.name; + this.usage = source.usage; + + const uniformsSource = source.uniforms; + + this.uniforms.length = 0; + + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { + + this.uniforms.push( uniformsSource[ i ].clone() ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +class InstancedInterleavedBuffer extends InterleavedBuffer { + + constructor( array, stride, meshPerAttribute = 1 ) { + + super( array, stride ); + + this.isInstancedInterleavedBuffer = true; + + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + clone( data ) { + + const ib = super.clone( data ); + + ib.meshPerAttribute = this.meshPerAttribute; + + return ib; + + } + + toJSON( data ) { + + const json = super.toJSON( data ); + + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + + return json; + + } + +} + +class GLBufferAttribute { + + constructor( buffer, type, itemSize, elementSize, count ) { + + this.isGLBufferAttribute = true; + + this.name = ''; + + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + + this.version = 0; + + } + + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + setBuffer( buffer ) { + + this.buffer = buffer; + + return this; + + } + + setType( type, elementSize ) { + + this.type = type; + this.elementSize = elementSize; + + return this; + + } + + setItemSize( itemSize ) { + + this.itemSize = itemSize; + + return this; + + } + + setCount( count ) { + + this.count = count; + + return this; + + } + +} + +class Raycaster { + + constructor( origin, direction, near = 0, far = Infinity ) { + + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) + + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } + + set( origin, direction ) { + + // direction is assumed to be normalized (for accurate distance calculations) + + this.ray.set( origin, direction ); + + } + + setFromCamera( coords, camera ) { + + if ( camera.isPerspectiveCamera ) { + + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; + + } else if ( camera.isOrthographicCamera ) { + + 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 ); + this.camera = camera; + + } else { + + console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type ); + + } + + } + + intersectObject( object, recursive = true, intersects = [] ) { + + intersectObject( object, this, intersects, recursive ); + + intersects.sort( ascSort ); + + return intersects; + + } + + intersectObjects( objects, recursive = true, intersects = [] ) { + + for ( let i = 0, l = objects.length; i < l; i ++ ) { + + intersectObject( objects[ i ], this, intersects, recursive ); + + } + + intersects.sort( ascSort ); + + return intersects; + + } + +} + +function ascSort( a, b ) { + + return a.distance - b.distance; + +} + +function intersectObject( object, raycaster, intersects, recursive ) { + + if ( object.layers.test( raycaster.layers ) ) { + + object.raycast( raycaster, intersects ); + + } + + if ( recursive === true ) { + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + intersectObject( children[ i ], raycaster, intersects, true ); + + } + + } + +} + +/** + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ + +class Spherical { + + constructor( radius = 1, phi = 0, theta = 0 ) { + + this.radius = radius; + this.phi = phi; // polar angle + this.theta = theta; // azimuthal angle + + return this; + + } + + set( radius, phi, theta ) { + + this.radius = radius; + this.phi = phi; + this.theta = theta; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + + return this; + + } + + // restrict phi to be between EPS and PI-EPS + makeSafe() { + + const EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + y * y + z * z ); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) ); + + } + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + */ + +class Cylindrical { + + constructor( radius = 1, theta = 0, y = 0 ) { + + this.radius = radius; // distance from the origin to a point in the x-z plane + this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = y; // height above the x-z plane + + return this; + + } + + set( radius, theta, y ) { + + this.radius = radius; + this.theta = theta; + this.y = y; + + return this; + + } + + copy( other ) { + + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + + return this; + + } + + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$4 = /*@__PURE__*/ new Vector2(); + +class Box2 { + + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + + this.isBox2 = true; + + this.min = min; + this.max = max; + + } + + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + clone() { + + return new this.constructor().copy( this ); + + } + + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + makeEmpty() { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + + } + + isEmpty() { + + // 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 ); + + } + + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + containsPoint( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; + + } + + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + + } + + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + + } + + intersectsBox( box ) { + + // using 4 splitting planes to rule out intersections + + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + + } + + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + distanceToPoint( point ) { + + const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); + + } + + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + return this; + + } + + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + +} + +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); + +class Line3 { + + constructor( start = new Vector3(), end = new Vector3() ) { + + this.start = start; + this.end = end; + + } + + set( start, end ) { + + this.start.copy( start ); + this.end.copy( end ); + + return this; + + } + + copy( line ) { + + this.start.copy( line.start ); + this.end.copy( line.end ); + + return this; + + } + + getCenter( target ) { + + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + + } + + delta( target ) { + + return target.subVectors( this.end, this.start ); + + } + + distanceSq() { + + return this.start.distanceToSquared( this.end ); + + } + + distance() { + + return this.start.distanceTo( this.end ); + + } + + at( t, target ) { + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + closestPointToPointParameter( point, clampToLine ) { + + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); + + const startEnd2 = _startEnd.dot( _startEnd ); + const startEnd_startP = _startEnd.dot( _startP ); + + let t = startEnd_startP / startEnd2; + + if ( clampToLine ) { + + t = clamp( t, 0, 1 ); + + } + + return t; + + } + + closestPointToPoint( point, clampToLine, target ) { + + const t = this.closestPointToPointParameter( point, clampToLine ); + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + applyMatrix4( matrix ) { + + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); + + return this; + + } + + equals( line ) { + + return line.start.equals( this.start ) && line.end.equals( this.end ); + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$3 = /*@__PURE__*/ new Vector3(); + +class SpotLightHelper extends Object3D { + + constructor( light, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'SpotLightHelper'; + + const geometry = new BufferGeometry(); + + const 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 ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; + + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); + + this.update(); + + } + + dispose() { + + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); + + this.cone.scale.set( coneWidth, coneWidth, coneLength ); + + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); + + this.cone.lookAt( _vector$3 ); + + if ( this.color !== undefined ) { + + this.cone.material.color.set( this.color ); + + } else { + + this.cone.material.color.copy( this.light.color ); + + } + + } + +} + +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _boneMatrix = /*@__PURE__*/ new Matrix4(); +const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + + +class SkeletonHelper extends LineSegments { + + constructor( object ) { + + const bones = getBoneList( object ); + + const geometry = new BufferGeometry(); + + const vertices = []; + const colors = []; + + const color1 = new Color( 0, 0, 1 ); + const color2 = new Color( 0, 1, 0 ); + + for ( let i = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); + + } + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + + super( geometry, material ); + + this.isSkeletonHelper = true; + + this.type = 'SkeletonHelper'; + + this.root = object; + this.bones = bones; + + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + + } + + updateMatrixWorld( force ) { + + const bones = this.bones; + + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); + + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + + for ( let i = 0, j = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); + + j += 2; + + } + + } + + geometry.getAttribute( 'position' ).needsUpdate = true; + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function getBoneList( object ) { + + const boneList = []; + + if ( object.isBone === true ) { + + boneList.push( object ); + + } + + for ( let i = 0; i < object.children.length; i ++ ) { + + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + + } + + return boneList; + +} + +class PointLightHelper extends Mesh { + + constructor( light, sphereSize, color ) { + + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + + super( geometry, material ); + + this.light = light; + + this.color = color; + + this.type = 'PointLightHelper'; + + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + + this.update(); + + + /* + // TODO: delete this comment? + const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); + const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); + + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); + + const d = light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.scale.set( d, d, d ); + + } + + this.add( this.lightDistance ); + */ + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ); + + } + + /* + const d = this.light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); + + } + */ + + } + +} + +const _vector$1 = /*@__PURE__*/ new Vector3(); +const _color1 = /*@__PURE__*/ new Color(); +const _color2 = /*@__PURE__*/ new Color(); + +class HemisphereLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'HemisphereLightHelper'; + + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); + + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; + + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); + + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + + this.add( new Mesh( geometry, this.material ) ); + + this.update(); + + } + + dispose() { + + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + + update() { + + const mesh = this.children[ 0 ]; + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + const colors = mesh.geometry.getAttribute( 'color' ); + + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); + + for ( let i = 0, l = colors.count; i < l; i ++ ) { + + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + + colors.setXYZ( i, color.r, color.g, color.b ); + + } + + colors.needsUpdate = true; + + } + + this.light.updateWorldMatrix( true, false ); + + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + + } + +} + +class GridHelper extends LineSegments { + + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + + const vertices = [], colors = []; + + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); + + const color = i === center ? color1 : color2; + + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'GridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class PolarGridHelper extends LineSegments { + + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const vertices = []; + const colors = []; + + // create the sectors + + if ( sectors > 1 ) { + + for ( let i = 0; i < sectors; i ++ ) { + + const v = ( i / sectors ) * ( Math.PI * 2 ); + + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; + + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); + + const color = ( i & 1 ) ? color1 : color2; + + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); + + } + + } + + // create the rings + + for ( let i = 0; i < rings; i ++ ) { + + const color = ( i & 1 ) ? color1 : color2; + + const r = radius - ( radius / rings * i ); + + for ( let j = 0; j < divisions; j ++ ) { + + // first vertex + + let v = ( j / divisions ) * ( Math.PI * 2 ); + + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + // second vertex + + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + } + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'PolarGridHelper'; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +const _v1 = /*@__PURE__*/ new Vector3(); +const _v2 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); + +class DirectionalLightHelper extends Object3D { + + constructor( light, size, color ) { + + super(); + + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + this.color = color; + + this.type = 'DirectionalLightHelper'; + + if ( size === undefined ) size = 1; + + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); + + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); + + this.update(); + + } + + dispose() { + + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + + } + + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); + + this.lightPlane.lookAt( _v2 ); + + if ( this.color !== undefined ) { + + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); + + } else { + + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); + + } + + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); + + } + +} + +const _vector = /*@__PURE__*/ new Vector3(); +const _camera = /*@__PURE__*/ new Camera(); + +/** + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html + */ + +class CameraHelper extends LineSegments { + + constructor( camera ) { + + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + + const vertices = []; + const colors = []; + + const pointMap = {}; + + // near + + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); + + // far + + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); + + // sides + + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); + + // cone + + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); + + // up + + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); + + // target + + addLine( 'c', 't' ); + addLine( 'p', 'c' ); + + // cross + + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); + + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); + + function addLine( a, b ) { + + addPoint( a ); + addPoint( b ); + + } + + function addPoint( id ) { + + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + + if ( pointMap[ id ] === undefined ) { + + pointMap[ id ] = []; + + } + + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + super( geometry, material ); + + this.type = 'CameraHelper'; + + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + + this.pointMap = pointMap; + + this.update(); + + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + + } + + update() { + + const geometry = this.geometry; + const pointMap = this.pointMap; + + const w = 1, h = 1; + + // we need just camera projection matrix inverse + // world matrix must be identity + + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + + // center / target + + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + + // near + + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); + + // far + + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + + // up + + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + + // cross + + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + + geometry.getAttribute( 'position' ).needsUpdate = true; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function setPoint( point, pointMap, geometry, camera, x, y, z ) { + + _vector.set( x, y, z ).unproject( camera ); + + const points = pointMap[ point ]; + + if ( points !== undefined ) { + + const position = geometry.getAttribute( 'position' ); + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); + + } + + } + +} + +const _box = /*@__PURE__*/ new Box3(); + +class BoxHelper extends LineSegments { + + constructor( object, color = 0xffff00 ) { + + const 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 ] ); + const positions = new Float32Array( 8 * 3 ); + + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.object = object; + this.type = 'BoxHelper'; + + this.matrixAutoUpdate = false; + + this.update(); + + } + + update( object ) { + + if ( object !== undefined ) { + + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + + } + + if ( this.object !== undefined ) { + + _box.setFromObject( this.object ); + + } + + if ( _box.isEmpty() ) return; + + const min = _box.min; + const max = _box.max; + + /* + 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 + */ + + const position = this.geometry.attributes.position; + const 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; + + position.needsUpdate = true; + + this.geometry.computeBoundingSphere(); + + } + + setFromObject( object ) { + + this.object = object; + this.update(); + + return this; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.object = source.object; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class Box3Helper extends LineSegments { + + constructor( box, color = 0xffff00 ) { + + const 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 ] ); + + const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + + const geometry = new BufferGeometry(); + + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.box = box; + + this.type = 'Box3Helper'; + + this.geometry.computeBoundingSphere(); + + } + + updateMatrixWorld( force ) { + + const box = this.box; + + if ( box.isEmpty() ) return; + + box.getCenter( this.position ); + + box.getSize( this.scale ); + + this.scale.multiplyScalar( 0.5 ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class PlaneHelper extends Line { + + constructor( plane, size = 1, hex = 0xffff00 ) { + + const color = hex; + + const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.type = 'PlaneHelper'; + + this.plane = plane; + + this.size = size; + + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; + + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + + } + + updateMatrixWorld( force ) { + + this.position.set( 0, 0, 0 ); + + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); + + this.lookAt( this.plane.normal ); + + this.translateZ( - this.plane.constant ); + + super.updateMatrixWorld( force ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + +} + +const _axis = /*@__PURE__*/ new Vector3(); +let _lineGeometry, _coneGeometry; + +class ArrowHelper extends Object3D { + + // dir is assumed to be normalized + + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + super(); + + this.type = 'ArrowHelper'; + + if ( _lineGeometry === undefined ) { + + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + + _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); + + } + + this.position.copy( origin ); + + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); + + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); + + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); + + } + + setDirection( dir ) { + + // dir is assumed to be normalized + + if ( dir.y > 0.99999 ) { + + this.quaternion.set( 0, 0, 0, 1 ); + + } else if ( dir.y < - 0.99999 ) { + + this.quaternion.set( 1, 0, 0, 0 ); + + } else { + + _axis.set( dir.z, 0, - dir.x ).normalize(); + + const radians = Math.acos( dir.y ); + + this.quaternion.setFromAxisAngle( _axis, radians ); + + } + + } + + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); + + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); + + } + + setColor( color ) { + + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } + + copy( source ) { + + super.copy( source, false ); + + this.line.copy( source.line ); + this.cone.copy( source.cone ); + + return this; + + } + + dispose() { + + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + +} + +class AxesHelper extends LineSegments { + + constructor( size = 1 ) { + + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; + + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'AxesHelper'; + + } + + setColors( xAxisColor, yAxisColor, zAxisColor ) { + + const color = new Color(); + const array = this.geometry.attributes.color.array; + + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); + + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); + + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); + + this.geometry.attributes.color.needsUpdate = true; + + return this; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +class ShapePath { + + constructor() { + + this.type = 'ShapePath'; + + this.color = new Color(); + + this.subPaths = []; + this.currentPath = null; + + } + + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); + + return this; + + } + + lineTo( x, y ) { + + this.currentPath.lineTo( x, y ); + + return this; + + } + + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + + return this; + + } + + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + + return this; + + } + + splineThru( pts ) { + + this.currentPath.splineThru( pts ); + + return this; + + } + + toShapes( isCCW ) { + + function toShapesNoHoles( inSubpaths ) { + + const shapes = []; + + for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) { + + const tmpPath = inSubpaths[ i ]; + + const tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + + shapes.push( tmpShape ); + + } + + return shapes; + + } + + function isPointInsidePolygon( inPt, inPolygon ) { + + const polyLen = inPolygon.length; + + // 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 + let inside = false; + for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + + let edgeLowPt = inPolygon[ p ]; + let edgeHighPt = inPolygon[ q ]; + + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + + if ( Math.abs( edgeDy ) > Number.EPSILON ) { + + // not parallel + if ( edgeDy < 0 ) { + + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + + } + + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; + + 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 { + + const 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 + + } + + } 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; + + } + + } + + return inside; + + } + + const isClockWise = ShapeUtils.isClockWise; + + const subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; + + let solid, tmpPath, tmpShape; + const shapes = []; + + if ( subPaths.length === 1 ) { + + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; + + } + + let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; + + // console.log("Holes first", holesFirst); + + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; + + for ( let i = 0, l = subPaths.length; i < l; i ++ ) { + + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; + + if ( solid ) { + + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; + + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; + + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; + + //console.log('cw', i); + + } else { + + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + + //console.log('ccw', i); + + } + + } + + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); + + + if ( newShapes.length > 1 ) { + + let ambiguous = false; + let toChange = 0; + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + betterShapeHoles[ sIdx ] = []; + + } + + for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + + const sho = newShapeHoles[ sIdx ]; + + for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) { + + const ho = sho[ hIdx ]; + let hole_unassigned = true; + + for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + + if ( sIdx !== s2Idx ) toChange ++; + + if ( hole_unassigned ) { + + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); + + } else { + + ambiguous = true; + + } + + } + + } + + if ( hole_unassigned ) { + + betterShapeHoles[ sIdx ].push( ho ); + + } + + } + + } + + if ( toChange > 0 && ambiguous === false ) { + + newShapeHoles = betterShapeHoles; + + } + + } + + let tmpHoles; + + for ( let i = 0, il = newShapes.length; i < il; i ++ ) { + + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; + + for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + + tmpShape.holes.push( tmpHoles[ j ].h ); + + } + + } + + //console.log("shape", shapes); + + return shapes; + + } + +} + +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf + +const _tables = /*@__PURE__*/ _generateTables(); + +function _generateTables() { + + // float32 to float16 helpers + + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); + + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); + + for ( let i = 0; i < 256; ++ i ) { + + const e = i - 127; + + // very small number (0, -0) + + if ( e < - 27 ) { + + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // small number (denorm) + + } else if ( e < - 14 ) { + + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; + + // normal number + + } else if ( e <= 15 ) { + + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + // large number (Infinity, -Infinity) + + } else if ( e < 128 ) { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // stay (NaN, Infinity, -Infinity) + + } else { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + } + + } + + // float16 to float32 helpers + + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); + + for ( let i = 1; i < 1024; ++ i ) { + + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent + + // normalized + while ( ( m & 0x00800000 ) === 0 ) { + + m <<= 1; + e -= 0x00800000; // decrement exponent + + } + + m &= ~ 0x00800000; // clear leading 1 bit + e += 0x38800000; // adjust bias + + mantissaTable[ i ] = m | e; + + } + + for ( let i = 1024; i < 2048; ++ i ) { + + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + + } + + for ( let i = 1; i < 31; ++ i ) { + + exponentTable[ i ] = i << 23; + + } + + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; + + for ( let i = 33; i < 63; ++ i ) { + + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + + } + + exponentTable[ 63 ] = 0xc7800000; + + for ( let i = 1; i < 64; ++ i ) { + + if ( i !== 32 ) { + + offsetTable[ i ] = 1024; + + } + + } + + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; + +} + +// float32 to float16 + +function toHalfFloat( val ) { + + if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' ); + + val = clamp( val, - 65504, 65504 ); + + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); + +} + +// float16 to float32 + +function fromHalfFloat( val ) { + + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; + +} + +var DataUtils = /*#__PURE__*/Object.freeze({ + __proto__: null, + fromHalfFloat: fromHalfFloat, + toHalfFloat: toHalfFloat +}); + +// r144 + +class BoxBufferGeometry extends BoxGeometry { + + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { + + console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' ); + super( width, height, depth, widthSegments, heightSegments, depthSegments ); + + + } + +} + +// r144 + +class CapsuleBufferGeometry extends CapsuleGeometry { + + constructor( radius, length, capSegments, radialSegments ) { + + console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' ); + super( radius, length, capSegments, radialSegments ); + + } + +} + +// r144 + +class CircleBufferGeometry extends CircleGeometry { + + constructor( radius, segments, thetaStart, thetaLength ) { + + console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' ); + super( radius, segments, thetaStart, thetaLength ); + + } + +} + +// r144 + +class ConeBufferGeometry extends ConeGeometry { + + constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' ); + super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + +} + +// r144 + +class CylinderBufferGeometry extends CylinderGeometry { + + constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' ); + super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + } + +} + +// r144 + +class DodecahedronBufferGeometry extends DodecahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class ExtrudeBufferGeometry extends ExtrudeGeometry { + + constructor( shapes, options ) { + + console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' ); + super( shapes, options ); + + } + +} + +// r144 + +class IcosahedronBufferGeometry extends IcosahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class LatheBufferGeometry extends LatheGeometry { + + constructor( points, segments, phiStart, phiLength ) { + + console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' ); + super( points, segments, phiStart, phiLength ); + + } + +} + +// r144 + +class OctahedronBufferGeometry extends OctahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class PlaneBufferGeometry extends PlaneGeometry { + + constructor( width, height, widthSegments, heightSegments ) { + + console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' ); + super( width, height, widthSegments, heightSegments ); + + } + +} + +// r144 + +class PolyhedronBufferGeometry extends PolyhedronGeometry { + + constructor( vertices, indices, radius, detail ) { + + console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' ); + super( vertices, indices, radius, detail ); + + } + +} + +// r144 + +class RingBufferGeometry extends RingGeometry { + + constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + + console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' ); + super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ); + + } + +} + +// r144 + +class ShapeBufferGeometry extends ShapeGeometry { + + constructor( shapes, curveSegments ) { + + console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' ); + super( shapes, curveSegments ); + + } + +} + +// r144 + +class SphereBufferGeometry extends SphereGeometry { + + constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + + console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' ); + super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ); + + } + +} + +// r144 + +class TetrahedronBufferGeometry extends TetrahedronGeometry { + + constructor( radius, detail ) { + + console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' ); + super( radius, detail ); + + } + +} + +// r144 + +class TorusBufferGeometry extends TorusGeometry { + + constructor( radius, tube, radialSegments, tubularSegments, arc ) { + + console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' ); + super( radius, tube, radialSegments, tubularSegments, arc ); + + } + +} + +// r144 + +class TorusKnotBufferGeometry extends TorusKnotGeometry { + + constructor( radius, tube, tubularSegments, radialSegments, p, q ) { + + console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' ); + super( radius, tube, tubularSegments, radialSegments, p, q ); + + } + +} + +// r144 + +class TubeBufferGeometry extends TubeGeometry { + + constructor( path, tubularSegments, radius, radialSegments, closed ) { + + console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' ); + super( path, tubularSegments, radius, radialSegments, closed ); + + } + +} + +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + +} + +if ( typeof window !== 'undefined' ) { + + if ( window.__THREE__ ) { + + console.warn( 'WARNING: Multiple instances of Three.js being imported.' ); + + } else { + + window.__THREE__ = REVISION; + + } + +} + +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding }; diff --git a/renderer/index.html b/renderer/index.html new file mode 100644 index 0000000..1c3232e --- /dev/null +++ b/renderer/index.html @@ -0,0 +1,197 @@ + + + + 390 logo + + + + + + + + + + + + + + + + + + diff --git a/renderer/jsm/animation/AnimationClipCreator.js b/renderer/jsm/animation/AnimationClipCreator.js new file mode 100644 index 0000000..2646c7c --- /dev/null +++ b/renderer/jsm/animation/AnimationClipCreator.js @@ -0,0 +1,114 @@ +import { + AnimationClip, + BooleanKeyframeTrack, + ColorKeyframeTrack, + NumberKeyframeTrack, + Vector3, + VectorKeyframeTrack +} from 'three'; + +class AnimationClipCreator { + + static CreateRotationAnimation( period, axis = 'x' ) { + + const times = [ 0, period ], values = [ 0, 360 ]; + + const trackName = '.rotation[' + axis + ']'; + + const track = new NumberKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, period, [ track ] ); + + } + + static CreateScaleAxisAnimation( period, axis = 'x' ) { + + const times = [ 0, period ], values = [ 0, 1 ]; + + const trackName = '.scale[' + axis + ']'; + + const track = new NumberKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, period, [ track ] ); + + } + + static CreateShakeAnimation( duration, shakeScale ) { + + const times = [], values = [], tmp = new Vector3(); + + for ( let i = 0; i < duration * 10; i ++ ) { + + times.push( i / 10 ); + + tmp.set( Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0 ). + multiply( shakeScale ). + toArray( values, values.length ); + + } + + const trackName = '.position'; + + const track = new VectorKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, duration, [ track ] ); + + } + + static CreatePulsationAnimation( duration, pulseScale ) { + + const times = [], values = [], tmp = new Vector3(); + + for ( let i = 0; i < duration * 10; i ++ ) { + + times.push( i / 10 ); + + const scaleFactor = Math.random() * pulseScale; + tmp.set( scaleFactor, scaleFactor, scaleFactor ). + toArray( values, values.length ); + + } + + const trackName = '.scale'; + + const track = new VectorKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, duration, [ track ] ); + + } + + static CreateVisibilityAnimation( duration ) { + + const times = [ 0, duration / 2, duration ], values = [ true, false, true ]; + + const trackName = '.visible'; + + const track = new BooleanKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, duration, [ track ] ); + + } + + static CreateMaterialColorAnimation( duration, colors ) { + + const times = [], values = [], + timeStep = duration / colors.length; + + for ( let i = 0; i <= colors.length; i ++ ) { + + times.push( i * timeStep ); + values.push( colors[ i % colors.length ] ); + + } + + const trackName = '.material[0].color'; + + const track = new ColorKeyframeTrack( trackName, times, values ); + + return new AnimationClip( null, duration, [ track ] ); + + } + +} + +export { AnimationClipCreator }; diff --git a/renderer/jsm/animation/CCDIKSolver.js b/renderer/jsm/animation/CCDIKSolver.js new file mode 100644 index 0000000..7066c99 --- /dev/null +++ b/renderer/jsm/animation/CCDIKSolver.js @@ -0,0 +1,482 @@ +import { + BufferAttribute, + BufferGeometry, + Color, + Line, + LineBasicMaterial, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + Quaternion, + SphereGeometry, + Vector3 +} from 'three'; + +const _q = new Quaternion(); +const _targetPos = new Vector3(); +const _targetVec = new Vector3(); +const _effectorPos = new Vector3(); +const _effectorVec = new Vector3(); +const _linkPos = new Vector3(); +const _invLinkQ = new Quaternion(); +const _linkScale = new Vector3(); +const _axis = new Vector3(); +const _vector = new Vector3(); +const _matrix = new Matrix4(); + + +/** + * CCD Algorithm + * - https://sites.google.com/site/auraliusproject/ccd-algorithm + * + * // ik parameter example + * // + * // target, effector, index in links are bone index in skeleton.bones. + * // the bones relation should be + * // <-- parent child --> + * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector + * iks = [ { + * target: 1, + * effector: 2, + * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ], + * iteration: 10, + * minAngle: 0.0, + * maxAngle: 1.0, + * } ]; + */ + +class CCDIKSolver { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Array} iks + */ + constructor( mesh, iks = [] ) { + + this.mesh = mesh; + this.iks = iks; + + this._valid(); + + } + + /** + * Update all IK bones. + * + * @return {CCDIKSolver} + */ + update() { + + const iks = this.iks; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + this.updateOne( iks[ i ] ); + + } + + return this; + + } + + /** + * Update one IK bone + * + * @param {Object} ik parameter + * @return {CCDIKSolver} + */ + updateOne( ik ) { + + const bones = this.mesh.skeleton.bones; + + // for reference overhead reduction in loop + const math = Math; + + const effector = bones[ ik.effector ]; + const target = bones[ ik.target ]; + + // don't use getWorldPosition() here for the performance + // because it calls updateMatrixWorld( true ) inside. + _targetPos.setFromMatrixPosition( target.matrixWorld ); + + const links = ik.links; + const iteration = ik.iteration !== undefined ? ik.iteration : 1; + + for ( let i = 0; i < iteration; i ++ ) { + + let rotated = false; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + const link = bones[ links[ j ].index ]; + + // skip this link and following links. + // this skip is used for MMD performance optimization. + if ( links[ j ].enabled === false ) break; + + const limitation = links[ j ].limitation; + const rotationMin = links[ j ].rotationMin; + const rotationMax = links[ j ].rotationMax; + + // don't use getWorldPosition/Quaternion() here for the performance + // because they call updateMatrixWorld( true ) inside. + link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale ); + _invLinkQ.invert(); + _effectorPos.setFromMatrixPosition( effector.matrixWorld ); + + // work in link world + _effectorVec.subVectors( _effectorPos, _linkPos ); + _effectorVec.applyQuaternion( _invLinkQ ); + _effectorVec.normalize(); + + _targetVec.subVectors( _targetPos, _linkPos ); + _targetVec.applyQuaternion( _invLinkQ ); + _targetVec.normalize(); + + let angle = _targetVec.dot( _effectorVec ); + + if ( angle > 1.0 ) { + + angle = 1.0; + + } else if ( angle < - 1.0 ) { + + angle = - 1.0; + + } + + angle = math.acos( angle ); + + // skip if changing angle is too small to prevent vibration of bone + if ( angle < 1e-5 ) continue; + + if ( ik.minAngle !== undefined && angle < ik.minAngle ) { + + angle = ik.minAngle; + + } + + if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) { + + angle = ik.maxAngle; + + } + + _axis.crossVectors( _effectorVec, _targetVec ); + _axis.normalize(); + + _q.setFromAxisAngle( _axis, angle ); + link.quaternion.multiply( _q ); + + // TODO: re-consider the limitation specification + if ( limitation !== undefined ) { + + let c = link.quaternion.w; + + if ( c > 1.0 ) c = 1.0; + + const c2 = math.sqrt( 1 - c * c ); + link.quaternion.set( limitation.x * c2, + limitation.y * c2, + limitation.z * c2, + c ); + + } + + if ( rotationMin !== undefined ) { + + link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) ); + + } + + if ( rotationMax !== undefined ) { + + link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) ); + + } + + link.updateMatrixWorld( true ); + + rotated = true; + + } + + if ( ! rotated ) break; + + } + + return this; + + } + + /** + * Creates Helper + * + * @return {CCDIKHelper} + */ + createHelper() { + + return new CCDIKHelper( this.mesh, this.iks ); + + } + + // private methods + + _valid() { + + const iks = this.iks; + const bones = this.mesh.skeleton.bones; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + const effector = bones[ ik.effector ]; + const links = ik.links; + let link0, link1; + + link0 = effector; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + link1 = bones[ links[ j ].index ]; + + if ( link0.parent !== link1 ) { + + console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name ); + + } + + link0 = link1; + + } + + } + + } + +} + +function getPosition( bone, matrixWorldInv ) { + + return _vector + .setFromMatrixPosition( bone.matrixWorld ) + .applyMatrix4( matrixWorldInv ); + +} + +function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) { + + const v = getPosition( bone, matrixWorldInv ); + + array[ index * 3 + 0 ] = v.x; + array[ index * 3 + 1 ] = v.y; + array[ index * 3 + 2 ] = v.z; + +} + +/** + * Visualize IK bones + * + * @param {SkinnedMesh} mesh + * @param {Array} iks + */ +class CCDIKHelper extends Object3D { + + constructor( mesh, iks = [], sphereSize = 0.25 ) { + + super(); + + this.root = mesh; + this.iks = iks; + + this.matrix.copy( mesh.matrixWorld ); + this.matrixAutoUpdate = false; + + this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 ); + + this.targetSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0xff8888 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.effectorSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0x88ff88 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.linkSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0x8888ff ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.lineMaterial = new LineBasicMaterial( { + color: new Color( 0xff0000 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this._init(); + + } + + /** + * Updates IK bones visualization. + */ + updateMatrixWorld( force ) { + + const mesh = this.root; + + if ( this.visible ) { + + let offset = 0; + + const iks = this.iks; + const bones = mesh.skeleton.bones; + + _matrix.copy( mesh.matrixWorld ).invert(); + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + + const targetBone = bones[ ik.target ]; + const effectorBone = bones[ ik.effector ]; + + const targetMesh = this.children[ offset ++ ]; + const effectorMesh = this.children[ offset ++ ]; + + targetMesh.position.copy( getPosition( targetBone, _matrix ) ); + effectorMesh.position.copy( getPosition( effectorBone, _matrix ) ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = ik.links[ j ]; + const linkBone = bones[ link.index ]; + + const linkMesh = this.children[ offset ++ ]; + + linkMesh.position.copy( getPosition( linkBone, _matrix ) ); + + } + + const line = this.children[ offset ++ ]; + const array = line.geometry.attributes.position.array; + + setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix ); + setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = ik.links[ j ]; + const linkBone = bones[ link.index ]; + setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix ); + + } + + line.geometry.attributes.position.needsUpdate = true; + + } + + } + + this.matrix.copy( mesh.matrixWorld ); + + super.updateMatrixWorld( force ); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. + */ + dispose() { + + this.sphereGeometry.dispose(); + + this.targetSphereMaterial.dispose(); + this.effectorSphereMaterial.dispose(); + this.linkSphereMaterial.dispose(); + this.lineMaterial.dispose(); + + const children = this.children; + + for ( let i = 0; i < children.length; i ++ ) { + + const child = children[ i ]; + + if ( child.isLine ) child.geometry.dispose(); + + } + + } + + // private method + + _init() { + + const scope = this; + const iks = this.iks; + + function createLineGeometry( ik ) { + + const geometry = new BufferGeometry(); + const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 ); + geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + + return geometry; + + } + + function createTargetMesh() { + + return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial ); + + } + + function createEffectorMesh() { + + return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial ); + + } + + function createLinkMesh() { + + return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial ); + + } + + function createLine( ik ) { + + return new Line( createLineGeometry( ik ), scope.lineMaterial ); + + } + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + + this.add( createTargetMesh() ); + this.add( createEffectorMesh() ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + this.add( createLinkMesh() ); + + } + + this.add( createLine( ik ) ); + + } + + } + +} + +export { CCDIKSolver, CCDIKHelper }; diff --git a/renderer/jsm/animation/MMDAnimationHelper.js b/renderer/jsm/animation/MMDAnimationHelper.js new file mode 100644 index 0000000..b24dea1 --- /dev/null +++ b/renderer/jsm/animation/MMDAnimationHelper.js @@ -0,0 +1,1207 @@ +import { + AnimationMixer, + Object3D, + Quaternion, + Vector3 +} from 'three'; +import { CCDIKSolver } from '../animation/CCDIKSolver.js'; +import { MMDPhysics } from '../animation/MMDPhysics.js'; + +/** + * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader + * with MMD special features as IK, Grant, and Physics. + * + * Dependencies + * - ammo.js https://github.com/kripken/ammo.js + * - MMDPhysics + * - CCDIKSolver + * + * TODO + * - more precise grant skinning support. + */ +class MMDAnimationHelper { + + /** + * @param {Object} params - (optional) + * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true. + * @param {Number} params.afterglow - Default is 0.0. + * @param {boolean} params.resetPhysicsOnLoop - Default is true. + */ + constructor( params = {} ) { + + this.meshes = []; + + this.camera = null; + this.cameraTarget = new Object3D(); + this.cameraTarget.name = 'target'; + + this.audio = null; + this.audioManager = null; + + this.objects = new WeakMap(); + + this.configuration = { + sync: params.sync !== undefined ? params.sync : true, + afterglow: params.afterglow !== undefined ? params.afterglow : 0.0, + resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true, + pmxAnimation: params.pmxAnimation !== undefined ? params.pmxAnimation : false + }; + + this.enabled = { + animation: true, + ik: true, + grant: true, + physics: true, + cameraAnimation: true + }; + + this.onBeforePhysics = function ( /* mesh */ ) {}; + + // experimental + this.sharedPhysics = false; + this.masterPhysics = null; + + } + + /** + * Adds an Three.js Object to helper and setups animation. + * The anmation durations of added objects are synched + * if this.configuration.sync is true. + * + * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object + * @param {Object} params - (optional) + * @param {THREE.AnimationClip|Array} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined. + * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true. + * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60. + * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65. + * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3. + * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ). + * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0. + * @return {MMDAnimationHelper} + */ + add( object, params = {} ) { + + if ( object.isSkinnedMesh ) { + + this._addMesh( object, params ); + + } else if ( object.isCamera ) { + + this._setupCamera( object, params ); + + } else if ( object.type === 'Audio' ) { + + this._setupAudio( object, params ); + + } else { + + throw new Error( 'THREE.MMDAnimationHelper.add: ' + + 'accepts only ' + + 'THREE.SkinnedMesh or ' + + 'THREE.Camera or ' + + 'THREE.Audio instance.' ); + + } + + if ( this.configuration.sync ) this._syncDuration(); + + return this; + + } + + /** + * Removes an Three.js Object from helper. + * + * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object + * @return {MMDAnimationHelper} + */ + remove( object ) { + + if ( object.isSkinnedMesh ) { + + this._removeMesh( object ); + + } else if ( object.isCamera ) { + + this._clearCamera( object ); + + } else if ( object.type === 'Audio' ) { + + this._clearAudio( object ); + + } else { + + throw new Error( 'THREE.MMDAnimationHelper.remove: ' + + 'accepts only ' + + 'THREE.SkinnedMesh or ' + + 'THREE.Camera or ' + + 'THREE.Audio instance.' ); + + } + + if ( this.configuration.sync ) this._syncDuration(); + + return this; + + } + + /** + * Updates the animation. + * + * @param {Number} delta + * @return {MMDAnimationHelper} + */ + update( delta ) { + + if ( this.audioManager !== null ) this.audioManager.control( delta ); + + for ( let i = 0; i < this.meshes.length; i ++ ) { + + this._animateMesh( this.meshes[ i ], delta ); + + } + + if ( this.sharedPhysics ) this._updateSharedPhysics( delta ); + + if ( this.camera !== null ) this._animateCamera( this.camera, delta ); + + return this; + + } + + /** + * Changes the pose of SkinnedMesh as VPD specifies. + * + * @param {THREE.SkinnedMesh} mesh + * @param {Object} vpd - VPD content parsed MMDParser + * @param {Object} params - (optional) + * @param {boolean} params.resetPose - Default is true. + * @param {boolean} params.ik - Default is true. + * @param {boolean} params.grant - Default is true. + * @return {MMDAnimationHelper} + */ + pose( mesh, vpd, params = {} ) { + + if ( params.resetPose !== false ) mesh.pose(); + + const bones = mesh.skeleton.bones; + const boneParams = vpd.bones; + + const boneNameDictionary = {}; + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + boneNameDictionary[ bones[ i ].name ] = i; + + } + + const vector = new Vector3(); + const quaternion = new Quaternion(); + + for ( let i = 0, il = boneParams.length; i < il; i ++ ) { + + const boneParam = boneParams[ i ]; + const boneIndex = boneNameDictionary[ boneParam.name ]; + + if ( boneIndex === undefined ) continue; + + const bone = bones[ boneIndex ]; + bone.position.add( vector.fromArray( boneParam.translation ) ); + bone.quaternion.multiply( quaternion.fromArray( boneParam.quaternion ) ); + + } + + mesh.updateMatrixWorld( true ); + + // PMX animation system special path + if ( this.configuration.pmxAnimation && + mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) { + + const sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() ); + const ikSolver = params.ik !== false ? this._createCCDIKSolver( mesh ) : null; + const grantSolver = params.grant !== false ? this.createGrantSolver( mesh ) : null; + this._animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ); + + } else { + + if ( params.ik !== false ) { + + this._createCCDIKSolver( mesh ).update(); + + } + + if ( params.grant !== false ) { + + this.createGrantSolver( mesh ).update(); + + } + + } + + return this; + + } + + /** + * Enabes/Disables an animation feature. + * + * @param {string} key + * @param {boolean} enabled + * @return {MMDAnimationHelper} + */ + enable( key, enabled ) { + + if ( this.enabled[ key ] === undefined ) { + + throw new Error( 'THREE.MMDAnimationHelper.enable: ' + + 'unknown key ' + key ); + + } + + this.enabled[ key ] = enabled; + + if ( key === 'physics' ) { + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + this._optimizeIK( this.meshes[ i ], enabled ); + + } + + } + + return this; + + } + + /** + * Creates an GrantSolver instance. + * + * @param {THREE.SkinnedMesh} mesh + * @return {GrantSolver} + */ + createGrantSolver( mesh ) { + + return new GrantSolver( mesh, mesh.geometry.userData.MMD.grants ); + + } + + // private methods + + _addMesh( mesh, params ) { + + if ( this.meshes.indexOf( mesh ) >= 0 ) { + + throw new Error( 'THREE.MMDAnimationHelper._addMesh: ' + + 'SkinnedMesh \'' + mesh.name + '\' has already been added.' ); + + } + + this.meshes.push( mesh ); + this.objects.set( mesh, { looped: false } ); + + this._setupMeshAnimation( mesh, params.animation ); + + if ( params.physics !== false ) { + + this._setupMeshPhysics( mesh, params ); + + } + + return this; + + } + + _setupCamera( camera, params ) { + + if ( this.camera === camera ) { + + throw new Error( 'THREE.MMDAnimationHelper._setupCamera: ' + + 'Camera \'' + camera.name + '\' has already been set.' ); + + } + + if ( this.camera ) this.clearCamera( this.camera ); + + this.camera = camera; + + camera.add( this.cameraTarget ); + + this.objects.set( camera, {} ); + + if ( params.animation !== undefined ) { + + this._setupCameraAnimation( camera, params.animation ); + + } + + return this; + + } + + _setupAudio( audio, params ) { + + if ( this.audio === audio ) { + + throw new Error( 'THREE.MMDAnimationHelper._setupAudio: ' + + 'Audio \'' + audio.name + '\' has already been set.' ); + + } + + if ( this.audio ) this.clearAudio( this.audio ); + + this.audio = audio; + this.audioManager = new AudioManager( audio, params ); + + this.objects.set( this.audioManager, { + duration: this.audioManager.duration + } ); + + return this; + + } + + _removeMesh( mesh ) { + + let found = false; + let writeIndex = 0; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + if ( this.meshes[ i ] === mesh ) { + + this.objects.delete( mesh ); + found = true; + + continue; + + } + + this.meshes[ writeIndex ++ ] = this.meshes[ i ]; + + } + + if ( ! found ) { + + throw new Error( 'THREE.MMDAnimationHelper._removeMesh: ' + + 'SkinnedMesh \'' + mesh.name + '\' has not been added yet.' ); + + } + + this.meshes.length = writeIndex; + + return this; + + } + + _clearCamera( camera ) { + + if ( camera !== this.camera ) { + + throw new Error( 'THREE.MMDAnimationHelper._clearCamera: ' + + 'Camera \'' + camera.name + '\' has not been set yet.' ); + + } + + this.camera.remove( this.cameraTarget ); + + this.objects.delete( this.camera ); + this.camera = null; + + return this; + + } + + _clearAudio( audio ) { + + if ( audio !== this.audio ) { + + throw new Error( 'THREE.MMDAnimationHelper._clearAudio: ' + + 'Audio \'' + audio.name + '\' has not been set yet.' ); + + } + + this.objects.delete( this.audioManager ); + + this.audio = null; + this.audioManager = null; + + return this; + + } + + _setupMeshAnimation( mesh, animation ) { + + const objects = this.objects.get( mesh ); + + if ( animation !== undefined ) { + + const animations = Array.isArray( animation ) + ? animation : [ animation ]; + + objects.mixer = new AnimationMixer( mesh ); + + for ( let i = 0, il = animations.length; i < il; i ++ ) { + + objects.mixer.clipAction( animations[ i ] ).play(); + + } + + // TODO: find a workaround not to access ._clip looking like a private property + objects.mixer.addEventListener( 'loop', function ( event ) { + + const tracks = event.action._clip.tracks; + + if ( tracks.length > 0 && tracks[ 0 ].name.slice( 0, 6 ) !== '.bones' ) return; + + objects.looped = true; + + } ); + + } + + objects.ikSolver = this._createCCDIKSolver( mesh ); + objects.grantSolver = this.createGrantSolver( mesh ); + + return this; + + } + + _setupCameraAnimation( camera, animation ) { + + const animations = Array.isArray( animation ) + ? animation : [ animation ]; + + const objects = this.objects.get( camera ); + + objects.mixer = new AnimationMixer( camera ); + + for ( let i = 0, il = animations.length; i < il; i ++ ) { + + objects.mixer.clipAction( animations[ i ] ).play(); + + } + + } + + _setupMeshPhysics( mesh, params ) { + + const objects = this.objects.get( mesh ); + + // shared physics is experimental + + if ( params.world === undefined && this.sharedPhysics ) { + + const masterPhysics = this._getMasterPhysics(); + + if ( masterPhysics !== null ) world = masterPhysics.world; // eslint-disable-line no-undef + + } + + objects.physics = this._createMMDPhysics( mesh, params ); + + if ( objects.mixer && params.animationWarmup !== false ) { + + this._animateMesh( mesh, 0 ); + objects.physics.reset(); + + } + + objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 ); + + this._optimizeIK( mesh, true ); + + } + + _animateMesh( mesh, delta ) { + + const objects = this.objects.get( mesh ); + + const mixer = objects.mixer; + const ikSolver = objects.ikSolver; + const grantSolver = objects.grantSolver; + const physics = objects.physics; + const looped = objects.looped; + + if ( mixer && this.enabled.animation ) { + + // alternate solution to save/restore bones but less performant? + //mesh.pose(); + //this._updatePropertyMixersBuffer( mesh ); + + this._restoreBones( mesh ); + + mixer.update( delta ); + + this._saveBones( mesh ); + + // PMX animation system special path + if ( this.configuration.pmxAnimation && + mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) { + + if ( ! objects.sortedBonesData ) objects.sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() ); + + this._animatePMXMesh( + mesh, + objects.sortedBonesData, + ikSolver && this.enabled.ik ? ikSolver : null, + grantSolver && this.enabled.grant ? grantSolver : null + ); + + } else { + + if ( ikSolver && this.enabled.ik ) { + + mesh.updateMatrixWorld( true ); + ikSolver.update(); + + } + + if ( grantSolver && this.enabled.grant ) { + + grantSolver.update(); + + } + + } + + } + + if ( looped === true && this.enabled.physics ) { + + if ( physics && this.configuration.resetPhysicsOnLoop ) physics.reset(); + + objects.looped = false; + + } + + if ( physics && this.enabled.physics && ! this.sharedPhysics ) { + + this.onBeforePhysics( mesh ); + physics.update( delta ); + + } + + } + + // Sort bones in order by 1. transformationClass and 2. bone index. + // In PMX animation system, bone transformations should be processed + // in this order. + _sortBoneDataArray( boneDataArray ) { + + return boneDataArray.sort( function ( a, b ) { + + if ( a.transformationClass !== b.transformationClass ) { + + return a.transformationClass - b.transformationClass; + + } else { + + return a.index - b.index; + + } + + } ); + + } + + // PMX Animation system is a bit too complex and doesn't great match to + // Three.js Animation system. This method attempts to simulate it as much as + // possible but doesn't perfectly simulate. + // This method is more costly than the regular one so + // you are recommended to set constructor parameter "pmxAnimation: true" + // only if your PMX model animation doesn't work well. + // If you need better method you would be required to write your own. + _animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ) { + + _quaternionIndex = 0; + _grantResultMap.clear(); + + for ( let i = 0, il = sortedBonesData.length; i < il; i ++ ) { + + updateOne( mesh, sortedBonesData[ i ].index, ikSolver, grantSolver ); + + } + + mesh.updateMatrixWorld( true ); + return this; + + } + + _animateCamera( camera, delta ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer && this.enabled.cameraAnimation ) { + + mixer.update( delta ); + + camera.updateProjectionMatrix(); + + camera.up.set( 0, 1, 0 ); + camera.up.applyQuaternion( camera.quaternion ); + camera.lookAt( this.cameraTarget.position ); + + } + + } + + _optimizeIK( mesh, physicsEnabled ) { + + const iks = mesh.geometry.userData.MMD.iks; + const bones = mesh.geometry.userData.MMD.bones; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + const links = ik.links; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + const link = links[ j ]; + + if ( physicsEnabled === true ) { + + // disable IK of the bone the corresponding rigidBody type of which is 1 or 2 + // because its rotation will be overriden by physics + link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true; + + } else { + + link.enabled = true; + + } + + } + + } + + } + + _createCCDIKSolver( mesh ) { + + if ( CCDIKSolver === undefined ) { + + throw new Error( 'THREE.MMDAnimationHelper: Import CCDIKSolver.' ); + + } + + return new CCDIKSolver( mesh, mesh.geometry.userData.MMD.iks ); + + } + + _createMMDPhysics( mesh, params ) { + + if ( MMDPhysics === undefined ) { + + throw new Error( 'THREE.MMDPhysics: Import MMDPhysics.' ); + + } + + return new MMDPhysics( + mesh, + mesh.geometry.userData.MMD.rigidBodies, + mesh.geometry.userData.MMD.constraints, + params ); + + } + + /* + * Detects the longest duration and then sets it to them to sync. + * TODO: Not to access private properties ( ._actions and ._clip ) + */ + _syncDuration() { + + let max = 0.0; + + const objects = this.objects; + const meshes = this.meshes; + const camera = this.camera; + const audioManager = this.audioManager; + + // get the longest duration + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + const mixer = this.objects.get( meshes[ i ] ).mixer; + + if ( mixer === undefined ) continue; + + for ( let j = 0; j < mixer._actions.length; j ++ ) { + + const clip = mixer._actions[ j ]._clip; + + if ( ! objects.has( clip ) ) { + + objects.set( clip, { + duration: clip.duration + } ); + + } + + max = Math.max( max, objects.get( clip ).duration ); + + } + + } + + if ( camera !== null ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer !== undefined ) { + + for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) { + + const clip = mixer._actions[ i ]._clip; + + if ( ! objects.has( clip ) ) { + + objects.set( clip, { + duration: clip.duration + } ); + + } + + max = Math.max( max, objects.get( clip ).duration ); + + } + + } + + } + + if ( audioManager !== null ) { + + max = Math.max( max, objects.get( audioManager ).duration ); + + } + + max += this.configuration.afterglow; + + // update the duration + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const mixer = this.objects.get( this.meshes[ i ] ).mixer; + + if ( mixer === undefined ) continue; + + for ( let j = 0, jl = mixer._actions.length; j < jl; j ++ ) { + + mixer._actions[ j ]._clip.duration = max; + + } + + } + + if ( camera !== null ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer !== undefined ) { + + for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) { + + mixer._actions[ i ]._clip.duration = max; + + } + + } + + } + + if ( audioManager !== null ) { + + audioManager.duration = max; + + } + + } + + // workaround + + _updatePropertyMixersBuffer( mesh ) { + + const mixer = this.objects.get( mesh ).mixer; + + const propertyMixers = mixer._bindings; + const accuIndex = mixer._accuIndex; + + for ( let i = 0, il = propertyMixers.length; i < il; i ++ ) { + + const propertyMixer = propertyMixers[ i ]; + const buffer = propertyMixer.buffer; + const stride = propertyMixer.valueSize; + const offset = ( accuIndex + 1 ) * stride; + + propertyMixer.binding.getValue( buffer, offset ); + + } + + } + + /* + * Avoiding these two issues by restore/save bones before/after mixer animation. + * + * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer. + * Calculating IK, Grant, and Physics after mixer animation can break + * the cache coherency. + * + * 2. Applying Grant two or more times without reset the posing breaks model. + */ + _saveBones( mesh ) { + + const objects = this.objects.get( mesh ); + + const bones = mesh.skeleton.bones; + + let backupBones = objects.backupBones; + + if ( backupBones === undefined ) { + + backupBones = new Float32Array( bones.length * 7 ); + objects.backupBones = backupBones; + + } + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + const bone = bones[ i ]; + bone.position.toArray( backupBones, i * 7 ); + bone.quaternion.toArray( backupBones, i * 7 + 3 ); + + } + + } + + _restoreBones( mesh ) { + + const objects = this.objects.get( mesh ); + + const backupBones = objects.backupBones; + + if ( backupBones === undefined ) return; + + const bones = mesh.skeleton.bones; + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + const bone = bones[ i ]; + bone.position.fromArray( backupBones, i * 7 ); + bone.quaternion.fromArray( backupBones, i * 7 + 3 ); + + } + + } + + // experimental + + _getMasterPhysics() { + + if ( this.masterPhysics !== null ) return this.masterPhysics; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const physics = this.meshes[ i ].physics; + + if ( physics !== undefined && physics !== null ) { + + this.masterPhysics = physics; + return this.masterPhysics; + + } + + } + + return null; + + } + + _updateSharedPhysics( delta ) { + + if ( this.meshes.length === 0 || ! this.enabled.physics || ! this.sharedPhysics ) return; + + const physics = this._getMasterPhysics(); + + if ( physics === null ) return; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const p = this.meshes[ i ].physics; + + if ( p !== null && p !== undefined ) { + + p.updateRigidBodies(); + + } + + } + + physics.stepSimulation( delta ); + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const p = this.meshes[ i ].physics; + + if ( p !== null && p !== undefined ) { + + p.updateBones(); + + } + + } + + } + +} + +// Keep working quaternions for less GC +const _quaternions = []; +let _quaternionIndex = 0; + +function getQuaternion() { + + if ( _quaternionIndex >= _quaternions.length ) { + + _quaternions.push( new Quaternion() ); + + } + + return _quaternions[ _quaternionIndex ++ ]; + +} + +// Save rotation whose grant and IK are already applied +// used by grant children +const _grantResultMap = new Map(); + +function updateOne( mesh, boneIndex, ikSolver, grantSolver ) { + + const bones = mesh.skeleton.bones; + const bonesData = mesh.geometry.userData.MMD.bones; + const boneData = bonesData[ boneIndex ]; + const bone = bones[ boneIndex ]; + + // Return if already updated by being referred as a grant parent. + if ( _grantResultMap.has( boneIndex ) ) return; + + const quaternion = getQuaternion(); + + // Initialize grant result here to prevent infinite loop. + // If it's referred before updating with actual result later + // result without applyting IK or grant is gotten + // but better than composing of infinite loop. + _grantResultMap.set( boneIndex, quaternion.copy( bone.quaternion ) ); + + // @TODO: Support global grant and grant position + if ( grantSolver && boneData.grant && + ! boneData.grant.isLocal && boneData.grant.affectRotation ) { + + const parentIndex = boneData.grant.parentIndex; + const ratio = boneData.grant.ratio; + + if ( ! _grantResultMap.has( parentIndex ) ) { + + updateOne( mesh, parentIndex, ikSolver, grantSolver ); + + } + + grantSolver.addGrantRotation( bone, _grantResultMap.get( parentIndex ), ratio ); + + } + + if ( ikSolver && boneData.ik ) { + + // @TODO: Updating world matrices every time solving an IK bone is + // costly. Optimize if possible. + mesh.updateMatrixWorld( true ); + ikSolver.updateOne( boneData.ik ); + + // No confident, but it seems the grant results with ik links should be updated? + const links = boneData.ik.links; + + for ( let i = 0, il = links.length; i < il; i ++ ) { + + const link = links[ i ]; + + if ( link.enabled === false ) continue; + + const linkIndex = link.index; + + if ( _grantResultMap.has( linkIndex ) ) { + + _grantResultMap.set( linkIndex, _grantResultMap.get( linkIndex ).copy( bones[ linkIndex ].quaternion ) ); + + } + + } + + } + + // Update with the actual result here + quaternion.copy( bone.quaternion ); + +} + +// + +class AudioManager { + + /** + * @param {THREE.Audio} audio + * @param {Object} params - (optional) + * @param {Nuumber} params.delayTime + */ + constructor( audio, params = {} ) { + + this.audio = audio; + + this.elapsedTime = 0.0; + this.currentTime = 0.0; + this.delayTime = params.delayTime !== undefined + ? params.delayTime : 0.0; + + this.audioDuration = this.audio.buffer.duration; + this.duration = this.audioDuration + this.delayTime; + + } + + /** + * @param {Number} delta + * @return {AudioManager} + */ + control( delta ) { + + this.elapsed += delta; + this.currentTime += delta; + + if ( this._shouldStopAudio() ) this.audio.stop(); + if ( this._shouldStartAudio() ) this.audio.play(); + + return this; + + } + + // private methods + + _shouldStartAudio() { + + if ( this.audio.isPlaying ) return false; + + while ( this.currentTime >= this.duration ) { + + this.currentTime -= this.duration; + + } + + if ( this.currentTime < this.delayTime ) return false; + + // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration + if ( ( this.currentTime - this.delayTime ) > this.audioDuration ) return false; + + return true; + + } + + _shouldStopAudio() { + + return this.audio.isPlaying && + this.currentTime >= this.duration; + + } + +} + +const _q = new Quaternion(); + +/** + * Solver for Grant (Fuyo in Japanese. I just google translated because + * Fuyo may be MMD specific term and may not be common word in 3D CG terms.) + * Grant propagates a bone's transform to other bones transforms even if + * they are not children. + * @param {THREE.SkinnedMesh} mesh + * @param {Array} grants + */ +class GrantSolver { + + constructor( mesh, grants = [] ) { + + this.mesh = mesh; + this.grants = grants; + + } + + /** + * Solve all the grant bones + * @return {GrantSolver} + */ + update() { + + const grants = this.grants; + + for ( let i = 0, il = grants.length; i < il; i ++ ) { + + this.updateOne( grants[ i ] ); + + } + + return this; + + } + + /** + * Solve a grant bone + * @param {Object} grant - grant parameter + * @return {GrantSolver} + */ + updateOne( grant ) { + + const bones = this.mesh.skeleton.bones; + const bone = bones[ grant.index ]; + const parentBone = bones[ grant.parentIndex ]; + + if ( grant.isLocal ) { + + // TODO: implement + if ( grant.affectPosition ) { + + } + + // TODO: implement + if ( grant.affectRotation ) { + + } + + } else { + + // TODO: implement + if ( grant.affectPosition ) { + + } + + if ( grant.affectRotation ) { + + this.addGrantRotation( bone, parentBone.quaternion, grant.ratio ); + + } + + } + + return this; + + } + + addGrantRotation( bone, q, ratio ) { + + _q.set( 0, 0, 0, 1 ); + _q.slerp( q, ratio ); + bone.quaternion.multiply( _q ); + + return this; + + } + +} + +export { MMDAnimationHelper }; diff --git a/renderer/jsm/animation/MMDPhysics.js b/renderer/jsm/animation/MMDPhysics.js new file mode 100644 index 0000000..0570901 --- /dev/null +++ b/renderer/jsm/animation/MMDPhysics.js @@ -0,0 +1,1406 @@ +import { + Bone, + BoxGeometry, + CapsuleGeometry, + Color, + Euler, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + Quaternion, + SphereGeometry, + Vector3 +} from 'three'; + +/** + * Dependencies + * - Ammo.js https://github.com/kripken/ammo.js + * + * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine) + * for MMD model loaded by MMDLoader. + * + * TODO + * - Physics in Worker + */ + +/* global Ammo */ + +class MMDPhysics { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Array} rigidBodyParams + * @param {Array} (optional) constraintParams + * @param {Object} params - (optional) + * @param {Number} params.unitStep - Default is 1 / 65. + * @param {Integer} params.maxStepNum - Default is 3. + * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 ) + */ + constructor( mesh, rigidBodyParams, constraintParams = [], params = {} ) { + + if ( typeof Ammo === 'undefined' ) { + + throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' ); + + } + + this.manager = new ResourceManager(); + + this.mesh = mesh; + + /* + * I don't know why but 1/60 unitStep easily breaks models + * so I set it 1/65 so far. + * Don't set too small unitStep because + * the smaller unitStep can make the performance worse. + */ + this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65; + this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3; + this.gravity = new Vector3( 0, - 9.8 * 10, 0 ); + + if ( params.gravity !== undefined ) this.gravity.copy( params.gravity ); + + this.world = params.world !== undefined ? params.world : null; // experimental + + this.bodies = []; + this.constraints = []; + + this._init( mesh, rigidBodyParams, constraintParams ); + + } + + /** + * Advances Physics calculation and updates bones. + * + * @param {Number} delta - time in second + * @return {MMDPhysics} + */ + update( delta ) { + + const manager = this.manager; + const mesh = this.mesh; + + // rigid bodies and constrains are for + // mesh's world scale (1, 1, 1). + // Convert to (1, 1, 1) if it isn't. + + let isNonDefaultScale = false; + + const position = manager.allocThreeVector3(); + const quaternion = manager.allocThreeQuaternion(); + const scale = manager.allocThreeVector3(); + + mesh.matrixWorld.decompose( position, quaternion, scale ); + + if ( scale.x !== 1 || scale.y !== 1 || scale.z !== 1 ) { + + isNonDefaultScale = true; + + } + + let parent; + + if ( isNonDefaultScale ) { + + parent = mesh.parent; + + if ( parent !== null ) mesh.parent = null; + + scale.copy( this.mesh.scale ); + + mesh.scale.set( 1, 1, 1 ); + mesh.updateMatrixWorld( true ); + + } + + // calculate physics and update bones + + this._updateRigidBodies(); + this._stepSimulation( delta ); + this._updateBones(); + + // restore mesh if converted above + + if ( isNonDefaultScale ) { + + if ( parent !== null ) mesh.parent = parent; + + mesh.scale.copy( scale ); + + } + + manager.freeThreeVector3( scale ); + manager.freeThreeQuaternion( quaternion ); + manager.freeThreeVector3( position ); + + return this; + + } + + /** + * Resets rigid bodies transorm to current bone's. + * + * @return {MMDPhysics} + */ + reset() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].reset(); + + } + + return this; + + } + + /** + * Warm ups Rigid bodies. Calculates cycles steps. + * + * @param {Integer} cycles + * @return {MMDPhysics} + */ + warmup( cycles ) { + + for ( let i = 0; i < cycles; i ++ ) { + + this.update( 1 / 60 ); + + } + + return this; + + } + + /** + * Sets gravity. + * + * @param {Vector3} gravity + * @return {MMDPhysicsHelper} + */ + setGravity( gravity ) { + + this.world.setGravity( new Ammo.btVector3( gravity.x, gravity.y, gravity.z ) ); + this.gravity.copy( gravity ); + + return this; + + } + + /** + * Creates MMDPhysicsHelper + * + * @return {MMDPhysicsHelper} + */ + createHelper() { + + return new MMDPhysicsHelper( this.mesh, this ); + + } + + // private methods + + _init( mesh, rigidBodyParams, constraintParams ) { + + const manager = this.manager; + + // rigid body/constraint parameters are for + // mesh's default world transform as position(0, 0, 0), + // quaternion(0, 0, 0, 1) and scale(0, 0, 0) + + const parent = mesh.parent; + + if ( parent !== null ) mesh.parent = null; + + const currentPosition = manager.allocThreeVector3(); + const currentQuaternion = manager.allocThreeQuaternion(); + const currentScale = manager.allocThreeVector3(); + + currentPosition.copy( mesh.position ); + currentQuaternion.copy( mesh.quaternion ); + currentScale.copy( mesh.scale ); + + mesh.position.set( 0, 0, 0 ); + mesh.quaternion.set( 0, 0, 0, 1 ); + mesh.scale.set( 1, 1, 1 ); + + mesh.updateMatrixWorld( true ); + + if ( this.world === null ) { + + this.world = this._createWorld(); + this.setGravity( this.gravity ); + + } + + this._initRigidBodies( rigidBodyParams ); + this._initConstraints( constraintParams ); + + if ( parent !== null ) mesh.parent = parent; + + mesh.position.copy( currentPosition ); + mesh.quaternion.copy( currentQuaternion ); + mesh.scale.copy( currentScale ); + + mesh.updateMatrixWorld( true ); + + this.reset(); + + manager.freeThreeVector3( currentPosition ); + manager.freeThreeQuaternion( currentQuaternion ); + manager.freeThreeVector3( currentScale ); + + } + + _createWorld() { + + const config = new Ammo.btDefaultCollisionConfiguration(); + const dispatcher = new Ammo.btCollisionDispatcher( config ); + const cache = new Ammo.btDbvtBroadphase(); + const solver = new Ammo.btSequentialImpulseConstraintSolver(); + const world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config ); + return world; + + } + + _initRigidBodies( rigidBodies ) { + + for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) { + + this.bodies.push( new RigidBody( + this.mesh, this.world, rigidBodies[ i ], this.manager ) ); + + } + + } + + _initConstraints( constraints ) { + + for ( let i = 0, il = constraints.length; i < il; i ++ ) { + + const params = constraints[ i ]; + const bodyA = this.bodies[ params.rigidBodyIndex1 ]; + const bodyB = this.bodies[ params.rigidBodyIndex2 ]; + this.constraints.push( new Constraint( this.mesh, this.world, bodyA, bodyB, params, this.manager ) ); + + } + + } + + _stepSimulation( delta ) { + + const unitStep = this.unitStep; + let stepTime = delta; + let maxStepNum = ( ( delta / unitStep ) | 0 ) + 1; + + if ( stepTime < unitStep ) { + + stepTime = unitStep; + maxStepNum = 1; + + } + + if ( maxStepNum > this.maxStepNum ) { + + maxStepNum = this.maxStepNum; + + } + + this.world.stepSimulation( stepTime, maxStepNum, unitStep ); + + } + + _updateRigidBodies() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].updateFromBone(); + + } + + } + + _updateBones() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].updateBone(); + + } + + } + +} + +/** + * This manager's responsibilies are + * + * 1. manage Ammo.js and Three.js object resources and + * improve the performance and the memory consumption by + * reusing objects. + * + * 2. provide simple Ammo object operations. + */ +class ResourceManager { + + constructor() { + + // for Three.js + this.threeVector3s = []; + this.threeMatrix4s = []; + this.threeQuaternions = []; + this.threeEulers = []; + + // for Ammo.js + this.transforms = []; + this.quaternions = []; + this.vector3s = []; + + } + + allocThreeVector3() { + + return ( this.threeVector3s.length > 0 ) + ? this.threeVector3s.pop() + : new Vector3(); + + } + + freeThreeVector3( v ) { + + this.threeVector3s.push( v ); + + } + + allocThreeMatrix4() { + + return ( this.threeMatrix4s.length > 0 ) + ? this.threeMatrix4s.pop() + : new Matrix4(); + + } + + freeThreeMatrix4( m ) { + + this.threeMatrix4s.push( m ); + + } + + allocThreeQuaternion() { + + return ( this.threeQuaternions.length > 0 ) + ? this.threeQuaternions.pop() + : new Quaternion(); + + } + + freeThreeQuaternion( q ) { + + this.threeQuaternions.push( q ); + + } + + allocThreeEuler() { + + return ( this.threeEulers.length > 0 ) + ? this.threeEulers.pop() + : new Euler(); + + } + + freeThreeEuler( e ) { + + this.threeEulers.push( e ); + + } + + allocTransform() { + + return ( this.transforms.length > 0 ) + ? this.transforms.pop() + : new Ammo.btTransform(); + + } + + freeTransform( t ) { + + this.transforms.push( t ); + + } + + allocQuaternion() { + + return ( this.quaternions.length > 0 ) + ? this.quaternions.pop() + : new Ammo.btQuaternion(); + + } + + freeQuaternion( q ) { + + this.quaternions.push( q ); + + } + + allocVector3() { + + return ( this.vector3s.length > 0 ) + ? this.vector3s.pop() + : new Ammo.btVector3(); + + } + + freeVector3( v ) { + + this.vector3s.push( v ); + + } + + setIdentity( t ) { + + t.setIdentity(); + + } + + getBasis( t ) { + + var q = this.allocQuaternion(); + t.getBasis().getRotation( q ); + return q; + + } + + getBasisAsMatrix3( t ) { + + var q = this.getBasis( t ); + var m = this.quaternionToMatrix3( q ); + this.freeQuaternion( q ); + return m; + + } + + getOrigin( t ) { + + return t.getOrigin(); + + } + + setOrigin( t, v ) { + + t.getOrigin().setValue( v.x(), v.y(), v.z() ); + + } + + copyOrigin( t1, t2 ) { + + var o = t2.getOrigin(); + this.setOrigin( t1, o ); + + } + + setBasis( t, q ) { + + t.setRotation( q ); + + } + + setBasisFromMatrix3( t, m ) { + + var q = this.matrix3ToQuaternion( m ); + this.setBasis( t, q ); + this.freeQuaternion( q ); + + } + + setOriginFromArray3( t, a ) { + + t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] ); + + } + + setOriginFromThreeVector3( t, v ) { + + t.getOrigin().setValue( v.x, v.y, v.z ); + + } + + setBasisFromArray3( t, a ) { + + var thQ = this.allocThreeQuaternion(); + var thE = this.allocThreeEuler(); + thE.set( a[ 0 ], a[ 1 ], a[ 2 ] ); + this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) ); + + this.freeThreeEuler( thE ); + this.freeThreeQuaternion( thQ ); + + } + + setBasisFromThreeQuaternion( t, a ) { + + var q = this.allocQuaternion(); + + q.setX( a.x ); + q.setY( a.y ); + q.setZ( a.z ); + q.setW( a.w ); + this.setBasis( t, q ); + + this.freeQuaternion( q ); + + } + + multiplyTransforms( t1, t2 ) { + + var t = this.allocTransform(); + this.setIdentity( t ); + + var m1 = this.getBasisAsMatrix3( t1 ); + var m2 = this.getBasisAsMatrix3( t2 ); + + var o1 = this.getOrigin( t1 ); + var o2 = this.getOrigin( t2 ); + + var v1 = this.multiplyMatrix3ByVector3( m1, o2 ); + var v2 = this.addVector3( v1, o1 ); + this.setOrigin( t, v2 ); + + var m3 = this.multiplyMatrices3( m1, m2 ); + this.setBasisFromMatrix3( t, m3 ); + + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return t; + + } + + inverseTransform( t ) { + + var t2 = this.allocTransform(); + + var m1 = this.getBasisAsMatrix3( t ); + var o = this.getOrigin( t ); + + var m2 = this.transposeMatrix3( m1 ); + var v1 = this.negativeVector3( o ); + var v2 = this.multiplyMatrix3ByVector3( m2, v1 ); + + this.setOrigin( t2, v2 ); + this.setBasisFromMatrix3( t2, m2 ); + + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return t2; + + } + + multiplyMatrices3( m1, m2 ) { + + var m3 = []; + + var v10 = this.rowOfMatrix3( m1, 0 ); + var v11 = this.rowOfMatrix3( m1, 1 ); + var v12 = this.rowOfMatrix3( m1, 2 ); + + var v20 = this.columnOfMatrix3( m2, 0 ); + var v21 = this.columnOfMatrix3( m2, 1 ); + var v22 = this.columnOfMatrix3( m2, 2 ); + + m3[ 0 ] = this.dotVectors3( v10, v20 ); + m3[ 1 ] = this.dotVectors3( v10, v21 ); + m3[ 2 ] = this.dotVectors3( v10, v22 ); + m3[ 3 ] = this.dotVectors3( v11, v20 ); + m3[ 4 ] = this.dotVectors3( v11, v21 ); + m3[ 5 ] = this.dotVectors3( v11, v22 ); + m3[ 6 ] = this.dotVectors3( v12, v20 ); + m3[ 7 ] = this.dotVectors3( v12, v21 ); + m3[ 8 ] = this.dotVectors3( v12, v22 ); + + this.freeVector3( v10 ); + this.freeVector3( v11 ); + this.freeVector3( v12 ); + this.freeVector3( v20 ); + this.freeVector3( v21 ); + this.freeVector3( v22 ); + + return m3; + + } + + addVector3( v1, v2 ) { + + var v = this.allocVector3(); + v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() ); + return v; + + } + + dotVectors3( v1, v2 ) { + + return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); + + } + + rowOfMatrix3( m, i ) { + + var v = this.allocVector3(); + v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] ); + return v; + + } + + columnOfMatrix3( m, i ) { + + var v = this.allocVector3(); + v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] ); + return v; + + } + + negativeVector3( v ) { + + var v2 = this.allocVector3(); + v2.setValue( - v.x(), - v.y(), - v.z() ); + return v2; + + } + + multiplyMatrix3ByVector3( m, v ) { + + var v4 = this.allocVector3(); + + var v0 = this.rowOfMatrix3( m, 0 ); + var v1 = this.rowOfMatrix3( m, 1 ); + var v2 = this.rowOfMatrix3( m, 2 ); + var x = this.dotVectors3( v0, v ); + var y = this.dotVectors3( v1, v ); + var z = this.dotVectors3( v2, v ); + + v4.setValue( x, y, z ); + + this.freeVector3( v0 ); + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return v4; + + } + + transposeMatrix3( m ) { + + var m2 = []; + m2[ 0 ] = m[ 0 ]; + m2[ 1 ] = m[ 3 ]; + m2[ 2 ] = m[ 6 ]; + m2[ 3 ] = m[ 1 ]; + m2[ 4 ] = m[ 4 ]; + m2[ 5 ] = m[ 7 ]; + m2[ 6 ] = m[ 2 ]; + m2[ 7 ] = m[ 5 ]; + m2[ 8 ] = m[ 8 ]; + return m2; + + } + + quaternionToMatrix3( q ) { + + var m = []; + + var x = q.x(); + var y = q.y(); + var z = q.z(); + var w = q.w(); + + var xx = x * x; + var yy = y * y; + var zz = z * z; + + var xy = x * y; + var yz = y * z; + var zx = z * x; + + var xw = x * w; + var yw = y * w; + var zw = z * w; + + m[ 0 ] = 1 - 2 * ( yy + zz ); + m[ 1 ] = 2 * ( xy - zw ); + m[ 2 ] = 2 * ( zx + yw ); + m[ 3 ] = 2 * ( xy + zw ); + m[ 4 ] = 1 - 2 * ( zz + xx ); + m[ 5 ] = 2 * ( yz - xw ); + m[ 6 ] = 2 * ( zx - yw ); + m[ 7 ] = 2 * ( yz + xw ); + m[ 8 ] = 1 - 2 * ( xx + yy ); + + return m; + + } + + matrix3ToQuaternion( m ) { + + var t = m[ 0 ] + m[ 4 ] + m[ 8 ]; + var s, x, y, z, w; + + if ( t > 0 ) { + + s = Math.sqrt( t + 1.0 ) * 2; + w = 0.25 * s; + x = ( m[ 7 ] - m[ 5 ] ) / s; + y = ( m[ 2 ] - m[ 6 ] ) / s; + z = ( m[ 3 ] - m[ 1 ] ) / s; + + } else if ( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) { + + s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2; + w = ( m[ 7 ] - m[ 5 ] ) / s; + x = 0.25 * s; + y = ( m[ 1 ] + m[ 3 ] ) / s; + z = ( m[ 2 ] + m[ 6 ] ) / s; + + } else if ( m[ 4 ] > m[ 8 ] ) { + + s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2; + w = ( m[ 2 ] - m[ 6 ] ) / s; + x = ( m[ 1 ] + m[ 3 ] ) / s; + y = 0.25 * s; + z = ( m[ 5 ] + m[ 7 ] ) / s; + + } else { + + s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2; + w = ( m[ 3 ] - m[ 1 ] ) / s; + x = ( m[ 2 ] + m[ 6 ] ) / s; + y = ( m[ 5 ] + m[ 7 ] ) / s; + z = 0.25 * s; + + } + + var q = this.allocQuaternion(); + q.setX( x ); + q.setY( y ); + q.setZ( z ); + q.setW( w ); + return q; + + } + +} + +/** + * @param {THREE.SkinnedMesh} mesh + * @param {Ammo.btDiscreteDynamicsWorld} world + * @param {Object} params + * @param {ResourceManager} manager + */ +class RigidBody { + + constructor( mesh, world, params, manager ) { + + this.mesh = mesh; + this.world = world; + this.params = params; + this.manager = manager; + + this.body = null; + this.bone = null; + this.boneOffsetForm = null; + this.boneOffsetFormInverse = null; + + this._init(); + + } + + /** + * Resets rigid body transform to the current bone's. + * + * @return {RigidBody} + */ + reset() { + + this._setTransformFromBone(); + return this; + + } + + /** + * Updates rigid body's transform from the current bone. + * + * @return {RidigBody} + */ + updateFromBone() { + + if ( this.params.boneIndex !== - 1 && this.params.type === 0 ) { + + this._setTransformFromBone(); + + } + + return this; + + } + + /** + * Updates bone from the current ridid body's transform. + * + * @return {RidigBody} + */ + updateBone() { + + if ( this.params.type === 0 || this.params.boneIndex === - 1 ) { + + return this; + + } + + this._updateBoneRotation(); + + if ( this.params.type === 1 ) { + + this._updateBonePosition(); + + } + + this.bone.updateMatrixWorld( true ); + + if ( this.params.type === 2 ) { + + this._setPositionFromBone(); + + } + + return this; + + } + + // private methods + + _init() { + + function generateShape( p ) { + + switch ( p.shapeType ) { + + case 0: + return new Ammo.btSphereShape( p.width ); + + case 1: + return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) ); + + case 2: + return new Ammo.btCapsuleShape( p.width, p.height ); + + default: + throw new Error( 'unknown shape type ' + p.shapeType ); + + } + + } + + const manager = this.manager; + const params = this.params; + const bones = this.mesh.skeleton.bones; + const bone = ( params.boneIndex === - 1 ) + ? new Bone() + : bones[ params.boneIndex ]; + + const shape = generateShape( params ); + const weight = ( params.type === 0 ) ? 0 : params.weight; + const localInertia = manager.allocVector3(); + localInertia.setValue( 0, 0, 0 ); + + if ( weight !== 0 ) { + + shape.calculateLocalInertia( weight, localInertia ); + + } + + const boneOffsetForm = manager.allocTransform(); + manager.setIdentity( boneOffsetForm ); + manager.setOriginFromArray3( boneOffsetForm, params.position ); + manager.setBasisFromArray3( boneOffsetForm, params.rotation ); + + const vector = manager.allocThreeVector3(); + const boneForm = manager.allocTransform(); + manager.setIdentity( boneForm ); + manager.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) ); + + const form = manager.multiplyTransforms( boneForm, boneOffsetForm ); + const state = new Ammo.btDefaultMotionState( form ); + + const info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia ); + info.set_m_friction( params.friction ); + info.set_m_restitution( params.restitution ); + + const body = new Ammo.btRigidBody( info ); + + if ( params.type === 0 ) { + + body.setCollisionFlags( body.getCollisionFlags() | 2 ); + + /* + * It'd be better to comment out this line though in general I should call this method + * because I'm not sure why but physics will be more like MMD's + * if I comment out. + */ + body.setActivationState( 4 ); + + } + + body.setDamping( params.positionDamping, params.rotationDamping ); + body.setSleepingThresholds( 0, 0 ); + + this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget ); + + this.body = body; + this.bone = bone; + this.boneOffsetForm = boneOffsetForm; + this.boneOffsetFormInverse = manager.inverseTransform( boneOffsetForm ); + + manager.freeVector3( localInertia ); + manager.freeTransform( form ); + manager.freeTransform( boneForm ); + manager.freeThreeVector3( vector ); + + } + + _getBoneTransform() { + + const manager = this.manager; + const p = manager.allocThreeVector3(); + const q = manager.allocThreeQuaternion(); + const s = manager.allocThreeVector3(); + + this.bone.matrixWorld.decompose( p, q, s ); + + const tr = manager.allocTransform(); + manager.setOriginFromThreeVector3( tr, p ); + manager.setBasisFromThreeQuaternion( tr, q ); + + const form = manager.multiplyTransforms( tr, this.boneOffsetForm ); + + manager.freeTransform( tr ); + manager.freeThreeVector3( s ); + manager.freeThreeQuaternion( q ); + manager.freeThreeVector3( p ); + + return form; + + } + + _getWorldTransformForBone() { + + const manager = this.manager; + const tr = this.body.getCenterOfMassTransform(); + return manager.multiplyTransforms( tr, this.boneOffsetFormInverse ); + + } + + _setTransformFromBone() { + + const manager = this.manager; + const form = this._getBoneTransform(); + + // TODO: check the most appropriate way to set + //this.body.setWorldTransform( form ); + this.body.setCenterOfMassTransform( form ); + this.body.getMotionState().setWorldTransform( form ); + + manager.freeTransform( form ); + + } + + _setPositionFromBone() { + + const manager = this.manager; + const form = this._getBoneTransform(); + + const tr = manager.allocTransform(); + this.body.getMotionState().getWorldTransform( tr ); + manager.copyOrigin( tr, form ); + + // TODO: check the most appropriate way to set + //this.body.setWorldTransform( tr ); + this.body.setCenterOfMassTransform( tr ); + this.body.getMotionState().setWorldTransform( tr ); + + manager.freeTransform( tr ); + manager.freeTransform( form ); + + } + + _updateBoneRotation() { + + const manager = this.manager; + + const tr = this._getWorldTransformForBone(); + const q = manager.getBasis( tr ); + + const thQ = manager.allocThreeQuaternion(); + const thQ2 = manager.allocThreeQuaternion(); + const thQ3 = manager.allocThreeQuaternion(); + + thQ.set( q.x(), q.y(), q.z(), q.w() ); + thQ2.setFromRotationMatrix( this.bone.matrixWorld ); + thQ2.conjugate(); + thQ2.multiply( thQ ); + + //this.bone.quaternion.multiply( thQ2 ); + + thQ3.setFromRotationMatrix( this.bone.matrix ); + + // Renormalizing quaternion here because repeatedly transforming + // quaternion continuously accumulates floating point error and + // can end up being overflow. See #15335 + this.bone.quaternion.copy( thQ2.multiply( thQ3 ).normalize() ); + + manager.freeThreeQuaternion( thQ ); + manager.freeThreeQuaternion( thQ2 ); + manager.freeThreeQuaternion( thQ3 ); + + manager.freeQuaternion( q ); + manager.freeTransform( tr ); + + } + + _updateBonePosition() { + + const manager = this.manager; + + const tr = this._getWorldTransformForBone(); + + const thV = manager.allocThreeVector3(); + + const o = manager.getOrigin( tr ); + thV.set( o.x(), o.y(), o.z() ); + + if ( this.bone.parent ) { + + this.bone.parent.worldToLocal( thV ); + + } + + this.bone.position.copy( thV ); + + manager.freeThreeVector3( thV ); + + manager.freeTransform( tr ); + + } + +} + +// + +class Constraint { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Ammo.btDiscreteDynamicsWorld} world + * @param {RigidBody} bodyA + * @param {RigidBody} bodyB + * @param {Object} params + * @param {ResourceManager} manager + */ + constructor( mesh, world, bodyA, bodyB, params, manager ) { + + this.mesh = mesh; + this.world = world; + this.bodyA = bodyA; + this.bodyB = bodyB; + this.params = params; + this.manager = manager; + + this.constraint = null; + + this._init(); + + } + + // private method + + _init() { + + const manager = this.manager; + const params = this.params; + const bodyA = this.bodyA; + const bodyB = this.bodyB; + + const form = manager.allocTransform(); + manager.setIdentity( form ); + manager.setOriginFromArray3( form, params.position ); + manager.setBasisFromArray3( form, params.rotation ); + + const formA = manager.allocTransform(); + const formB = manager.allocTransform(); + + bodyA.body.getMotionState().getWorldTransform( formA ); + bodyB.body.getMotionState().getWorldTransform( formB ); + + const formInverseA = manager.inverseTransform( formA ); + const formInverseB = manager.inverseTransform( formB ); + + const formA2 = manager.multiplyTransforms( formInverseA, form ); + const formB2 = manager.multiplyTransforms( formInverseB, form ); + + const constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true ); + + const lll = manager.allocVector3(); + const lul = manager.allocVector3(); + const all = manager.allocVector3(); + const aul = manager.allocVector3(); + + lll.setValue( params.translationLimitation1[ 0 ], + params.translationLimitation1[ 1 ], + params.translationLimitation1[ 2 ] ); + lul.setValue( params.translationLimitation2[ 0 ], + params.translationLimitation2[ 1 ], + params.translationLimitation2[ 2 ] ); + all.setValue( params.rotationLimitation1[ 0 ], + params.rotationLimitation1[ 1 ], + params.rotationLimitation1[ 2 ] ); + aul.setValue( params.rotationLimitation2[ 0 ], + params.rotationLimitation2[ 1 ], + params.rotationLimitation2[ 2 ] ); + + constraint.setLinearLowerLimit( lll ); + constraint.setLinearUpperLimit( lul ); + constraint.setAngularLowerLimit( all ); + constraint.setAngularUpperLimit( aul ); + + for ( let i = 0; i < 3; i ++ ) { + + if ( params.springPosition[ i ] !== 0 ) { + + constraint.enableSpring( i, true ); + constraint.setStiffness( i, params.springPosition[ i ] ); + + } + + } + + for ( let i = 0; i < 3; i ++ ) { + + if ( params.springRotation[ i ] !== 0 ) { + + constraint.enableSpring( i + 3, true ); + constraint.setStiffness( i + 3, params.springRotation[ i ] ); + + } + + } + + /* + * Currently(10/31/2016) official ammo.js doesn't support + * btGeneric6DofSpringConstraint.setParam method. + * You need custom ammo.js (add the method into idl) if you wanna use. + * By setting this parameter, physics will be more like MMD's + */ + if ( constraint.setParam !== undefined ) { + + for ( let i = 0; i < 6; i ++ ) { + + constraint.setParam( 2, 0.475, i ); + + } + + } + + this.world.addConstraint( constraint, true ); + this.constraint = constraint; + + manager.freeTransform( form ); + manager.freeTransform( formA ); + manager.freeTransform( formB ); + manager.freeTransform( formInverseA ); + manager.freeTransform( formInverseB ); + manager.freeTransform( formA2 ); + manager.freeTransform( formB2 ); + manager.freeVector3( lll ); + manager.freeVector3( lul ); + manager.freeVector3( all ); + manager.freeVector3( aul ); + + } + +} + +// + +const _position = new Vector3(); +const _quaternion = new Quaternion(); +const _scale = new Vector3(); +const _matrixWorldInv = new Matrix4(); + +class MMDPhysicsHelper extends Object3D { + + /** + * Visualize Rigid bodies + * + * @param {THREE.SkinnedMesh} mesh + * @param {Physics} physics + */ + constructor( mesh, physics ) { + + super(); + + this.root = mesh; + this.physics = physics; + + this.matrix.copy( mesh.matrixWorld ); + this.matrixAutoUpdate = false; + + this.materials = []; + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0xff8888 ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0x88ff88 ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0x8888ff ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this._init(); + + } + + + /** + * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. + */ + dispose() { + + const materials = this.materials; + const children = this.children; + + for ( let i = 0; i < materials.length; i ++ ) { + + materials[ i ].dispose(); + + } + + for ( let i = 0; i < children.length; i ++ ) { + + const child = children[ i ]; + + if ( child.isMesh ) child.geometry.dispose(); + + } + + } + + /** + * Updates Rigid Bodies visualization. + */ + updateMatrixWorld( force ) { + + var mesh = this.root; + + if ( this.visible ) { + + var bodies = this.physics.bodies; + + _matrixWorldInv + .copy( mesh.matrixWorld ) + .decompose( _position, _quaternion, _scale ) + .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) ) + .invert(); + + for ( var i = 0, il = bodies.length; i < il; i ++ ) { + + var body = bodies[ i ].body; + var child = this.children[ i ]; + + var tr = body.getCenterOfMassTransform(); + var origin = tr.getOrigin(); + var rotation = tr.getRotation(); + + child.position + .set( origin.x(), origin.y(), origin.z() ) + .applyMatrix4( _matrixWorldInv ); + + child.quaternion + .setFromRotationMatrix( _matrixWorldInv ) + .multiply( + _quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() ) + ); + + } + + } + + this.matrix + .copy( mesh.matrixWorld ) + .decompose( _position, _quaternion, _scale ) + .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) ); + + super.updateMatrixWorld( force ); + + } + + // private method + + _init() { + + var bodies = this.physics.bodies; + + function createGeometry( param ) { + + switch ( param.shapeType ) { + + case 0: + return new SphereGeometry( param.width, 16, 8 ); + + case 1: + return new BoxGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 ); + + case 2: + return new CapsuleGeometry( param.width, param.height, 8, 16 ); + + default: + return null; + + } + + } + + for ( var i = 0, il = bodies.length; i < il; i ++ ) { + + var param = bodies[ i ].params; + this.add( new Mesh( createGeometry( param ), this.materials[ param.type ] ) ); + + } + + } + +} + +export { MMDPhysics }; diff --git a/renderer/jsm/cameras/CinematicCamera.js b/renderer/jsm/cameras/CinematicCamera.js new file mode 100644 index 0000000..47b94e7 --- /dev/null +++ b/renderer/jsm/cameras/CinematicCamera.js @@ -0,0 +1,209 @@ +import { + Mesh, + OrthographicCamera, + PerspectiveCamera, + PlaneGeometry, + Scene, + ShaderMaterial, + UniformsUtils, + WebGLRenderTarget +} from 'three'; + +import { BokehShader } from '../shaders/BokehShader2.js'; +import { BokehDepthShader } from '../shaders/BokehShader2.js'; + +class CinematicCamera extends PerspectiveCamera { + + constructor( fov, aspect, near, far ) { + + super( fov, aspect, near, far ); + + this.type = 'CinematicCamera'; + + this.postprocessing = { enabled: true }; + this.shaderSettings = { + rings: 3, + samples: 4 + }; + + const depthShader = BokehDepthShader; + + this.materialDepth = new ShaderMaterial( { + uniforms: depthShader.uniforms, + vertexShader: depthShader.vertexShader, + fragmentShader: depthShader.fragmentShader + } ); + + this.materialDepth.uniforms[ 'mNear' ].value = near; + this.materialDepth.uniforms[ 'mFar' ].value = far; + + // In case of cinematicCamera, having a default lens set is important + this.setLens(); + + this.initPostProcessing(); + + } + + // providing fnumber and coc(Circle of Confusion) as extra arguments + // In case of cinematicCamera, having a default lens set is important + // if fnumber and coc are not provided, cinematicCamera tries to act as a basic PerspectiveCamera + setLens( focalLength = 35, filmGauge = 35, fNumber = 8, coc = 0.019 ) { + + this.filmGauge = filmGauge; + + this.setFocalLength( focalLength ); + + this.fNumber = fNumber; + this.coc = coc; + + // fNumber is focalLength by aperture + this.aperture = focalLength / this.fNumber; + + // hyperFocal is required to calculate depthOfField when a lens tries to focus at a distance with given fNumber and focalLength + this.hyperFocal = ( focalLength * focalLength ) / ( this.aperture * this.coc ); + + } + + linearize( depth ) { + + const zfar = this.far; + const znear = this.near; + return - zfar * znear / ( depth * ( zfar - znear ) - zfar ); + + } + + smoothstep( near, far, depth ) { + + const x = this.saturate( ( depth - near ) / ( far - near ) ); + return x * x * ( 3 - 2 * x ); + + } + + saturate( x ) { + + return Math.max( 0, Math.min( 1, x ) ); + + } + + // function for focusing at a distance from the camera + focusAt( focusDistance = 20 ) { + + const focalLength = this.getFocalLength(); + + // distance from the camera (normal to frustrum) to focus on + this.focus = focusDistance; + + // the nearest point from the camera which is in focus (unused) + this.nearPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal + ( this.focus - focalLength ) ); + + // the farthest point from the camera which is in focus (unused) + this.farPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal - ( this.focus - focalLength ) ); + + // the gap or width of the space in which is everything is in focus (unused) + this.depthOfField = this.farPoint - this.nearPoint; + + // Considering minimum distance of focus for a standard lens (unused) + if ( this.depthOfField < 0 ) this.depthOfField = 0; + + this.sdistance = this.smoothstep( this.near, this.far, this.focus ); + + this.ldistance = this.linearize( 1 - this.sdistance ); + + this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = this.ldistance; + + } + + initPostProcessing() { + + if ( this.postprocessing.enabled ) { + + this.postprocessing.scene = new Scene(); + + this.postprocessing.camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 ); + + this.postprocessing.scene.add( this.postprocessing.camera ); + + this.postprocessing.rtTextureDepth = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); + this.postprocessing.rtTextureColor = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); + + const bokeh_shader = BokehShader; + + this.postprocessing.bokeh_uniforms = UniformsUtils.clone( bokeh_shader.uniforms ); + + this.postprocessing.bokeh_uniforms[ 'tColor' ].value = this.postprocessing.rtTextureColor.texture; + this.postprocessing.bokeh_uniforms[ 'tDepth' ].value = this.postprocessing.rtTextureDepth.texture; + + this.postprocessing.bokeh_uniforms[ 'manualdof' ].value = 0; + this.postprocessing.bokeh_uniforms[ 'shaderFocus' ].value = 0; + + this.postprocessing.bokeh_uniforms[ 'fstop' ].value = 2.8; + + this.postprocessing.bokeh_uniforms[ 'showFocus' ].value = 1; + + this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = 0.1; + + //console.log( this.postprocessing.bokeh_uniforms[ "focalDepth" ].value ); + + this.postprocessing.bokeh_uniforms[ 'znear' ].value = this.near; + this.postprocessing.bokeh_uniforms[ 'zfar' ].value = this.near; + + + this.postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth; + + this.postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight; + + this.postprocessing.materialBokeh = new ShaderMaterial( { + uniforms: this.postprocessing.bokeh_uniforms, + vertexShader: bokeh_shader.vertexShader, + fragmentShader: bokeh_shader.fragmentShader, + defines: { + RINGS: this.shaderSettings.rings, + SAMPLES: this.shaderSettings.samples, + DEPTH_PACKING: 1 + } + } ); + + this.postprocessing.quad = new Mesh( new PlaneGeometry( window.innerWidth, window.innerHeight ), this.postprocessing.materialBokeh ); + this.postprocessing.quad.position.z = - 500; + this.postprocessing.scene.add( this.postprocessing.quad ); + + } + + } + + renderCinematic( scene, renderer ) { + + if ( this.postprocessing.enabled ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + renderer.clear(); + + // Render scene into texture + + scene.overrideMaterial = null; + renderer.setRenderTarget( this.postprocessing.rtTextureColor ); + renderer.clear(); + renderer.render( scene, this ); + + // Render depth into texture + + scene.overrideMaterial = this.materialDepth; + renderer.setRenderTarget( this.postprocessing.rtTextureDepth ); + renderer.clear(); + renderer.render( scene, this ); + + // Render bokeh composite + + renderer.setRenderTarget( null ); + renderer.render( this.postprocessing.scene, this.postprocessing.camera ); + + renderer.setRenderTarget( currentRenderTarget ); + + } + + } + +} + +export { CinematicCamera }; diff --git a/renderer/jsm/capabilities/WebGL.js b/renderer/jsm/capabilities/WebGL.js new file mode 100644 index 0000000..08666fe --- /dev/null +++ b/renderer/jsm/capabilities/WebGL.js @@ -0,0 +1,91 @@ +class WebGL { + + static isWebGLAvailable() { + + try { + + const canvas = document.createElement( 'canvas' ); + return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) ); + + } catch ( e ) { + + return false; + + } + + } + + static isWebGL2Available() { + + try { + + const canvas = document.createElement( 'canvas' ); + return !! ( window.WebGL2RenderingContext && canvas.getContext( 'webgl2' ) ); + + } catch ( e ) { + + return false; + + } + + } + + static getWebGLErrorMessage() { + + return this.getErrorMessage( 1 ); + + } + + static getWebGL2ErrorMessage() { + + return this.getErrorMessage( 2 ); + + } + + static getErrorMessage( version ) { + + const names = { + 1: 'WebGL', + 2: 'WebGL 2' + }; + + const contexts = { + 1: window.WebGLRenderingContext, + 2: window.WebGL2RenderingContext + }; + + let message = 'Your $0 does not seem to support $1'; + + const element = document.createElement( 'div' ); + element.id = 'webglmessage'; + element.style.fontFamily = 'monospace'; + element.style.fontSize = '13px'; + element.style.fontWeight = 'normal'; + element.style.textAlign = 'center'; + element.style.background = '#fff'; + element.style.color = '#000'; + element.style.padding = '1.5em'; + element.style.width = '400px'; + element.style.margin = '5em auto 0'; + + if ( contexts[ version ] ) { + + message = message.replace( '$0', 'graphics card' ); + + } else { + + message = message.replace( '$0', 'browser' ); + + } + + message = message.replace( '$1', names[ version ] ); + + element.innerHTML = message; + + return element; + + } + +} + +export default WebGL; diff --git a/renderer/jsm/capabilities/WebGPU.js b/renderer/jsm/capabilities/WebGPU.js new file mode 100644 index 0000000..8b1c8c1 --- /dev/null +++ b/renderer/jsm/capabilities/WebGPU.js @@ -0,0 +1,41 @@ +if ( window.GPUShaderStage === undefined ) { + + window.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 }; + +} + +class WebGPU { + + static isAvailable() { + + return ( navigator.gpu !== undefined ); + + } + + static getErrorMessage() { + + let message = 'Your browser does not support WebGPU'; + + if ( !! window.chrome ) message += '
Try: chrome://flags/#enable-unsafe-webgpu'; + + const element = document.createElement( 'div' ); + element.id = 'webgpumessage'; + element.style.fontFamily = 'monospace'; + element.style.fontSize = '13px'; + element.style.fontWeight = 'normal'; + element.style.textAlign = 'center'; + element.style.background = '#fff'; + element.style.color = '#000'; + element.style.padding = '1.5em'; + element.style.width = '400px'; + element.style.margin = '5em auto 0'; + + element.innerHTML = message; + + return element; + + } + +} + +export default WebGPU; diff --git a/renderer/jsm/controls/ArcballControls.js b/renderer/jsm/controls/ArcballControls.js new file mode 100644 index 0000000..ac56b8a --- /dev/null +++ b/renderer/jsm/controls/ArcballControls.js @@ -0,0 +1,3223 @@ +import { + GridHelper, + EllipseCurve, + BufferGeometry, + Line, + LineBasicMaterial, + Raycaster, + Group, + Box3, + Sphere, + Quaternion, + Vector2, + Vector3, + Matrix4, + MathUtils, + EventDispatcher +} from 'three'; + +//trackball state +const STATE = { + + IDLE: Symbol(), + ROTATE: Symbol(), + PAN: Symbol(), + SCALE: Symbol(), + FOV: Symbol(), + FOCUS: Symbol(), + ZROTATE: Symbol(), + TOUCH_MULTI: Symbol(), + ANIMATION_FOCUS: Symbol(), + ANIMATION_ROTATE: Symbol() + +}; + +const INPUT = { + + NONE: Symbol(), + ONE_FINGER: Symbol(), + ONE_FINGER_SWITCHED: Symbol(), + TWO_FINGER: Symbol(), + MULT_FINGER: Symbol(), + CURSOR: Symbol() + +}; + +//cursor center coordinates +const _center = { + + x: 0, + y: 0 + +}; + +//transformation matrices for gizmos and camera +const _transformation = { + + camera: new Matrix4(), + gizmos: new Matrix4() + +}; + +//events +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; + +const _raycaster = new Raycaster(); +const _offset = new Vector3(); + +const _gizmoMatrixStateTemp = new Matrix4(); +const _cameraMatrixStateTemp = new Matrix4(); +const _scalePointTemp = new Vector3(); +/** + * + * @param {Camera} camera Virtual camera used in the scene + * @param {HTMLElement} domElement Renderer's dom element + * @param {Scene} scene The scene to be rendered + */ +class ArcballControls extends EventDispatcher { + + constructor( camera, domElement, scene = null ) { + + super(); + this.camera = null; + this.domElement = domElement; + this.scene = scene; + this.target = new Vector3(); + this._currentTarget = new Vector3(); + this.radiusFactor = 0.67; + + this.mouseActions = []; + this._mouseOp = null; + + + //global vectors and matrices that are used in some operations to avoid creating new objects every time (e.g. every time cursor moves) + this._v2_1 = new Vector2(); + this._v3_1 = new Vector3(); + this._v3_2 = new Vector3(); + + this._m4_1 = new Matrix4(); + this._m4_2 = new Matrix4(); + + this._quat = new Quaternion(); + + //transformation matrices + this._translationMatrix = new Matrix4(); //matrix for translation operation + this._rotationMatrix = new Matrix4(); //matrix for rotation operation + this._scaleMatrix = new Matrix4(); //matrix for scaling operation + + this._rotationAxis = new Vector3(); //axis for rotate operation + + + //camera state + this._cameraMatrixState = new Matrix4(); + this._cameraProjectionState = new Matrix4(); + + this._fovState = 1; + this._upState = new Vector3(); + this._zoomState = 1; + this._nearPos = 0; + this._farPos = 0; + + this._gizmoMatrixState = new Matrix4(); + + //initial values + this._up0 = new Vector3(); + this._zoom0 = 1; + this._fov0 = 0; + this._initialNear = 0; + this._nearPos0 = 0; + this._initialFar = 0; + this._farPos0 = 0; + this._cameraMatrixState0 = new Matrix4(); + this._gizmoMatrixState0 = new Matrix4(); + + //pointers array + this._button = - 1; + this._touchStart = []; + this._touchCurrent = []; + this._input = INPUT.NONE; + + //two fingers touch interaction + this._switchSensibility = 32; //minimum movement to be performed to fire single pan start after the second finger has been released + this._startFingerDistance = 0; //distance between two fingers + this._currentFingerDistance = 0; + this._startFingerRotation = 0; //amount of rotation performed with two fingers + this._currentFingerRotation = 0; + + //double tap + this._devPxRatio = 0; + this._downValid = true; + this._nclicks = 0; + this._downEvents = []; + this._downStart = 0; //pointerDown time + this._clickStart = 0; //first click time + this._maxDownTime = 250; + this._maxInterval = 300; + this._posThreshold = 24; + this._movementThreshold = 24; + + //cursor positions + this._currentCursorPosition = new Vector3(); + this._startCursorPosition = new Vector3(); + + //grid + this._grid = null; //grid to be visualized during pan operation + this._gridPosition = new Vector3(); + + //gizmos + this._gizmos = new Group(); + this._curvePts = 128; + + + //animations + this._timeStart = - 1; //initial time + this._animationId = - 1; + + //focus animation + this.focusAnimationTime = 500; //duration of focus animation in ms + + //rotate animation + this._timePrev = 0; //time at which previous rotate operation has been detected + this._timeCurrent = 0; //time at which current rotate operation has been detected + this._anglePrev = 0; //angle of previous rotation + this._angleCurrent = 0; //angle of current rotation + this._cursorPosPrev = new Vector3(); //cursor position when previous rotate operation has been detected + this._cursorPosCurr = new Vector3();//cursor position when current rotate operation has been detected + this._wPrev = 0; //angular velocity of the previous rotate operation + this._wCurr = 0; //angular velocity of the current rotate operation + + + //parameters + this.adjustNearFar = false; + this.scaleFactor = 1.1; //zoom/distance multiplier + this.dampingFactor = 25; + this.wMax = 20; //maximum angular velocity allowed + this.enableAnimations = true; //if animations should be performed + this.enableGrid = false; //if grid should be showed during pan operation + this.cursorZoom = false; //if wheel zoom should be cursor centered + this.minFov = 5; + this.maxFov = 90; + + this.enabled = true; + this.enablePan = true; + this.enableRotate = true; + this.enableZoom = true; + this.enableGizmos = true; + + this.minDistance = 0; + this.maxDistance = Infinity; + this.minZoom = 0; + this.maxZoom = Infinity; + + //trackball parameters + this._tbRadius = 1; + + //FSA + this._state = STATE.IDLE; + + this.setCamera( camera ); + + if ( this.scene != null ) { + + this.scene.add( this._gizmos ); + + } + + this.domElement.style.touchAction = 'none'; + this._devPxRatio = window.devicePixelRatio; + + this.initializeMouseActions(); + + this._onContextMenu = onContextMenu.bind( this ); + this._onWheel = onWheel.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerCancel = onPointerCancel.bind( this ); + this._onWindowResize = onWindowResize.bind( this ); + + this.domElement.addEventListener( 'contextmenu', this._onContextMenu ); + this.domElement.addEventListener( 'wheel', this._onWheel ); + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointercancel', this._onPointerCancel ); + + window.addEventListener( 'resize', this._onWindowResize ); + + } + + onSinglePanStart( event, operation ) { + + if ( this.enabled ) { + + this.dispatchEvent( _startEvent ); + + this.setCenter( event.clientX, event.clientY ); + + switch ( operation ) { + + case 'PAN': + + if ( ! this.enablePan ) { + + return; + + } + + if ( this._animationId != - 1 ) { + + cancelAnimationFrame( this._animationId ); + this._animationId = - 1; + this._timeStart = - 1; + + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + this.updateTbState( STATE.PAN, true ); + this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) ); + if ( this.enableGrid ) { + + this.drawGrid(); + this.dispatchEvent( _changeEvent ); + + } + + break; + + case 'ROTATE': + + if ( ! this.enableRotate ) { + + return; + + } + + if ( this._animationId != - 1 ) { + + cancelAnimationFrame( this._animationId ); + this._animationId = - 1; + this._timeStart = - 1; + + } + + this.updateTbState( STATE.ROTATE, true ); + this._startCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) ); + this.activateGizmos( true ); + if ( this.enableAnimations ) { + + this._timePrev = this._timeCurrent = performance.now(); + this._angleCurrent = this._anglePrev = 0; + this._cursorPosPrev.copy( this._startCursorPosition ); + this._cursorPosCurr.copy( this._cursorPosPrev ); + this._wCurr = 0; + this._wPrev = this._wCurr; + + } + + this.dispatchEvent( _changeEvent ); + break; + + case 'FOV': + + if ( ! this.camera.isPerspectiveCamera || ! this.enableZoom ) { + + return; + + } + + if ( this._animationId != - 1 ) { + + cancelAnimationFrame( this._animationId ); + this._animationId = - 1; + this._timeStart = - 1; + + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + this.updateTbState( STATE.FOV, true ); + this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + this._currentCursorPosition.copy( this._startCursorPosition ); + break; + + case 'ZOOM': + + if ( ! this.enableZoom ) { + + return; + + } + + if ( this._animationId != - 1 ) { + + cancelAnimationFrame( this._animationId ); + this._animationId = - 1; + this._timeStart = - 1; + + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + this.updateTbState( STATE.SCALE, true ); + this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + this._currentCursorPosition.copy( this._startCursorPosition ); + break; + + } + + } + + } + + onSinglePanMove( event, opState ) { + + if ( this.enabled ) { + + const restart = opState != this._state; + this.setCenter( event.clientX, event.clientY ); + + switch ( opState ) { + + case STATE.PAN: + + if ( this.enablePan ) { + + if ( restart ) { + + //switch to pan operation + + this.dispatchEvent( _endEvent ); + this.dispatchEvent( _startEvent ); + + this.updateTbState( opState, true ); + this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) ); + if ( this.enableGrid ) { + + this.drawGrid(); + + } + + this.activateGizmos( false ); + + } else { + + //continue with pan operation + this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) ); + this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition ) ); + + } + + } + + break; + + case STATE.ROTATE: + + if ( this.enableRotate ) { + + if ( restart ) { + + //switch to rotate operation + + this.dispatchEvent( _endEvent ); + this.dispatchEvent( _startEvent ); + + this.updateTbState( opState, true ); + this._startCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) ); + + if ( this.enableGrid ) { + + this.disposeGrid(); + + } + + this.activateGizmos( true ); + + } else { + + //continue with rotate operation + this._currentCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) ); + + const distance = this._startCursorPosition.distanceTo( this._currentCursorPosition ); + const angle = this._startCursorPosition.angleTo( this._currentCursorPosition ); + const amount = Math.max( distance / this._tbRadius, angle ); //effective rotation angle + + this.applyTransformMatrix( this.rotate( this.calculateRotationAxis( this._startCursorPosition, this._currentCursorPosition ), amount ) ); + + if ( this.enableAnimations ) { + + this._timePrev = this._timeCurrent; + this._timeCurrent = performance.now(); + this._anglePrev = this._angleCurrent; + this._angleCurrent = amount; + this._cursorPosPrev.copy( this._cursorPosCurr ); + this._cursorPosCurr.copy( this._currentCursorPosition ); + this._wPrev = this._wCurr; + this._wCurr = this.calculateAngularSpeed( this._anglePrev, this._angleCurrent, this._timePrev, this._timeCurrent ); + + } + + } + + } + + break; + + case STATE.SCALE: + + if ( this.enableZoom ) { + + if ( restart ) { + + //switch to zoom operation + + this.dispatchEvent( _endEvent ); + this.dispatchEvent( _startEvent ); + + this.updateTbState( opState, true ); + this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + this._currentCursorPosition.copy( this._startCursorPosition ); + + if ( this.enableGrid ) { + + this.disposeGrid(); + + } + + this.activateGizmos( false ); + + } else { + + //continue with zoom operation + const screenNotches = 8; //how many wheel notches corresponds to a full screen pan + this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + + const movement = this._currentCursorPosition.y - this._startCursorPosition.y; + + let size = 1; + + if ( movement < 0 ) { + + size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) ); + + } else if ( movement > 0 ) { + + size = Math.pow( this.scaleFactor, movement * screenNotches ); + + } + + this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ); + + this.applyTransformMatrix( this.scale( size, this._v3_1 ) ); + + } + + } + + break; + + case STATE.FOV: + + if ( this.enableZoom && this.camera.isPerspectiveCamera ) { + + if ( restart ) { + + //switch to fov operation + + this.dispatchEvent( _endEvent ); + this.dispatchEvent( _startEvent ); + + this.updateTbState( opState, true ); + this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + this._currentCursorPosition.copy( this._startCursorPosition ); + + if ( this.enableGrid ) { + + this.disposeGrid(); + + } + + this.activateGizmos( false ); + + } else { + + //continue with fov operation + const screenNotches = 8; //how many wheel notches corresponds to a full screen pan + this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + + const movement = this._currentCursorPosition.y - this._startCursorPosition.y; + + let size = 1; + + if ( movement < 0 ) { + + size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) ); + + } else if ( movement > 0 ) { + + size = Math.pow( this.scaleFactor, movement * screenNotches ); + + } + + this._v3_1.setFromMatrixPosition( this._cameraMatrixState ); + const x = this._v3_1.distanceTo( this._gizmos.position ); + let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed + + //check min and max distance + xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance ); + + const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 ); + + //calculate new fov + let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 ); + + //check min and max fov + newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov ); + + const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) ); + size = x / newDistance; + this._v3_2.setFromMatrixPosition( this._gizmoMatrixState ); + + this.setFov( newFov ); + this.applyTransformMatrix( this.scale( size, this._v3_2, false ) ); + + //adjusting distance + _offset.copy( this._gizmos.position ).sub( this.camera.position ).normalize().multiplyScalar( newDistance / x ); + this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z ); + + } + + } + + break; + + } + + this.dispatchEvent( _changeEvent ); + + } + + } + + onSinglePanEnd() { + + if ( this._state == STATE.ROTATE ) { + + + if ( ! this.enableRotate ) { + + return; + + } + + if ( this.enableAnimations ) { + + //perform rotation animation + const deltaTime = ( performance.now() - this._timeCurrent ); + if ( deltaTime < 120 ) { + + const w = Math.abs( ( this._wPrev + this._wCurr ) / 2 ); + + const self = this; + this._animationId = window.requestAnimationFrame( function ( t ) { + + self.updateTbState( STATE.ANIMATION_ROTATE, true ); + const rotationAxis = self.calculateRotationAxis( self._cursorPosPrev, self._cursorPosCurr ); + + self.onRotationAnim( t, rotationAxis, Math.min( w, self.wMax ) ); + + } ); + + } else { + + //cursor has been standing still for over 120 ms since last movement + this.updateTbState( STATE.IDLE, false ); + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + } else { + + this.updateTbState( STATE.IDLE, false ); + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + } else if ( this._state == STATE.PAN || this._state == STATE.IDLE ) { + + this.updateTbState( STATE.IDLE, false ); + + if ( this.enableGrid ) { + + this.disposeGrid(); + + } + + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + + } + + this.dispatchEvent( _endEvent ); + + } + + onDoubleTap( event ) { + + if ( this.enabled && this.enablePan && this.scene != null ) { + + this.dispatchEvent( _startEvent ); + + this.setCenter( event.clientX, event.clientY ); + const hitP = this.unprojectOnObj( this.getCursorNDC( _center.x, _center.y, this.domElement ), this.camera ); + + if ( hitP != null && this.enableAnimations ) { + + const self = this; + if ( this._animationId != - 1 ) { + + window.cancelAnimationFrame( this._animationId ); + + } + + this._timeStart = - 1; + this._animationId = window.requestAnimationFrame( function ( t ) { + + self.updateTbState( STATE.ANIMATION_FOCUS, true ); + self.onFocusAnim( t, hitP, self._cameraMatrixState, self._gizmoMatrixState ); + + } ); + + } else if ( hitP != null && ! this.enableAnimations ) { + + this.updateTbState( STATE.FOCUS, true ); + this.focus( hitP, this.scaleFactor ); + this.updateTbState( STATE.IDLE, false ); + this.dispatchEvent( _changeEvent ); + + } + + } + + this.dispatchEvent( _endEvent ); + + } + + onDoublePanStart() { + + if ( this.enabled && this.enablePan ) { + + this.dispatchEvent( _startEvent ); + + this.updateTbState( STATE.PAN, true ); + + this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 ); + this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement, true ) ); + this._currentCursorPosition.copy( this._startCursorPosition ); + + this.activateGizmos( false ); + + } + + } + + onDoublePanMove() { + + if ( this.enabled && this.enablePan ) { + + this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 ); + + if ( this._state != STATE.PAN ) { + + this.updateTbState( STATE.PAN, true ); + this._startCursorPosition.copy( this._currentCursorPosition ); + + } + + this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement, true ) ); + this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition, true ) ); + this.dispatchEvent( _changeEvent ); + + } + + } + + onDoublePanEnd() { + + this.updateTbState( STATE.IDLE, false ); + this.dispatchEvent( _endEvent ); + + } + + onRotateStart() { + + if ( this.enabled && this.enableRotate ) { + + this.dispatchEvent( _startEvent ); + + this.updateTbState( STATE.ZROTATE, true ); + + //this._startFingerRotation = event.rotation; + + this._startFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] ); + this._currentFingerRotation = this._startFingerRotation; + + this.camera.getWorldDirection( this._rotationAxis ); //rotation axis + + if ( ! this.enablePan && ! this.enableZoom ) { + + this.activateGizmos( true ); + + } + + } + + } + + onRotateMove() { + + if ( this.enabled && this.enableRotate ) { + + this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 ); + let rotationPoint; + + if ( this._state != STATE.ZROTATE ) { + + this.updateTbState( STATE.ZROTATE, true ); + this._startFingerRotation = this._currentFingerRotation; + + } + + //this._currentFingerRotation = event.rotation; + this._currentFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] ); + + if ( ! this.enablePan ) { + + rotationPoint = new Vector3().setFromMatrixPosition( this._gizmoMatrixState ); + + } else { + + this._v3_2.setFromMatrixPosition( this._gizmoMatrixState ); + rotationPoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ).applyQuaternion( this.camera.quaternion ).multiplyScalar( 1 / this.camera.zoom ).add( this._v3_2 ); + + } + + const amount = MathUtils.DEG2RAD * ( this._startFingerRotation - this._currentFingerRotation ); + + this.applyTransformMatrix( this.zRotate( rotationPoint, amount ) ); + this.dispatchEvent( _changeEvent ); + + } + + } + + onRotateEnd() { + + this.updateTbState( STATE.IDLE, false ); + this.activateGizmos( false ); + this.dispatchEvent( _endEvent ); + + } + + onPinchStart() { + + if ( this.enabled && this.enableZoom ) { + + this.dispatchEvent( _startEvent ); + this.updateTbState( STATE.SCALE, true ); + + this._startFingerDistance = this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] ); + this._currentFingerDistance = this._startFingerDistance; + + this.activateGizmos( false ); + + } + + } + + onPinchMove() { + + if ( this.enabled && this.enableZoom ) { + + this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 ); + const minDistance = 12; //minimum distance between fingers (in css pixels) + + if ( this._state != STATE.SCALE ) { + + this._startFingerDistance = this._currentFingerDistance; + this.updateTbState( STATE.SCALE, true ); + + } + + this._currentFingerDistance = Math.max( this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] ), minDistance * this._devPxRatio ); + const amount = this._currentFingerDistance / this._startFingerDistance; + + let scalePoint; + + if ( ! this.enablePan ) { + + scalePoint = this._gizmos.position; + + } else { + + if ( this.camera.isOrthographicCamera ) { + + scalePoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) + .applyQuaternion( this.camera.quaternion ) + .multiplyScalar( 1 / this.camera.zoom ) + .add( this._gizmos.position ); + + } else if ( this.camera.isPerspectiveCamera ) { + + scalePoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) + .applyQuaternion( this.camera.quaternion ) + .add( this._gizmos.position ); + + } + + } + + this.applyTransformMatrix( this.scale( amount, scalePoint ) ); + this.dispatchEvent( _changeEvent ); + + } + + } + + onPinchEnd() { + + this.updateTbState( STATE.IDLE, false ); + this.dispatchEvent( _endEvent ); + + } + + onTriplePanStart() { + + if ( this.enabled && this.enableZoom ) { + + this.dispatchEvent( _startEvent ); + + this.updateTbState( STATE.SCALE, true ); + + //const center = event.center; + let clientX = 0; + let clientY = 0; + const nFingers = this._touchCurrent.length; + + for ( let i = 0; i < nFingers; i ++ ) { + + clientX += this._touchCurrent[ i ].clientX; + clientY += this._touchCurrent[ i ].clientY; + + } + + this.setCenter( clientX / nFingers, clientY / nFingers ); + + this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + this._currentCursorPosition.copy( this._startCursorPosition ); + + } + + } + + onTriplePanMove() { + + if ( this.enabled && this.enableZoom ) { + + // fov / 2 + // |\ + // | \ + // | \ + // x | \ + // | \ + // | \ + // | _ _ _\ + // y + + //const center = event.center; + let clientX = 0; + let clientY = 0; + const nFingers = this._touchCurrent.length; + + for ( let i = 0; i < nFingers; i ++ ) { + + clientX += this._touchCurrent[ i ].clientX; + clientY += this._touchCurrent[ i ].clientY; + + } + + this.setCenter( clientX / nFingers, clientY / nFingers ); + + const screenNotches = 8; //how many wheel notches corresponds to a full screen pan + this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 ); + + const movement = this._currentCursorPosition.y - this._startCursorPosition.y; + + let size = 1; + + if ( movement < 0 ) { + + size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) ); + + } else if ( movement > 0 ) { + + size = Math.pow( this.scaleFactor, movement * screenNotches ); + + } + + this._v3_1.setFromMatrixPosition( this._cameraMatrixState ); + const x = this._v3_1.distanceTo( this._gizmos.position ); + let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed + + //check min and max distance + xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance ); + + const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 ); + + //calculate new fov + let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 ); + + //check min and max fov + newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov ); + + const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) ); + size = x / newDistance; + this._v3_2.setFromMatrixPosition( this._gizmoMatrixState ); + + this.setFov( newFov ); + this.applyTransformMatrix( this.scale( size, this._v3_2, false ) ); + + //adjusting distance + _offset.copy( this._gizmos.position ).sub( this.camera.position ).normalize().multiplyScalar( newDistance / x ); + this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z ); + + this.dispatchEvent( _changeEvent ); + + } + + } + + onTriplePanEnd() { + + this.updateTbState( STATE.IDLE, false ); + this.dispatchEvent( _endEvent ); + //this.dispatchEvent( _changeEvent ); + + } + + /** + * Set _center's x/y coordinates + * @param {Number} clientX + * @param {Number} clientY + */ + setCenter( clientX, clientY ) { + + _center.x = clientX; + _center.y = clientY; + + } + + /** + * Set default mouse actions + */ + initializeMouseActions() { + + this.setMouseAction( 'PAN', 0, 'CTRL' ); + this.setMouseAction( 'PAN', 2 ); + + this.setMouseAction( 'ROTATE', 0 ); + + this.setMouseAction( 'ZOOM', 'WHEEL' ); + this.setMouseAction( 'ZOOM', 1 ); + + this.setMouseAction( 'FOV', 'WHEEL', 'SHIFT' ); + this.setMouseAction( 'FOV', 1, 'SHIFT' ); + + + } + + /** + * Compare two mouse actions + * @param {Object} action1 + * @param {Object} action2 + * @returns {Boolean} True if action1 and action 2 are the same mouse action, false otherwise + */ + compareMouseAction( action1, action2 ) { + + if ( action1.operation == action2.operation ) { + + if ( action1.mouse == action2.mouse && action1.key == action2.key ) { + + return true; + + } else { + + return false; + + } + + } else { + + return false; + + } + + } + + /** + * Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one + * @param {String} operation The operation to be performed ('PAN', 'ROTATE', 'ZOOM', 'FOV) + * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches + * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed + * @returns {Boolean} True if the mouse action has been successfully added, false otherwise + */ + setMouseAction( operation, mouse, key = null ) { + + const operationInput = [ 'PAN', 'ROTATE', 'ZOOM', 'FOV' ]; + const mouseInput = [ 0, 1, 2, 'WHEEL' ]; + const keyInput = [ 'CTRL', 'SHIFT', null ]; + let state; + + if ( ! operationInput.includes( operation ) || ! mouseInput.includes( mouse ) || ! keyInput.includes( key ) ) { + + //invalid parameters + return false; + + } + + if ( mouse == 'WHEEL' ) { + + if ( operation != 'ZOOM' && operation != 'FOV' ) { + + //cannot associate 2D operation to 1D input + return false; + + } + + } + + switch ( operation ) { + + case 'PAN': + + state = STATE.PAN; + break; + + case 'ROTATE': + + state = STATE.ROTATE; + break; + + case 'ZOOM': + + state = STATE.SCALE; + break; + + case 'FOV': + + state = STATE.FOV; + break; + + } + + const action = { + + operation: operation, + mouse: mouse, + key: key, + state: state + + }; + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + if ( this.mouseActions[ i ].mouse == action.mouse && this.mouseActions[ i ].key == action.key ) { + + this.mouseActions.splice( i, 1, action ); + return true; + + } + + } + + this.mouseActions.push( action ); + return true; + + } + + /** + * Remove a mouse action by specifying its mouse/key combination + * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches + * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed + * @returns {Boolean} True if the operation has been succesfully removed, false otherwise + */ + unsetMouseAction( mouse, key = null ) { + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + if ( this.mouseActions[ i ].mouse == mouse && this.mouseActions[ i ].key == key ) { + + this.mouseActions.splice( i, 1 ); + return true; + + } + + } + + return false; + + } + + /** + * Return the operation associated to a mouse/keyboard combination + * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches + * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed + * @returns The operation if it has been found, null otherwise + */ + getOpFromAction( mouse, key ) { + + let action; + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + action = this.mouseActions[ i ]; + if ( action.mouse == mouse && action.key == key ) { + + return action.operation; + + } + + } + + if ( key != null ) { + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + action = this.mouseActions[ i ]; + if ( action.mouse == mouse && action.key == null ) { + + return action.operation; + + } + + } + + } + + return null; + + } + + /** + * Get the operation associated to mouse and key combination and returns the corresponding FSA state + * @param {Number} mouse Mouse button + * @param {String} key Keyboard modifier + * @returns The FSA state obtained from the operation associated to mouse/keyboard combination + */ + getOpStateFromAction( mouse, key ) { + + let action; + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + action = this.mouseActions[ i ]; + if ( action.mouse == mouse && action.key == key ) { + + return action.state; + + } + + } + + if ( key != null ) { + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + action = this.mouseActions[ i ]; + if ( action.mouse == mouse && action.key == null ) { + + return action.state; + + } + + } + + } + + return null; + + } + + /** + * Calculate the angle between two pointers + * @param {PointerEvent} p1 + * @param {PointerEvent} p2 + * @returns {Number} The angle between two pointers in degrees + */ + getAngle( p1, p2 ) { + + return Math.atan2( p2.clientY - p1.clientY, p2.clientX - p1.clientX ) * 180 / Math.PI; + + } + + /** + * Update a PointerEvent inside current pointerevents array + * @param {PointerEvent} event + */ + updateTouchEvent( event ) { + + for ( let i = 0; i < this._touchCurrent.length; i ++ ) { + + if ( this._touchCurrent[ i ].pointerId == event.pointerId ) { + + this._touchCurrent.splice( i, 1, event ); + break; + + } + + } + + } + + /** + * Apply a transformation matrix, to the camera and gizmos + * @param {Object} transformation Object containing matrices to apply to camera and gizmos + */ + applyTransformMatrix( transformation ) { + + if ( transformation.camera != null ) { + + this._m4_1.copy( this._cameraMatrixState ).premultiply( transformation.camera ); + this._m4_1.decompose( this.camera.position, this.camera.quaternion, this.camera.scale ); + this.camera.updateMatrix(); + + //update camera up vector + if ( this._state == STATE.ROTATE || this._state == STATE.ZROTATE || this._state == STATE.ANIMATION_ROTATE ) { + + this.camera.up.copy( this._upState ).applyQuaternion( this.camera.quaternion ); + + } + + } + + if ( transformation.gizmos != null ) { + + this._m4_1.copy( this._gizmoMatrixState ).premultiply( transformation.gizmos ); + this._m4_1.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + this._gizmos.updateMatrix(); + + } + + if ( this._state == STATE.SCALE || this._state == STATE.FOCUS || this._state == STATE.ANIMATION_FOCUS ) { + + this._tbRadius = this.calculateTbRadius( this.camera ); + + if ( this.adjustNearFar ) { + + const cameraDistance = this.camera.position.distanceTo( this._gizmos.position ); + + const bb = new Box3(); + bb.setFromObject( this._gizmos ); + const sphere = new Sphere(); + bb.getBoundingSphere( sphere ); + + const adjustedNearPosition = Math.max( this._nearPos0, sphere.radius + sphere.center.length() ); + const regularNearPosition = cameraDistance - this._initialNear; + + const minNearPos = Math.min( adjustedNearPosition, regularNearPosition ); + this.camera.near = cameraDistance - minNearPos; + + + const adjustedFarPosition = Math.min( this._farPos0, - sphere.radius + sphere.center.length() ); + const regularFarPosition = cameraDistance - this._initialFar; + + const minFarPos = Math.min( adjustedFarPosition, regularFarPosition ); + this.camera.far = cameraDistance - minFarPos; + + this.camera.updateProjectionMatrix(); + + } else { + + let update = false; + + if ( this.camera.near != this._initialNear ) { + + this.camera.near = this._initialNear; + update = true; + + } + + if ( this.camera.far != this._initialFar ) { + + this.camera.far = this._initialFar; + update = true; + + } + + if ( update ) { + + this.camera.updateProjectionMatrix(); + + } + + } + + } + + } + + /** + * Calculate the angular speed + * @param {Number} p0 Position at t0 + * @param {Number} p1 Position at t1 + * @param {Number} t0 Initial time in milliseconds + * @param {Number} t1 Ending time in milliseconds + */ + calculateAngularSpeed( p0, p1, t0, t1 ) { + + const s = p1 - p0; + const t = ( t1 - t0 ) / 1000; + if ( t == 0 ) { + + return 0; + + } + + return s / t; + + } + + /** + * Calculate the distance between two pointers + * @param {PointerEvent} p0 The first pointer + * @param {PointerEvent} p1 The second pointer + * @returns {number} The distance between the two pointers + */ + calculatePointersDistance( p0, p1 ) { + + return Math.sqrt( Math.pow( p1.clientX - p0.clientX, 2 ) + Math.pow( p1.clientY - p0.clientY, 2 ) ); + + } + + /** + * Calculate the rotation axis as the vector perpendicular between two vectors + * @param {Vector3} vec1 The first vector + * @param {Vector3} vec2 The second vector + * @returns {Vector3} The normalized rotation axis + */ + calculateRotationAxis( vec1, vec2 ) { + + this._rotationMatrix.extractRotation( this._cameraMatrixState ); + this._quat.setFromRotationMatrix( this._rotationMatrix ); + + this._rotationAxis.crossVectors( vec1, vec2 ).applyQuaternion( this._quat ); + return this._rotationAxis.normalize().clone(); + + } + + /** + * Calculate the trackball radius so that gizmo's diamater will be 2/3 of the minimum side of the camera frustum + * @param {Camera} camera + * @returns {Number} The trackball radius + */ + calculateTbRadius( camera ) { + + const distance = camera.position.distanceTo( this._gizmos.position ); + + if ( camera.type == 'PerspectiveCamera' ) { + + const halfFovV = MathUtils.DEG2RAD * camera.fov * 0.5; //vertical fov/2 in radians + const halfFovH = Math.atan( ( camera.aspect ) * Math.tan( halfFovV ) ); //horizontal fov/2 in radians + return Math.tan( Math.min( halfFovV, halfFovH ) ) * distance * this.radiusFactor; + + } else if ( camera.type == 'OrthographicCamera' ) { + + return Math.min( camera.top, camera.right ) * this.radiusFactor; + + } + + } + + /** + * Focus operation consist of positioning the point of interest in front of the camera and a slightly zoom in + * @param {Vector3} point The point of interest + * @param {Number} size Scale factor + * @param {Number} amount Amount of operation to be completed (used for focus animations, default is complete full operation) + */ + focus( point, size, amount = 1 ) { + + //move center of camera (along with gizmos) towards point of interest + _offset.copy( point ).sub( this._gizmos.position ).multiplyScalar( amount ); + this._translationMatrix.makeTranslation( _offset.x, _offset.y, _offset.z ); + + _gizmoMatrixStateTemp.copy( this._gizmoMatrixState ); + this._gizmoMatrixState.premultiply( this._translationMatrix ); + this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + + _cameraMatrixStateTemp.copy( this._cameraMatrixState ); + this._cameraMatrixState.premultiply( this._translationMatrix ); + this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale ); + + //apply zoom + if ( this.enableZoom ) { + + this.applyTransformMatrix( this.scale( size, this._gizmos.position ) ); + + } + + this._gizmoMatrixState.copy( _gizmoMatrixStateTemp ); + this._cameraMatrixState.copy( _cameraMatrixStateTemp ); + + } + + /** + * Draw a grid and add it to the scene + */ + drawGrid() { + + if ( this.scene != null ) { + + const color = 0x888888; + const multiplier = 3; + let size, divisions, maxLength, tick; + + if ( this.camera.isOrthographicCamera ) { + + const width = this.camera.right - this.camera.left; + const height = this.camera.bottom - this.camera.top; + + maxLength = Math.max( width, height ); + tick = maxLength / 20; + + size = maxLength / this.camera.zoom * multiplier; + divisions = size / tick * this.camera.zoom; + + } else if ( this.camera.isPerspectiveCamera ) { + + const distance = this.camera.position.distanceTo( this._gizmos.position ); + const halfFovV = MathUtils.DEG2RAD * this.camera.fov * 0.5; + const halfFovH = Math.atan( ( this.camera.aspect ) * Math.tan( halfFovV ) ); + + maxLength = Math.tan( Math.max( halfFovV, halfFovH ) ) * distance * 2; + tick = maxLength / 20; + + size = maxLength * multiplier; + divisions = size / tick; + + } + + if ( this._grid == null ) { + + this._grid = new GridHelper( size, divisions, color, color ); + this._grid.position.copy( this._gizmos.position ); + this._gridPosition.copy( this._grid.position ); + this._grid.quaternion.copy( this.camera.quaternion ); + this._grid.rotateX( Math.PI * 0.5 ); + + this.scene.add( this._grid ); + + } + + } + + } + + /** + * Remove all listeners, stop animations and clean scene + */ + dispose() { + + if ( this._animationId != - 1 ) { + + window.cancelAnimationFrame( this._animationId ); + + } + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.removeEventListener( 'pointercancel', this._onPointerCancel ); + this.domElement.removeEventListener( 'wheel', this._onWheel ); + this.domElement.removeEventListener( 'contextmenu', this._onContextMenu ); + + window.removeEventListener( 'pointermove', this._onPointerMove ); + window.removeEventListener( 'pointerup', this._onPointerUp ); + + window.removeEventListener( 'resize', this._onWindowResize ); + + if ( this.scene !== null ) this.scene.remove( this._gizmos ); + this.disposeGrid(); + + } + + /** + * remove the grid from the scene + */ + disposeGrid() { + + if ( this._grid != null && this.scene != null ) { + + this.scene.remove( this._grid ); + this._grid = null; + + } + + } + + /** + * Compute the easing out cubic function for ease out effect in animation + * @param {Number} t The absolute progress of the animation in the bound of 0 (beginning of the) and 1 (ending of animation) + * @returns {Number} Result of easing out cubic at time t + */ + easeOutCubic( t ) { + + return 1 - Math.pow( 1 - t, 3 ); + + } + + /** + * Make rotation gizmos more or less visible + * @param {Boolean} isActive If true, make gizmos more visible + */ + activateGizmos( isActive ) { + + const gizmoX = this._gizmos.children[ 0 ]; + const gizmoY = this._gizmos.children[ 1 ]; + const gizmoZ = this._gizmos.children[ 2 ]; + + if ( isActive ) { + + gizmoX.material.setValues( { opacity: 1 } ); + gizmoY.material.setValues( { opacity: 1 } ); + gizmoZ.material.setValues( { opacity: 1 } ); + + } else { + + gizmoX.material.setValues( { opacity: 0.6 } ); + gizmoY.material.setValues( { opacity: 0.6 } ); + gizmoZ.material.setValues( { opacity: 0.6 } ); + + } + + } + + /** + * Calculate the cursor position in NDC + * @param {number} x Cursor horizontal coordinate within the canvas + * @param {number} y Cursor vertical coordinate within the canvas + * @param {HTMLElement} canvas The canvas where the renderer draws its output + * @returns {Vector2} Cursor normalized position inside the canvas + */ + getCursorNDC( cursorX, cursorY, canvas ) { + + const canvasRect = canvas.getBoundingClientRect(); + this._v2_1.setX( ( ( cursorX - canvasRect.left ) / canvasRect.width ) * 2 - 1 ); + this._v2_1.setY( ( ( canvasRect.bottom - cursorY ) / canvasRect.height ) * 2 - 1 ); + return this._v2_1.clone(); + + } + + /** + * Calculate the cursor position inside the canvas x/y coordinates with the origin being in the center of the canvas + * @param {Number} x Cursor horizontal coordinate within the canvas + * @param {Number} y Cursor vertical coordinate within the canvas + * @param {HTMLElement} canvas The canvas where the renderer draws its output + * @returns {Vector2} Cursor position inside the canvas + */ + getCursorPosition( cursorX, cursorY, canvas ) { + + this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) ); + this._v2_1.x *= ( this.camera.right - this.camera.left ) * 0.5; + this._v2_1.y *= ( this.camera.top - this.camera.bottom ) * 0.5; + return this._v2_1.clone(); + + } + + /** + * Set the camera to be controlled + * @param {Camera} camera The virtual camera to be controlled + */ + setCamera( camera ) { + + camera.lookAt( this.target ); + camera.updateMatrix(); + + //setting state + if ( camera.type == 'PerspectiveCamera' ) { + + this._fov0 = camera.fov; + this._fovState = camera.fov; + + } + + this._cameraMatrixState0.copy( camera.matrix ); + this._cameraMatrixState.copy( this._cameraMatrixState0 ); + this._cameraProjectionState.copy( camera.projectionMatrix ); + this._zoom0 = camera.zoom; + this._zoomState = this._zoom0; + + this._initialNear = camera.near; + this._nearPos0 = camera.position.distanceTo( this.target ) - camera.near; + this._nearPos = this._initialNear; + + this._initialFar = camera.far; + this._farPos0 = camera.position.distanceTo( this.target ) - camera.far; + this._farPos = this._initialFar; + + this._up0.copy( camera.up ); + this._upState.copy( camera.up ); + + this.camera = camera; + this.camera.updateProjectionMatrix(); + + //making gizmos + this._tbRadius = this.calculateTbRadius( camera ); + this.makeGizmos( this.target, this._tbRadius ); + + } + + /** + * Set gizmos visibility + * @param {Boolean} value Value of gizmos visibility + */ + setGizmosVisible( value ) { + + this._gizmos.visible = value; + this.dispatchEvent( _changeEvent ); + + } + + /** + * Set gizmos radius factor and redraws gizmos + * @param {Float} value Value of radius factor + */ + setTbRadius( value ) { + + this.radiusFactor = value; + this._tbRadius = this.calculateTbRadius( this.camera ); + + const curve = new EllipseCurve( 0, 0, this._tbRadius, this._tbRadius ); + const points = curve.getPoints( this._curvePts ); + const curveGeometry = new BufferGeometry().setFromPoints( points ); + + + for ( const gizmo in this._gizmos.children ) { + + this._gizmos.children[ gizmo ].geometry = curveGeometry; + + } + + this.dispatchEvent( _changeEvent ); + + } + + /** + * Creates the rotation gizmos matching trackball center and radius + * @param {Vector3} tbCenter The trackball center + * @param {number} tbRadius The trackball radius + */ + makeGizmos( tbCenter, tbRadius ) { + + const curve = new EllipseCurve( 0, 0, tbRadius, tbRadius ); + const points = curve.getPoints( this._curvePts ); + + //geometry + const curveGeometry = new BufferGeometry().setFromPoints( points ); + + //material + const curveMaterialX = new LineBasicMaterial( { color: 0xff8080, fog: false, transparent: true, opacity: 0.6 } ); + const curveMaterialY = new LineBasicMaterial( { color: 0x80ff80, fog: false, transparent: true, opacity: 0.6 } ); + const curveMaterialZ = new LineBasicMaterial( { color: 0x8080ff, fog: false, transparent: true, opacity: 0.6 } ); + + //line + const gizmoX = new Line( curveGeometry, curveMaterialX ); + const gizmoY = new Line( curveGeometry, curveMaterialY ); + const gizmoZ = new Line( curveGeometry, curveMaterialZ ); + + const rotation = Math.PI * 0.5; + gizmoX.rotation.x = rotation; + gizmoY.rotation.y = rotation; + + + //setting state + this._gizmoMatrixState0.identity().setPosition( tbCenter ); + this._gizmoMatrixState.copy( this._gizmoMatrixState0 ); + + if ( this.camera.zoom !== 1 ) { + + //adapt gizmos size to camera zoom + const size = 1 / this.camera.zoom; + this._scaleMatrix.makeScale( size, size, size ); + this._translationMatrix.makeTranslation( - tbCenter.x, - tbCenter.y, - tbCenter.z ); + + this._gizmoMatrixState.premultiply( this._translationMatrix ).premultiply( this._scaleMatrix ); + this._translationMatrix.makeTranslation( tbCenter.x, tbCenter.y, tbCenter.z ); + this._gizmoMatrixState.premultiply( this._translationMatrix ); + + } + + this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + + // + + this._gizmos.traverse( function ( object ) { + + if ( object.isLine ) { + + object.geometry.dispose(); + object.material.dispose(); + + } + + } ); + + this._gizmos.clear(); + + // + + this._gizmos.add( gizmoX ); + this._gizmos.add( gizmoY ); + this._gizmos.add( gizmoZ ); + + } + + /** + * Perform animation for focus operation + * @param {Number} time Instant in which this function is called as performance.now() + * @param {Vector3} point Point of interest for focus operation + * @param {Matrix4} cameraMatrix Camera matrix + * @param {Matrix4} gizmoMatrix Gizmos matrix + */ + onFocusAnim( time, point, cameraMatrix, gizmoMatrix ) { + + if ( this._timeStart == - 1 ) { + + //animation start + this._timeStart = time; + + } + + if ( this._state == STATE.ANIMATION_FOCUS ) { + + const deltaTime = time - this._timeStart; + const animTime = deltaTime / this.focusAnimationTime; + + this._gizmoMatrixState.copy( gizmoMatrix ); + + if ( animTime >= 1 ) { + + //animation end + + this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + + this.focus( point, this.scaleFactor ); + + this._timeStart = - 1; + this.updateTbState( STATE.IDLE, false ); + this.activateGizmos( false ); + + this.dispatchEvent( _changeEvent ); + + } else { + + const amount = this.easeOutCubic( animTime ); + const size = ( ( 1 - amount ) + ( this.scaleFactor * amount ) ); + + this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + this.focus( point, size, amount ); + + this.dispatchEvent( _changeEvent ); + const self = this; + this._animationId = window.requestAnimationFrame( function ( t ) { + + self.onFocusAnim( t, point, cameraMatrix, gizmoMatrix.clone() ); + + } ); + + } + + } else { + + //interrupt animation + + this._animationId = - 1; + this._timeStart = - 1; + + } + + } + + /** + * Perform animation for rotation operation + * @param {Number} time Instant in which this function is called as performance.now() + * @param {Vector3} rotationAxis Rotation axis + * @param {number} w0 Initial angular velocity + */ + onRotationAnim( time, rotationAxis, w0 ) { + + if ( this._timeStart == - 1 ) { + + //animation start + this._anglePrev = 0; + this._angleCurrent = 0; + this._timeStart = time; + + } + + if ( this._state == STATE.ANIMATION_ROTATE ) { + + //w = w0 + alpha * t + const deltaTime = ( time - this._timeStart ) / 1000; + const w = w0 + ( ( - this.dampingFactor ) * deltaTime ); + + if ( w > 0 ) { + + //tetha = 0.5 * alpha * t^2 + w0 * t + tetha0 + this._angleCurrent = 0.5 * ( - this.dampingFactor ) * Math.pow( deltaTime, 2 ) + w0 * deltaTime + 0; + this.applyTransformMatrix( this.rotate( rotationAxis, this._angleCurrent ) ); + this.dispatchEvent( _changeEvent ); + const self = this; + this._animationId = window.requestAnimationFrame( function ( t ) { + + self.onRotationAnim( t, rotationAxis, w0 ); + + } ); + + } else { + + this._animationId = - 1; + this._timeStart = - 1; + + this.updateTbState( STATE.IDLE, false ); + this.activateGizmos( false ); + + this.dispatchEvent( _changeEvent ); + + } + + } else { + + //interrupt animation + + this._animationId = - 1; + this._timeStart = - 1; + + if ( this._state != STATE.ROTATE ) { + + this.activateGizmos( false ); + this.dispatchEvent( _changeEvent ); + + } + + } + + } + + + /** + * Perform pan operation moving camera between two points + * @param {Vector3} p0 Initial point + * @param {Vector3} p1 Ending point + * @param {Boolean} adjust If movement should be adjusted considering camera distance (Perspective only) + */ + pan( p0, p1, adjust = false ) { + + const movement = p0.clone().sub( p1 ); + + if ( this.camera.isOrthographicCamera ) { + + //adjust movement amount + movement.multiplyScalar( 1 / this.camera.zoom ); + + } else if ( this.camera.isPerspectiveCamera && adjust ) { + + //adjust movement amount + this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ); //camera's initial position + this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ); //gizmo's initial position + const distanceFactor = this._v3_1.distanceTo( this._v3_2 ) / this.camera.position.distanceTo( this._gizmos.position ); + movement.multiplyScalar( 1 / distanceFactor ); + + } + + this._v3_1.set( movement.x, movement.y, 0 ).applyQuaternion( this.camera.quaternion ); + + this._m4_1.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z ); + + this.setTransformationMatrices( this._m4_1, this._m4_1 ); + return _transformation; + + } + + /** + * Reset trackball + */ + reset() { + + this.camera.zoom = this._zoom0; + + if ( this.camera.isPerspectiveCamera ) { + + this.camera.fov = this._fov0; + + } + + this.camera.near = this._nearPos; + this.camera.far = this._farPos; + this._cameraMatrixState.copy( this._cameraMatrixState0 ); + this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale ); + this.camera.up.copy( this._up0 ); + + this.camera.updateMatrix(); + this.camera.updateProjectionMatrix(); + + this._gizmoMatrixState.copy( this._gizmoMatrixState0 ); + this._gizmoMatrixState0.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + this._gizmos.updateMatrix(); + + this._tbRadius = this.calculateTbRadius( this.camera ); + this.makeGizmos( this._gizmos.position, this._tbRadius ); + + this.camera.lookAt( this._gizmos.position ); + + this.updateTbState( STATE.IDLE, false ); + + this.dispatchEvent( _changeEvent ); + + } + + /** + * Rotate the camera around an axis passing by trackball's center + * @param {Vector3} axis Rotation axis + * @param {number} angle Angle in radians + * @returns {Object} Object with 'camera' field containing transformation matrix resulting from the operation to be applied to the camera + */ + rotate( axis, angle ) { + + const point = this._gizmos.position; //rotation center + this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z ); + this._rotationMatrix.makeRotationAxis( axis, - angle ); + + //rotate camera + this._m4_1.makeTranslation( point.x, point.y, point.z ); + this._m4_1.multiply( this._rotationMatrix ); + this._m4_1.multiply( this._translationMatrix ); + + this.setTransformationMatrices( this._m4_1 ); + + return _transformation; + + } + + copyState() { + + let state; + if ( this.camera.isOrthographicCamera ) { + + state = JSON.stringify( { arcballState: { + + cameraFar: this.camera.far, + cameraMatrix: this.camera.matrix, + cameraNear: this.camera.near, + cameraUp: this.camera.up, + cameraZoom: this.camera.zoom, + gizmoMatrix: this._gizmos.matrix + + } } ); + + } else if ( this.camera.isPerspectiveCamera ) { + + state = JSON.stringify( { arcballState: { + cameraFar: this.camera.far, + cameraFov: this.camera.fov, + cameraMatrix: this.camera.matrix, + cameraNear: this.camera.near, + cameraUp: this.camera.up, + cameraZoom: this.camera.zoom, + gizmoMatrix: this._gizmos.matrix + + } } ); + + } + + navigator.clipboard.writeText( state ); + + } + + pasteState() { + + const self = this; + navigator.clipboard.readText().then( function resolved( value ) { + + self.setStateFromJSON( value ); + + } ); + + } + + /** + * Save the current state of the control. This can later be recover with .reset + */ + saveState() { + + this._cameraMatrixState0.copy( this.camera.matrix ); + this._gizmoMatrixState0.copy( this._gizmos.matrix ); + this._nearPos = this.camera.near; + this._farPos = this.camera.far; + this._zoom0 = this.camera.zoom; + this._up0.copy( this.camera.up ); + + if ( this.camera.isPerspectiveCamera ) { + + this._fov0 = this.camera.fov; + + } + + } + + /** + * Perform uniform scale operation around a given point + * @param {Number} size Scale factor + * @param {Vector3} point Point around which scale + * @param {Boolean} scaleGizmos If gizmos should be scaled (Perspective only) + * @returns {Object} Object with 'camera' and 'gizmo' fields containing transformation matrices resulting from the operation to be applied to the camera and gizmos + */ + scale( size, point, scaleGizmos = true ) { + + _scalePointTemp.copy( point ); + let sizeInverse = 1 / size; + + if ( this.camera.isOrthographicCamera ) { + + //camera zoom + this.camera.zoom = this._zoomState; + this.camera.zoom *= size; + + //check min and max zoom + if ( this.camera.zoom > this.maxZoom ) { + + this.camera.zoom = this.maxZoom; + sizeInverse = this._zoomState / this.maxZoom; + + } else if ( this.camera.zoom < this.minZoom ) { + + this.camera.zoom = this.minZoom; + sizeInverse = this._zoomState / this.minZoom; + + } + + this.camera.updateProjectionMatrix(); + + this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ); //gizmos position + + //scale gizmos so they appear in the same spot having the same dimension + this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse ); + this._translationMatrix.makeTranslation( - this._v3_1.x, - this._v3_1.y, - this._v3_1.z ); + + this._m4_2.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z ).multiply( this._scaleMatrix ); + this._m4_2.multiply( this._translationMatrix ); + + + //move camera and gizmos to obtain pinch effect + _scalePointTemp.sub( this._v3_1 ); + + const amount = _scalePointTemp.clone().multiplyScalar( sizeInverse ); + _scalePointTemp.sub( amount ); + + this._m4_1.makeTranslation( _scalePointTemp.x, _scalePointTemp.y, _scalePointTemp.z ); + this._m4_2.premultiply( this._m4_1 ); + + this.setTransformationMatrices( this._m4_1, this._m4_2 ); + return _transformation; + + } else if ( this.camera.isPerspectiveCamera ) { + + this._v3_1.setFromMatrixPosition( this._cameraMatrixState ); + this._v3_2.setFromMatrixPosition( this._gizmoMatrixState ); + + //move camera + let distance = this._v3_1.distanceTo( _scalePointTemp ); + let amount = distance - ( distance * sizeInverse ); + + //check min and max distance + const newDistance = distance - amount; + if ( newDistance < this.minDistance ) { + + sizeInverse = this.minDistance / distance; + amount = distance - ( distance * sizeInverse ); + + } else if ( newDistance > this.maxDistance ) { + + sizeInverse = this.maxDistance / distance; + amount = distance - ( distance * sizeInverse ); + + } + + _offset.copy( _scalePointTemp ).sub( this._v3_1 ).normalize().multiplyScalar( amount ); + + this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z ); + + + if ( scaleGizmos ) { + + //scale gizmos so they appear in the same spot having the same dimension + const pos = this._v3_2; + + distance = pos.distanceTo( _scalePointTemp ); + amount = distance - ( distance * sizeInverse ); + _offset.copy( _scalePointTemp ).sub( this._v3_2 ).normalize().multiplyScalar( amount ); + + this._translationMatrix.makeTranslation( pos.x, pos.y, pos.z ); + this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse ); + + this._m4_2.makeTranslation( _offset.x, _offset.y, _offset.z ).multiply( this._translationMatrix ); + this._m4_2.multiply( this._scaleMatrix ); + + this._translationMatrix.makeTranslation( - pos.x, - pos.y, - pos.z ); + + this._m4_2.multiply( this._translationMatrix ); + this.setTransformationMatrices( this._m4_1, this._m4_2 ); + + + } else { + + this.setTransformationMatrices( this._m4_1 ); + + } + + return _transformation; + + } + + } + + /** + * Set camera fov + * @param {Number} value fov to be setted + */ + setFov( value ) { + + if ( this.camera.isPerspectiveCamera ) { + + this.camera.fov = MathUtils.clamp( value, this.minFov, this.maxFov ); + this.camera.updateProjectionMatrix(); + + } + + } + + /** + * Set values in transformation object + * @param {Matrix4} camera Transformation to be applied to the camera + * @param {Matrix4} gizmos Transformation to be applied to gizmos + */ + setTransformationMatrices( camera = null, gizmos = null ) { + + if ( camera != null ) { + + if ( _transformation.camera != null ) { + + _transformation.camera.copy( camera ); + + } else { + + _transformation.camera = camera.clone(); + + } + + } else { + + _transformation.camera = null; + + } + + if ( gizmos != null ) { + + if ( _transformation.gizmos != null ) { + + _transformation.gizmos.copy( gizmos ); + + } else { + + _transformation.gizmos = gizmos.clone(); + + } + + } else { + + _transformation.gizmos = null; + + } + + } + + /** + * Rotate camera around its direction axis passing by a given point by a given angle + * @param {Vector3} point The point where the rotation axis is passing trough + * @param {Number} angle Angle in radians + * @returns The computed transormation matix + */ + zRotate( point, angle ) { + + this._rotationMatrix.makeRotationAxis( this._rotationAxis, angle ); + this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z ); + + this._m4_1.makeTranslation( point.x, point.y, point.z ); + this._m4_1.multiply( this._rotationMatrix ); + this._m4_1.multiply( this._translationMatrix ); + + this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ).sub( point ); //vector from rotation center to gizmos position + this._v3_2.copy( this._v3_1 ).applyAxisAngle( this._rotationAxis, angle ); //apply rotation + this._v3_2.sub( this._v3_1 ); + + this._m4_2.makeTranslation( this._v3_2.x, this._v3_2.y, this._v3_2.z ); + + this.setTransformationMatrices( this._m4_1, this._m4_2 ); + return _transformation; + + } + + + getRaycaster() { + + return _raycaster; + + } + + + /** + * Unproject the cursor on the 3D object surface + * @param {Vector2} cursor Cursor coordinates in NDC + * @param {Camera} camera Virtual camera + * @returns {Vector3} The point of intersection with the model, if exist, null otherwise + */ + unprojectOnObj( cursor, camera ) { + + const raycaster = this.getRaycaster(); + raycaster.near = camera.near; + raycaster.far = camera.far; + raycaster.setFromCamera( cursor, camera ); + + const intersect = raycaster.intersectObjects( this.scene.children, true ); + + for ( let i = 0; i < intersect.length; i ++ ) { + + if ( intersect[ i ].object.uuid != this._gizmos.uuid && intersect[ i ].face != null ) { + + return intersect[ i ].point.clone(); + + } + + } + + return null; + + } + + /** + * Unproject the cursor on the trackball surface + * @param {Camera} camera The virtual camera + * @param {Number} cursorX Cursor horizontal coordinate on screen + * @param {Number} cursorY Cursor vertical coordinate on screen + * @param {HTMLElement} canvas The canvas where the renderer draws its output + * @param {number} tbRadius The trackball radius + * @returns {Vector3} The unprojected point on the trackball surface + */ + unprojectOnTbSurface( camera, cursorX, cursorY, canvas, tbRadius ) { + + if ( camera.type == 'OrthographicCamera' ) { + + this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) ); + this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 ); + + const x2 = Math.pow( this._v2_1.x, 2 ); + const y2 = Math.pow( this._v2_1.y, 2 ); + const r2 = Math.pow( this._tbRadius, 2 ); + + if ( x2 + y2 <= r2 * 0.5 ) { + + //intersection with sphere + this._v3_1.setZ( Math.sqrt( r2 - ( x2 + y2 ) ) ); + + } else { + + //intersection with hyperboloid + this._v3_1.setZ( ( r2 * 0.5 ) / ( Math.sqrt( x2 + y2 ) ) ); + + } + + return this._v3_1; + + } else if ( camera.type == 'PerspectiveCamera' ) { + + //unproject cursor on the near plane + this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) ); + + this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 ); + this._v3_1.applyMatrix4( camera.projectionMatrixInverse ); + + const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction + const cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position ); + const radius2 = Math.pow( tbRadius, 2 ); + + // camera + // |\ + // | \ + // | \ + // h | \ + // | \ + // | \ + // _ _ | _ _ _\ _ _ near plane + // l + + const h = this._v3_1.z; + const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) ); + + if ( l == 0 ) { + + //ray aligned with camera + rayDir.set( this._v3_1.x, this._v3_1.y, tbRadius ); + return rayDir; + + } + + const m = h / l; + const q = cameraGizmoDistance; + + /* + * calculate intersection point between unprojected ray and trackball surface + *|y = m * x + q + *|x^2 + y^2 = r^2 + * + * (m^2 + 1) * x^2 + (2 * m * q) * x + q^2 - r^2 = 0 + */ + let a = Math.pow( m, 2 ) + 1; + let b = 2 * m * q; + let c = Math.pow( q, 2 ) - radius2; + let delta = Math.pow( b, 2 ) - ( 4 * a * c ); + + if ( delta >= 0 ) { + + //intersection with sphere + this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) ); + this._v2_1.setY( m * this._v2_1.x + q ); + + const angle = MathUtils.RAD2DEG * this._v2_1.angle(); + + if ( angle >= 45 ) { + + //if angle between intersection point and X' axis is >= 45°, return that point + //otherwise, calculate intersection point with hyperboloid + + const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) ); + rayDir.multiplyScalar( rayLength ); + rayDir.z += cameraGizmoDistance; + return rayDir; + + } + + } + + //intersection with hyperboloid + /* + *|y = m * x + q + *|y = (1 / x) * (r^2 / 2) + * + * m * x^2 + q * x - r^2 / 2 = 0 + */ + + a = m; + b = q; + c = - radius2 * 0.5; + delta = Math.pow( b, 2 ) - ( 4 * a * c ); + this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) ); + this._v2_1.setY( m * this._v2_1.x + q ); + + const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) ); + + rayDir.multiplyScalar( rayLength ); + rayDir.z += cameraGizmoDistance; + return rayDir; + + } + + } + + + /** + * Unproject the cursor on the plane passing through the center of the trackball orthogonal to the camera + * @param {Camera} camera The virtual camera + * @param {Number} cursorX Cursor horizontal coordinate on screen + * @param {Number} cursorY Cursor vertical coordinate on screen + * @param {HTMLElement} canvas The canvas where the renderer draws its output + * @param {Boolean} initialDistance If initial distance between camera and gizmos should be used for calculations instead of current (Perspective only) + * @returns {Vector3} The unprojected point on the trackball plane + */ + unprojectOnTbPlane( camera, cursorX, cursorY, canvas, initialDistance = false ) { + + if ( camera.type == 'OrthographicCamera' ) { + + this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) ); + this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 ); + + return this._v3_1.clone(); + + } else if ( camera.type == 'PerspectiveCamera' ) { + + this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) ); + + //unproject cursor on the near plane + this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 ); + this._v3_1.applyMatrix4( camera.projectionMatrixInverse ); + + const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction + + // camera + // |\ + // | \ + // | \ + // h | \ + // | \ + // | \ + // _ _ | _ _ _\ _ _ near plane + // l + + const h = this._v3_1.z; + const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) ); + let cameraGizmoDistance; + + if ( initialDistance ) { + + cameraGizmoDistance = this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ).distanceTo( this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ) ); + + } else { + + cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position ); + + } + + /* + * calculate intersection point between unprojected ray and the plane + *|y = mx + q + *|y = 0 + * + * x = -q/m + */ + if ( l == 0 ) { + + //ray aligned with camera + rayDir.set( 0, 0, 0 ); + return rayDir; + + } + + const m = h / l; + const q = cameraGizmoDistance; + const x = - q / m; + + const rayLength = Math.sqrt( Math.pow( q, 2 ) + Math.pow( x, 2 ) ); + rayDir.multiplyScalar( rayLength ); + rayDir.z = 0; + return rayDir; + + } + + } + + /** + * Update camera and gizmos state + */ + updateMatrixState() { + + //update camera and gizmos state + this._cameraMatrixState.copy( this.camera.matrix ); + this._gizmoMatrixState.copy( this._gizmos.matrix ); + + if ( this.camera.isOrthographicCamera ) { + + this._cameraProjectionState.copy( this.camera.projectionMatrix ); + this.camera.updateProjectionMatrix(); + this._zoomState = this.camera.zoom; + + } else if ( this.camera.isPerspectiveCamera ) { + + this._fovState = this.camera.fov; + + } + + } + + /** + * Update the trackball FSA + * @param {STATE} newState New state of the FSA + * @param {Boolean} updateMatrices If matriices state should be updated + */ + updateTbState( newState, updateMatrices ) { + + this._state = newState; + if ( updateMatrices ) { + + this.updateMatrixState(); + + } + + } + + update() { + + const EPS = 0.000001; + + if ( this.target.equals( this._currentTarget ) === false ) { + + this._gizmos.position.copy( this.target ); //for correct radius calculation + this._tbRadius = this.calculateTbRadius( this.camera ); + this.makeGizmos( this.target, this._tbRadius ); + this._currentTarget.copy( this.target ); + + } + + //check min/max parameters + if ( this.camera.isOrthographicCamera ) { + + //check zoom + if ( this.camera.zoom > this.maxZoom || this.camera.zoom < this.minZoom ) { + + const newZoom = MathUtils.clamp( this.camera.zoom, this.minZoom, this.maxZoom ); + this.applyTransformMatrix( this.scale( newZoom / this.camera.zoom, this._gizmos.position, true ) ); + + } + + } else if ( this.camera.isPerspectiveCamera ) { + + //check distance + const distance = this.camera.position.distanceTo( this._gizmos.position ); + + if ( distance > this.maxDistance + EPS || distance < this.minDistance - EPS ) { + + const newDistance = MathUtils.clamp( distance, this.minDistance, this.maxDistance ); + this.applyTransformMatrix( this.scale( newDistance / distance, this._gizmos.position ) ); + this.updateMatrixState(); + + } + + //check fov + if ( this.camera.fov < this.minFov || this.camera.fov > this.maxFov ) { + + this.camera.fov = MathUtils.clamp( this.camera.fov, this.minFov, this.maxFov ); + this.camera.updateProjectionMatrix(); + + } + + const oldRadius = this._tbRadius; + this._tbRadius = this.calculateTbRadius( this.camera ); + + if ( oldRadius < this._tbRadius - EPS || oldRadius > this._tbRadius + EPS ) { + + const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3; + const newRadius = this._tbRadius / scale; + const curve = new EllipseCurve( 0, 0, newRadius, newRadius ); + const points = curve.getPoints( this._curvePts ); + const curveGeometry = new BufferGeometry().setFromPoints( points ); + + for ( const gizmo in this._gizmos.children ) { + + this._gizmos.children[ gizmo ].geometry = curveGeometry; + + } + + } + + } + + this.camera.lookAt( this._gizmos.position ); + + } + + setStateFromJSON( json ) { + + const state = JSON.parse( json ); + + if ( state.arcballState != undefined ) { + + this._cameraMatrixState.fromArray( state.arcballState.cameraMatrix.elements ); + this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale ); + + this.camera.up.copy( state.arcballState.cameraUp ); + this.camera.near = state.arcballState.cameraNear; + this.camera.far = state.arcballState.cameraFar; + + this.camera.zoom = state.arcballState.cameraZoom; + + if ( this.camera.isPerspectiveCamera ) { + + this.camera.fov = state.arcballState.cameraFov; + + } + + this._gizmoMatrixState.fromArray( state.arcballState.gizmoMatrix.elements ); + this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale ); + + this.camera.updateMatrix(); + this.camera.updateProjectionMatrix(); + + this._gizmos.updateMatrix(); + + this._tbRadius = this.calculateTbRadius( this.camera ); + const gizmoTmp = new Matrix4().copy( this._gizmoMatrixState0 ); + this.makeGizmos( this._gizmos.position, this._tbRadius ); + this._gizmoMatrixState0.copy( gizmoTmp ); + + this.camera.lookAt( this._gizmos.position ); + this.updateTbState( STATE.IDLE, false ); + + this.dispatchEvent( _changeEvent ); + + } + + } + +} + +//listeners + +function onWindowResize() { + + const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3; + this._tbRadius = this.calculateTbRadius( this.camera ); + + const newRadius = this._tbRadius / scale; + const curve = new EllipseCurve( 0, 0, newRadius, newRadius ); + const points = curve.getPoints( this._curvePts ); + const curveGeometry = new BufferGeometry().setFromPoints( points ); + + + for ( const gizmo in this._gizmos.children ) { + + this._gizmos.children[ gizmo ].geometry = curveGeometry; + + } + + this.dispatchEvent( _changeEvent ); + +} + +function onContextMenu( event ) { + + if ( ! this.enabled ) { + + return; + + } + + for ( let i = 0; i < this.mouseActions.length; i ++ ) { + + if ( this.mouseActions[ i ].mouse == 2 ) { + + //prevent only if button 2 is actually used + event.preventDefault(); + break; + + } + + } + +} + +function onPointerCancel() { + + this._touchStart.splice( 0, this._touchStart.length ); + this._touchCurrent.splice( 0, this._touchCurrent.length ); + this._input = INPUT.NONE; + +} + +function onPointerDown( event ) { + + if ( event.button == 0 && event.isPrimary ) { + + this._downValid = true; + this._downEvents.push( event ); + this._downStart = performance.now(); + + } else { + + this._downValid = false; + + } + + if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) { + + this._touchStart.push( event ); + this._touchCurrent.push( event ); + + switch ( this._input ) { + + case INPUT.NONE: + + //singleStart + this._input = INPUT.ONE_FINGER; + this.onSinglePanStart( event, 'ROTATE' ); + + window.addEventListener( 'pointermove', this._onPointerMove ); + window.addEventListener( 'pointerup', this._onPointerUp ); + + break; + + case INPUT.ONE_FINGER: + case INPUT.ONE_FINGER_SWITCHED: + + //doubleStart + this._input = INPUT.TWO_FINGER; + + this.onRotateStart(); + this.onPinchStart(); + this.onDoublePanStart(); + + break; + + case INPUT.TWO_FINGER: + + //multipleStart + this._input = INPUT.MULT_FINGER; + this.onTriplePanStart( event ); + break; + + } + + } else if ( event.pointerType != 'touch' && this._input == INPUT.NONE ) { + + let modifier = null; + + if ( event.ctrlKey || event.metaKey ) { + + modifier = 'CTRL'; + + } else if ( event.shiftKey ) { + + modifier = 'SHIFT'; + + } + + this._mouseOp = this.getOpFromAction( event.button, modifier ); + if ( this._mouseOp != null ) { + + window.addEventListener( 'pointermove', this._onPointerMove ); + window.addEventListener( 'pointerup', this._onPointerUp ); + + //singleStart + this._input = INPUT.CURSOR; + this._button = event.button; + this.onSinglePanStart( event, this._mouseOp ); + + } + + } + +} + +function onPointerMove( event ) { + + if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) { + + switch ( this._input ) { + + case INPUT.ONE_FINGER: + + //singleMove + this.updateTouchEvent( event ); + + this.onSinglePanMove( event, STATE.ROTATE ); + break; + + case INPUT.ONE_FINGER_SWITCHED: + + const movement = this.calculatePointersDistance( this._touchCurrent[ 0 ], event ) * this._devPxRatio; + + if ( movement >= this._switchSensibility ) { + + //singleMove + this._input = INPUT.ONE_FINGER; + this.updateTouchEvent( event ); + + this.onSinglePanStart( event, 'ROTATE' ); + break; + + } + + break; + + case INPUT.TWO_FINGER: + + //rotate/pan/pinchMove + this.updateTouchEvent( event ); + + this.onRotateMove(); + this.onPinchMove(); + this.onDoublePanMove(); + + break; + + case INPUT.MULT_FINGER: + + //multMove + this.updateTouchEvent( event ); + + this.onTriplePanMove( event ); + break; + + } + + } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) { + + let modifier = null; + + if ( event.ctrlKey || event.metaKey ) { + + modifier = 'CTRL'; + + } else if ( event.shiftKey ) { + + modifier = 'SHIFT'; + + } + + const mouseOpState = this.getOpStateFromAction( this._button, modifier ); + + if ( mouseOpState != null ) { + + this.onSinglePanMove( event, mouseOpState ); + + } + + } + + //checkDistance + if ( this._downValid ) { + + const movement = this.calculatePointersDistance( this._downEvents[ this._downEvents.length - 1 ], event ) * this._devPxRatio; + if ( movement > this._movementThreshold ) { + + this._downValid = false; + + } + + } + +} + +function onPointerUp( event ) { + + if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) { + + const nTouch = this._touchCurrent.length; + + for ( let i = 0; i < nTouch; i ++ ) { + + if ( this._touchCurrent[ i ].pointerId == event.pointerId ) { + + this._touchCurrent.splice( i, 1 ); + this._touchStart.splice( i, 1 ); + break; + + } + + } + + switch ( this._input ) { + + case INPUT.ONE_FINGER: + case INPUT.ONE_FINGER_SWITCHED: + + //singleEnd + window.removeEventListener( 'pointermove', this._onPointerMove ); + window.removeEventListener( 'pointerup', this._onPointerUp ); + + this._input = INPUT.NONE; + this.onSinglePanEnd(); + + break; + + case INPUT.TWO_FINGER: + + //doubleEnd + this.onDoublePanEnd( event ); + this.onPinchEnd( event ); + this.onRotateEnd( event ); + + //switching to singleStart + this._input = INPUT.ONE_FINGER_SWITCHED; + + break; + + case INPUT.MULT_FINGER: + + if ( this._touchCurrent.length == 0 ) { + + window.removeEventListener( 'pointermove', this._onPointerMove ); + window.removeEventListener( 'pointerup', this._onPointerUp ); + + //multCancel + this._input = INPUT.NONE; + this.onTriplePanEnd(); + + } + + break; + + } + + } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) { + + window.removeEventListener( 'pointermove', this._onPointerMove ); + window.removeEventListener( 'pointerup', this._onPointerUp ); + + this._input = INPUT.NONE; + this.onSinglePanEnd(); + this._button = - 1; + + } + + if ( event.isPrimary ) { + + if ( this._downValid ) { + + const downTime = event.timeStamp - this._downEvents[ this._downEvents.length - 1 ].timeStamp; + + if ( downTime <= this._maxDownTime ) { + + if ( this._nclicks == 0 ) { + + //first valid click detected + this._nclicks = 1; + this._clickStart = performance.now(); + + } else { + + const clickInterval = event.timeStamp - this._clickStart; + const movement = this.calculatePointersDistance( this._downEvents[ 1 ], this._downEvents[ 0 ] ) * this._devPxRatio; + + if ( clickInterval <= this._maxInterval && movement <= this._posThreshold ) { + + //second valid click detected + //fire double tap and reset values + this._nclicks = 0; + this._downEvents.splice( 0, this._downEvents.length ); + this.onDoubleTap( event ); + + } else { + + //new 'first click' + this._nclicks = 1; + this._downEvents.shift(); + this._clickStart = performance.now(); + + } + + } + + } else { + + this._downValid = false; + this._nclicks = 0; + this._downEvents.splice( 0, this._downEvents.length ); + + } + + } else { + + this._nclicks = 0; + this._downEvents.splice( 0, this._downEvents.length ); + + } + + } + +} + +function onWheel( event ) { + + if ( this.enabled && this.enableZoom ) { + + let modifier = null; + + if ( event.ctrlKey || event.metaKey ) { + + modifier = 'CTRL'; + + } else if ( event.shiftKey ) { + + modifier = 'SHIFT'; + + } + + const mouseOp = this.getOpFromAction( 'WHEEL', modifier ); + + if ( mouseOp != null ) { + + event.preventDefault(); + this.dispatchEvent( _startEvent ); + + const notchDeltaY = 125; //distance of one notch of mouse wheel + let sgn = event.deltaY / notchDeltaY; + + let size = 1; + + if ( sgn > 0 ) { + + size = 1 / this.scaleFactor; + + } else if ( sgn < 0 ) { + + size = this.scaleFactor; + + } + + switch ( mouseOp ) { + + case 'ZOOM': + + this.updateTbState( STATE.SCALE, true ); + + if ( sgn > 0 ) { + + size = 1 / ( Math.pow( this.scaleFactor, sgn ) ); + + } else if ( sgn < 0 ) { + + size = Math.pow( this.scaleFactor, - sgn ); + + } + + if ( this.cursorZoom && this.enablePan ) { + + let scalePoint; + + if ( this.camera.isOrthographicCamera ) { + + scalePoint = this.unprojectOnTbPlane( this.camera, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.camera.quaternion ).multiplyScalar( 1 / this.camera.zoom ).add( this._gizmos.position ); + + } else if ( this.camera.isPerspectiveCamera ) { + + scalePoint = this.unprojectOnTbPlane( this.camera, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.camera.quaternion ).add( this._gizmos.position ); + + } + + this.applyTransformMatrix( this.scale( size, scalePoint ) ); + + } else { + + this.applyTransformMatrix( this.scale( size, this._gizmos.position ) ); + + } + + if ( this._grid != null ) { + + this.disposeGrid(); + this.drawGrid(); + + } + + this.updateTbState( STATE.IDLE, false ); + + this.dispatchEvent( _changeEvent ); + this.dispatchEvent( _endEvent ); + + break; + + case 'FOV': + + if ( this.camera.isPerspectiveCamera ) { + + this.updateTbState( STATE.FOV, true ); + + + //Vertigo effect + + // fov / 2 + // |\ + // | \ + // | \ + // x | \ + // | \ + // | \ + // | _ _ _\ + // y + + //check for iOs shift shortcut + if ( event.deltaX != 0 ) { + + sgn = event.deltaX / notchDeltaY; + + size = 1; + + if ( sgn > 0 ) { + + size = 1 / ( Math.pow( this.scaleFactor, sgn ) ); + + } else if ( sgn < 0 ) { + + size = Math.pow( this.scaleFactor, - sgn ); + + } + + } + + this._v3_1.setFromMatrixPosition( this._cameraMatrixState ); + const x = this._v3_1.distanceTo( this._gizmos.position ); + let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed + + //check min and max distance + xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance ); + + const y = x * Math.tan( MathUtils.DEG2RAD * this.camera.fov * 0.5 ); + + //calculate new fov + let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 ); + + //check min and max fov + if ( newFov > this.maxFov ) { + + newFov = this.maxFov; + + } else if ( newFov < this.minFov ) { + + newFov = this.minFov; + + } + + const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) ); + size = x / newDistance; + + this.setFov( newFov ); + this.applyTransformMatrix( this.scale( size, this._gizmos.position, false ) ); + + } + + if ( this._grid != null ) { + + this.disposeGrid(); + this.drawGrid(); + + } + + this.updateTbState( STATE.IDLE, false ); + + this.dispatchEvent( _changeEvent ); + this.dispatchEvent( _endEvent ); + + break; + + } + + } + + } + +} + +export { ArcballControls }; diff --git a/renderer/jsm/controls/DragControls.js b/renderer/jsm/controls/DragControls.js new file mode 100644 index 0000000..4db4813 --- /dev/null +++ b/renderer/jsm/controls/DragControls.js @@ -0,0 +1,220 @@ +import { + EventDispatcher, + Matrix4, + Plane, + Raycaster, + Vector2, + Vector3 +} from 'three'; + +const _plane = new Plane(); +const _raycaster = new Raycaster(); + +const _pointer = new Vector2(); +const _offset = new Vector3(); +const _intersection = new Vector3(); +const _worldPosition = new Vector3(); +const _inverseMatrix = new Matrix4(); + +class DragControls extends EventDispatcher { + + constructor( _objects, _camera, _domElement ) { + + super(); + + _domElement.style.touchAction = 'none'; // disable touch scroll + + let _selected = null, _hovered = null; + + const _intersections = []; + + // + + const scope = this; + + function activate() { + + _domElement.addEventListener( 'pointermove', onPointerMove ); + _domElement.addEventListener( 'pointerdown', onPointerDown ); + _domElement.addEventListener( 'pointerup', onPointerCancel ); + _domElement.addEventListener( 'pointerleave', onPointerCancel ); + + } + + function deactivate() { + + _domElement.removeEventListener( 'pointermove', onPointerMove ); + _domElement.removeEventListener( 'pointerdown', onPointerDown ); + _domElement.removeEventListener( 'pointerup', onPointerCancel ); + _domElement.removeEventListener( 'pointerleave', onPointerCancel ); + + _domElement.style.cursor = ''; + + } + + function dispose() { + + deactivate(); + + } + + function getObjects() { + + return _objects; + + } + + function getRaycaster() { + + return _raycaster; + + } + + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + updatePointer( event ); + + _raycaster.setFromCamera( _pointer, _camera ); + + if ( _selected ) { + + if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) { + + _selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) ); + + } + + scope.dispatchEvent( { type: 'drag', object: _selected } ); + + return; + + } + + // hover support + + if ( event.pointerType === 'mouse' || event.pointerType === 'pen' ) { + + _intersections.length = 0; + + _raycaster.setFromCamera( _pointer, _camera ); + _raycaster.intersectObjects( _objects, true, _intersections ); + + if ( _intersections.length > 0 ) { + + const object = _intersections[ 0 ].object; + + _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( object.matrixWorld ) ); + + if ( _hovered !== object && _hovered !== null ) { + + scope.dispatchEvent( { type: 'hoveroff', object: _hovered } ); + + _domElement.style.cursor = 'auto'; + _hovered = null; + + } + + if ( _hovered !== object ) { + + scope.dispatchEvent( { type: 'hoveron', object: object } ); + + _domElement.style.cursor = 'pointer'; + _hovered = object; + + } + + } else { + + if ( _hovered !== null ) { + + scope.dispatchEvent( { type: 'hoveroff', object: _hovered } ); + + _domElement.style.cursor = 'auto'; + _hovered = null; + + } + + } + + } + + } + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + updatePointer( event ); + + _intersections.length = 0; + + _raycaster.setFromCamera( _pointer, _camera ); + _raycaster.intersectObjects( _objects, true, _intersections ); + + if ( _intersections.length > 0 ) { + + _selected = ( scope.transformGroup === true ) ? _objects[ 0 ] : _intersections[ 0 ].object; + + _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) ); + + if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) { + + _inverseMatrix.copy( _selected.parent.matrixWorld ).invert(); + _offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) ); + + } + + _domElement.style.cursor = 'move'; + + scope.dispatchEvent( { type: 'dragstart', object: _selected } ); + + } + + + } + + function onPointerCancel() { + + if ( scope.enabled === false ) return; + + if ( _selected ) { + + scope.dispatchEvent( { type: 'dragend', object: _selected } ); + + _selected = null; + + } + + _domElement.style.cursor = _hovered ? 'pointer' : 'auto'; + + } + + function updatePointer( event ) { + + const rect = _domElement.getBoundingClientRect(); + + _pointer.x = ( event.clientX - rect.left ) / rect.width * 2 - 1; + _pointer.y = - ( event.clientY - rect.top ) / rect.height * 2 + 1; + + } + + activate(); + + // API + + this.enabled = true; + this.transformGroup = false; + + this.activate = activate; + this.deactivate = deactivate; + this.dispose = dispose; + this.getObjects = getObjects; + this.getRaycaster = getRaycaster; + + } + +} + +export { DragControls }; diff --git a/renderer/jsm/controls/FirstPersonControls.js b/renderer/jsm/controls/FirstPersonControls.js new file mode 100644 index 0000000..0d03421 --- /dev/null +++ b/renderer/jsm/controls/FirstPersonControls.js @@ -0,0 +1,325 @@ +import { + MathUtils, + Spherical, + Vector3 +} from 'three'; + +const _lookDirection = new Vector3(); +const _spherical = new Spherical(); +const _target = new Vector3(); + +class FirstPersonControls { + + constructor( object, domElement ) { + + this.object = object; + this.domElement = domElement; + + // API + + this.enabled = true; + + this.movementSpeed = 1.0; + this.lookSpeed = 0.005; + + this.lookVertical = true; + this.autoForward = false; + + this.activeLook = true; + + this.heightSpeed = false; + this.heightCoef = 1.0; + this.heightMin = 0.0; + this.heightMax = 1.0; + + this.constrainVertical = false; + this.verticalMin = 0; + this.verticalMax = Math.PI; + + this.mouseDragOn = false; + + // internals + + this.autoSpeedFactor = 0.0; + + this.pointerX = 0; + this.pointerY = 0; + + this.moveForward = false; + this.moveBackward = false; + this.moveLeft = false; + this.moveRight = false; + + this.viewHalfX = 0; + this.viewHalfY = 0; + + // private variables + + let lat = 0; + let lon = 0; + + // + + this.handleResize = function () { + + if ( this.domElement === document ) { + + this.viewHalfX = window.innerWidth / 2; + this.viewHalfY = window.innerHeight / 2; + + } else { + + this.viewHalfX = this.domElement.offsetWidth / 2; + this.viewHalfY = this.domElement.offsetHeight / 2; + + } + + }; + + this.onPointerDown = function ( event ) { + + if ( this.domElement !== document ) { + + this.domElement.focus(); + + } + + if ( this.activeLook ) { + + switch ( event.button ) { + + case 0: this.moveForward = true; break; + case 2: this.moveBackward = true; break; + + } + + } + + this.mouseDragOn = true; + + }; + + this.onPointerUp = function ( event ) { + + if ( this.activeLook ) { + + switch ( event.button ) { + + case 0: this.moveForward = false; break; + case 2: this.moveBackward = false; break; + + } + + } + + this.mouseDragOn = false; + + }; + + this.onPointerMove = function ( event ) { + + if ( this.domElement === document ) { + + this.pointerX = event.pageX - this.viewHalfX; + this.pointerY = event.pageY - this.viewHalfY; + + } else { + + this.pointerX = event.pageX - this.domElement.offsetLeft - this.viewHalfX; + this.pointerY = event.pageY - this.domElement.offsetTop - this.viewHalfY; + + } + + }; + + this.onKeyDown = function ( event ) { + + switch ( event.code ) { + + case 'ArrowUp': + case 'KeyW': this.moveForward = true; break; + + case 'ArrowLeft': + case 'KeyA': this.moveLeft = true; break; + + case 'ArrowDown': + case 'KeyS': this.moveBackward = true; break; + + case 'ArrowRight': + case 'KeyD': this.moveRight = true; break; + + case 'KeyR': this.moveUp = true; break; + case 'KeyF': this.moveDown = true; break; + + } + + }; + + this.onKeyUp = function ( event ) { + + switch ( event.code ) { + + case 'ArrowUp': + case 'KeyW': this.moveForward = false; break; + + case 'ArrowLeft': + case 'KeyA': this.moveLeft = false; break; + + case 'ArrowDown': + case 'KeyS': this.moveBackward = false; break; + + case 'ArrowRight': + case 'KeyD': this.moveRight = false; break; + + case 'KeyR': this.moveUp = false; break; + case 'KeyF': this.moveDown = false; break; + + } + + }; + + this.lookAt = function ( x, y, z ) { + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + this.object.lookAt( _target ); + + setOrientation( this ); + + return this; + + }; + + this.update = function () { + + const targetPosition = new Vector3(); + + return function update( delta ) { + + if ( this.enabled === false ) return; + + if ( this.heightSpeed ) { + + const y = MathUtils.clamp( this.object.position.y, this.heightMin, this.heightMax ); + const heightDelta = y - this.heightMin; + + this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef ); + + } else { + + this.autoSpeedFactor = 0.0; + + } + + const actualMoveSpeed = delta * this.movementSpeed; + + if ( this.moveForward || ( this.autoForward && ! this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) ); + if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed ); + + if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed ); + if ( this.moveRight ) this.object.translateX( actualMoveSpeed ); + + if ( this.moveUp ) this.object.translateY( actualMoveSpeed ); + if ( this.moveDown ) this.object.translateY( - actualMoveSpeed ); + + let actualLookSpeed = delta * this.lookSpeed; + + if ( ! this.activeLook ) { + + actualLookSpeed = 0; + + } + + let verticalLookRatio = 1; + + if ( this.constrainVertical ) { + + verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin ); + + } + + lon -= this.pointerX * actualLookSpeed; + if ( this.lookVertical ) lat -= this.pointerY * actualLookSpeed * verticalLookRatio; + + lat = Math.max( - 85, Math.min( 85, lat ) ); + + let phi = MathUtils.degToRad( 90 - lat ); + const theta = MathUtils.degToRad( lon ); + + if ( this.constrainVertical ) { + + phi = MathUtils.mapLinear( phi, 0, Math.PI, this.verticalMin, this.verticalMax ); + + } + + const position = this.object.position; + + targetPosition.setFromSphericalCoords( 1, phi, theta ).add( position ); + + this.object.lookAt( targetPosition ); + + }; + + }(); + + this.dispose = function () { + + this.domElement.removeEventListener( 'contextmenu', contextmenu ); + this.domElement.removeEventListener( 'pointerdown', _onPointerDown ); + this.domElement.removeEventListener( 'pointermove', _onPointerMove ); + this.domElement.removeEventListener( 'pointerup', _onPointerUp ); + + window.removeEventListener( 'keydown', _onKeyDown ); + window.removeEventListener( 'keyup', _onKeyUp ); + + }; + + const _onPointerMove = this.onPointerMove.bind( this ); + const _onPointerDown = this.onPointerDown.bind( this ); + const _onPointerUp = this.onPointerUp.bind( this ); + const _onKeyDown = this.onKeyDown.bind( this ); + const _onKeyUp = this.onKeyUp.bind( this ); + + this.domElement.addEventListener( 'contextmenu', contextmenu ); + this.domElement.addEventListener( 'pointerdown', _onPointerDown ); + this.domElement.addEventListener( 'pointermove', _onPointerMove ); + this.domElement.addEventListener( 'pointerup', _onPointerUp ); + + window.addEventListener( 'keydown', _onKeyDown ); + window.addEventListener( 'keyup', _onKeyUp ); + + function setOrientation( controls ) { + + const quaternion = controls.object.quaternion; + + _lookDirection.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + _spherical.setFromVector3( _lookDirection ); + + lat = 90 - MathUtils.radToDeg( _spherical.phi ); + lon = MathUtils.radToDeg( _spherical.theta ); + + } + + this.handleResize(); + + setOrientation( this ); + + } + +} + +function contextmenu( event ) { + + event.preventDefault(); + +} + +export { FirstPersonControls }; diff --git a/renderer/jsm/controls/FlyControls.js b/renderer/jsm/controls/FlyControls.js new file mode 100644 index 0000000..0c6bb3a --- /dev/null +++ b/renderer/jsm/controls/FlyControls.js @@ -0,0 +1,284 @@ +import { + EventDispatcher, + Quaternion, + Vector3 +} from 'three'; + +const _changeEvent = { type: 'change' }; + +class FlyControls extends EventDispatcher { + + constructor( object, domElement ) { + + super(); + + this.object = object; + this.domElement = domElement; + + // API + + this.movementSpeed = 1.0; + this.rollSpeed = 0.005; + + this.dragToLook = false; + this.autoForward = false; + + // disable default target object behavior + + // internals + + const scope = this; + + const EPS = 0.000001; + + const lastQuaternion = new Quaternion(); + const lastPosition = new Vector3(); + + this.tmpQuaternion = new Quaternion(); + + this.status = 0; + + this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 }; + this.moveVector = new Vector3( 0, 0, 0 ); + this.rotationVector = new Vector3( 0, 0, 0 ); + + this.keydown = function ( event ) { + + if ( event.altKey ) { + + return; + + } + + switch ( event.code ) { + + case 'ShiftLeft': + case 'ShiftRight': this.movementSpeedMultiplier = .1; break; + + case 'KeyW': this.moveState.forward = 1; break; + case 'KeyS': this.moveState.back = 1; break; + + case 'KeyA': this.moveState.left = 1; break; + case 'KeyD': this.moveState.right = 1; break; + + case 'KeyR': this.moveState.up = 1; break; + case 'KeyF': this.moveState.down = 1; break; + + case 'ArrowUp': this.moveState.pitchUp = 1; break; + case 'ArrowDown': this.moveState.pitchDown = 1; break; + + case 'ArrowLeft': this.moveState.yawLeft = 1; break; + case 'ArrowRight': this.moveState.yawRight = 1; break; + + case 'KeyQ': this.moveState.rollLeft = 1; break; + case 'KeyE': this.moveState.rollRight = 1; break; + + } + + this.updateMovementVector(); + this.updateRotationVector(); + + }; + + this.keyup = function ( event ) { + + switch ( event.code ) { + + case 'ShiftLeft': + case 'ShiftRight': this.movementSpeedMultiplier = 1; break; + + case 'KeyW': this.moveState.forward = 0; break; + case 'KeyS': this.moveState.back = 0; break; + + case 'KeyA': this.moveState.left = 0; break; + case 'KeyD': this.moveState.right = 0; break; + + case 'KeyR': this.moveState.up = 0; break; + case 'KeyF': this.moveState.down = 0; break; + + case 'ArrowUp': this.moveState.pitchUp = 0; break; + case 'ArrowDown': this.moveState.pitchDown = 0; break; + + case 'ArrowLeft': this.moveState.yawLeft = 0; break; + case 'ArrowRight': this.moveState.yawRight = 0; break; + + case 'KeyQ': this.moveState.rollLeft = 0; break; + case 'KeyE': this.moveState.rollRight = 0; break; + + } + + this.updateMovementVector(); + this.updateRotationVector(); + + }; + + this.pointerdown = function ( event ) { + + if ( this.dragToLook ) { + + this.status ++; + + } else { + + switch ( event.button ) { + + case 0: this.moveState.forward = 1; break; + case 2: this.moveState.back = 1; break; + + } + + this.updateMovementVector(); + + } + + }; + + this.pointermove = function ( event ) { + + if ( ! this.dragToLook || this.status > 0 ) { + + const container = this.getContainerDimensions(); + const halfWidth = container.size[ 0 ] / 2; + const halfHeight = container.size[ 1 ] / 2; + + this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth; + this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight; + + this.updateRotationVector(); + + } + + }; + + this.pointerup = function ( event ) { + + if ( this.dragToLook ) { + + this.status --; + + this.moveState.yawLeft = this.moveState.pitchDown = 0; + + } else { + + switch ( event.button ) { + + case 0: this.moveState.forward = 0; break; + case 2: this.moveState.back = 0; break; + + } + + this.updateMovementVector(); + + } + + this.updateRotationVector(); + + }; + + this.update = function ( delta ) { + + const moveMult = delta * scope.movementSpeed; + const rotMult = delta * scope.rollSpeed; + + scope.object.translateX( scope.moveVector.x * moveMult ); + scope.object.translateY( scope.moveVector.y * moveMult ); + scope.object.translateZ( scope.moveVector.z * moveMult ); + + scope.tmpQuaternion.set( scope.rotationVector.x * rotMult, scope.rotationVector.y * rotMult, scope.rotationVector.z * rotMult, 1 ).normalize(); + scope.object.quaternion.multiply( scope.tmpQuaternion ); + + if ( + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS + ) { + + scope.dispatchEvent( _changeEvent ); + lastQuaternion.copy( scope.object.quaternion ); + lastPosition.copy( scope.object.position ); + + } + + }; + + this.updateMovementVector = function () { + + const forward = ( this.moveState.forward || ( this.autoForward && ! this.moveState.back ) ) ? 1 : 0; + + this.moveVector.x = ( - this.moveState.left + this.moveState.right ); + this.moveVector.y = ( - this.moveState.down + this.moveState.up ); + this.moveVector.z = ( - forward + this.moveState.back ); + + //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] ); + + }; + + this.updateRotationVector = function () { + + this.rotationVector.x = ( - this.moveState.pitchDown + this.moveState.pitchUp ); + this.rotationVector.y = ( - this.moveState.yawRight + this.moveState.yawLeft ); + this.rotationVector.z = ( - this.moveState.rollRight + this.moveState.rollLeft ); + + //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] ); + + }; + + this.getContainerDimensions = function () { + + if ( this.domElement != document ) { + + return { + size: [ this.domElement.offsetWidth, this.domElement.offsetHeight ], + offset: [ this.domElement.offsetLeft, this.domElement.offsetTop ] + }; + + } else { + + return { + size: [ window.innerWidth, window.innerHeight ], + offset: [ 0, 0 ] + }; + + } + + }; + + this.dispose = function () { + + this.domElement.removeEventListener( 'contextmenu', contextmenu ); + this.domElement.removeEventListener( 'pointerdown', _pointerdown ); + this.domElement.removeEventListener( 'pointermove', _pointermove ); + this.domElement.removeEventListener( 'pointerup', _pointerup ); + + window.removeEventListener( 'keydown', _keydown ); + window.removeEventListener( 'keyup', _keyup ); + + }; + + const _pointermove = this.pointermove.bind( this ); + const _pointerdown = this.pointerdown.bind( this ); + const _pointerup = this.pointerup.bind( this ); + const _keydown = this.keydown.bind( this ); + const _keyup = this.keyup.bind( this ); + + this.domElement.addEventListener( 'contextmenu', contextmenu ); + this.domElement.addEventListener( 'pointerdown', _pointerdown ); + this.domElement.addEventListener( 'pointermove', _pointermove ); + this.domElement.addEventListener( 'pointerup', _pointerup ); + + window.addEventListener( 'keydown', _keydown ); + window.addEventListener( 'keyup', _keyup ); + + this.updateMovementVector(); + this.updateRotationVector(); + + } + +} + +function contextmenu( event ) { + + event.preventDefault(); + +} + +export { FlyControls }; diff --git a/renderer/jsm/controls/OrbitControls.js b/renderer/jsm/controls/OrbitControls.js new file mode 100644 index 0000000..42eae81 --- /dev/null +++ b/renderer/jsm/controls/OrbitControls.js @@ -0,0 +1,1287 @@ +import { + EventDispatcher, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3 +} from 'three'; + +// This set of controls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). +// +// Orbit - left mouse / touch: one-finger move +// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish +// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move + +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; + +class OrbitControls extends EventDispatcher { + + constructor( object, domElement ) { + + super(); + + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll + + // Set to false to disable this control + this.enabled = true; + + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); + + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; + + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; + + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians + + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians + + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; + + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; + + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; + + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push + + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; + + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; + + // the target DOM element for key events + this._domElementKeyEvents = null; + + // + // public methods + // + + this.getPolarAngle = function () { + + return spherical.phi; + + }; + + this.getAzimuthalAngle = function () { + + return spherical.theta; + + }; + + this.getDistance = function () { + + return this.object.position.distanceTo( this.target ); + + }; + + this.listenToKeyEvents = function ( domElement ) { + + domElement.addEventListener( 'keydown', onKeyDown ); + this._domElementKeyEvents = domElement; + + }; + + this.saveState = function () { + + scope.target0.copy( scope.target ); + scope.position0.copy( scope.object.position ); + scope.zoom0 = scope.object.zoom; + + }; + + this.reset = function () { + + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.zoom = scope.zoom0; + + scope.object.updateProjectionMatrix(); + scope.dispatchEvent( _changeEvent ); + + scope.update(); + + state = STATE.NONE; + + }; + + // this method is exposed, but perhaps it would be better if we can make it private... + this.update = function () { + + const offset = new Vector3(); + + // so camera.up is the orbit axis + const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + const quatInverse = quat.clone().invert(); + + const lastPosition = new Vector3(); + const lastQuaternion = new Quaternion(); + + const twoPI = 2 * Math.PI; + + return function update() { + + const position = scope.object.position; + + offset.copy( position ).sub( scope.target ); + + // rotate offset to "y-axis-is-up" space + offset.applyQuaternion( quat ); + + // angle from z-axis around y-axis + spherical.setFromVector3( offset ); + + if ( scope.autoRotate && state === STATE.NONE ) { + + rotateLeft( getAutoRotationAngle() ); + + } + + if ( scope.enableDamping ) { + + spherical.theta += sphericalDelta.theta * scope.dampingFactor; + spherical.phi += sphericalDelta.phi * scope.dampingFactor; + + } else { + + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; + + } + + // restrict theta to be between desired limits + + let min = scope.minAzimuthAngle; + let max = scope.maxAzimuthAngle; + + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI; + + if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI; + + if ( min <= max ) { + + spherical.theta = Math.max( min, Math.min( max, spherical.theta ) ); + + } else { + + spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, spherical.theta ) : + Math.min( max, spherical.theta ); + + } + + } + + // restrict phi to be between desired limits + spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); + + spherical.makeSafe(); + + + spherical.radius *= scale; + + // restrict radius to be between desired limits + spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); + + // move target to panned location + + if ( scope.enableDamping === true ) { + + scope.target.addScaledVector( panOffset, scope.dampingFactor ); + + } else { + + scope.target.add( panOffset ); + + } + + offset.setFromSpherical( spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + offset.applyQuaternion( quatInverse ); + + position.copy( scope.target ).add( offset ); + + scope.object.lookAt( scope.target ); + + if ( scope.enableDamping === true ) { + + sphericalDelta.theta *= ( 1 - scope.dampingFactor ); + sphericalDelta.phi *= ( 1 - scope.dampingFactor ); + + panOffset.multiplyScalar( 1 - scope.dampingFactor ); + + } else { + + sphericalDelta.set( 0, 0, 0 ); + + panOffset.set( 0, 0, 0 ); + + } + + scale = 1; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + lastPosition.distanceToSquared( scope.object.position ) > EPS || + 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastQuaternion.copy( scope.object.quaternion ); + zoomChanged = false; + + return true; + + } + + return false; + + }; + + }(); + + this.dispose = function () { + + scope.domElement.removeEventListener( 'contextmenu', onContextMenu ); + + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + + if ( scope._domElementKeyEvents !== null ) { + + scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); + + } + + //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? + + }; + + // + // internals + // + + const scope = this; + + const STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 + }; + + let state = STATE.NONE; + + const EPS = 0.000001; + + // current position in spherical coordinates + const spherical = new Spherical(); + const sphericalDelta = new Spherical(); + + let scale = 1; + const panOffset = new Vector3(); + let zoomChanged = false; + + const rotateStart = new Vector2(); + const rotateEnd = new Vector2(); + const rotateDelta = new Vector2(); + + const panStart = new Vector2(); + const panEnd = new Vector2(); + const panDelta = new Vector2(); + + const dollyStart = new Vector2(); + const dollyEnd = new Vector2(); + const dollyDelta = new Vector2(); + + const pointers = []; + const pointerPositions = {}; + + function getAutoRotationAngle() { + + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; + + } + + function getZoomScale() { + + return Math.pow( 0.95, scope.zoomSpeed ); + + } + + function rotateLeft( angle ) { + + sphericalDelta.theta -= angle; + + } + + function rotateUp( angle ) { + + sphericalDelta.phi -= angle; + + } + + const panLeft = function () { + + const v = new Vector3(); + + return function panLeft( distance, objectMatrix ) { + + v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + v.multiplyScalar( - distance ); + + panOffset.add( v ); + + }; + + }(); + + const panUp = function () { + + const v = new Vector3(); + + return function panUp( distance, objectMatrix ) { + + if ( scope.screenSpacePanning === true ) { + + v.setFromMatrixColumn( objectMatrix, 1 ); + + } else { + + v.setFromMatrixColumn( objectMatrix, 0 ); + v.crossVectors( scope.object.up, v ); + + } + + v.multiplyScalar( distance ); + + panOffset.add( v ); + + }; + + }(); + + // deltaX and deltaY are in pixels; right and down are positive + const pan = function () { + + const offset = new Vector3(); + + return function pan( deltaX, deltaY ) { + + const element = scope.domElement; + + if ( scope.object.isPerspectiveCamera ) { + + // perspective + const position = scope.object.position; + offset.copy( position ).sub( scope.target ); + let targetDistance = offset.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); + panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); + + } else if ( scope.object.isOrthographicCamera ) { + + // orthographic + panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); + panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); + + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + scope.enablePan = false; + + } + + }; + + }(); + + function dollyOut( dollyScale ) { + + if ( scope.object.isPerspectiveCamera ) { + + scale /= dollyScale; + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; + + } + + } + + function dollyIn( dollyScale ) { + + if ( scope.object.isPerspectiveCamera ) { + + scale *= dollyScale; + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + scope.enableZoom = false; + + } + + } + + // + // event callbacks - update the object state + // + + function handleMouseDownRotate( event ) { + + rotateStart.set( event.clientX, event.clientY ); + + } + + function handleMouseDownDolly( event ) { + + dollyStart.set( event.clientX, event.clientY ); + + } + + function handleMouseDownPan( event ) { + + panStart.set( event.clientX, event.clientY ); + + } + + function handleMouseMoveRotate( event ) { + + rotateEnd.set( event.clientX, event.clientY ); + + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + + const element = scope.domElement; + + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + + rotateStart.copy( rotateEnd ); + + scope.update(); + + } + + function handleMouseMoveDolly( event ) { + + dollyEnd.set( event.clientX, event.clientY ); + + dollyDelta.subVectors( dollyEnd, dollyStart ); + + if ( dollyDelta.y > 0 ) { + + dollyOut( getZoomScale() ); + + } else if ( dollyDelta.y < 0 ) { + + dollyIn( getZoomScale() ); + + } + + dollyStart.copy( dollyEnd ); + + scope.update(); + + } + + function handleMouseMovePan( event ) { + + panEnd.set( event.clientX, event.clientY ); + + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + + pan( panDelta.x, panDelta.y ); + + panStart.copy( panEnd ); + + scope.update(); + + } + + function handleMouseWheel( event ) { + + if ( event.deltaY < 0 ) { + + dollyIn( getZoomScale() ); + + } else if ( event.deltaY > 0 ) { + + dollyOut( getZoomScale() ); + + } + + scope.update(); + + } + + function handleKeyDown( event ) { + + let needsUpdate = false; + + switch ( event.code ) { + + case scope.keys.UP: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + + } else { + + pan( 0, scope.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case scope.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + + } else { + + pan( 0, - scope.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case scope.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + + } else { + + pan( scope.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + case scope.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight ); + + } else { + + pan( - scope.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + } + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + scope.update(); + + } + + + } + + function handleTouchStartRotate() { + + if ( pointers.length === 1 ) { + + rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); + + } else { + + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); + + rotateStart.set( x, y ); + + } + + } + + function handleTouchStartPan() { + + if ( pointers.length === 1 ) { + + panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY ); + + } else { + + const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX ); + const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY ); + + panStart.set( x, y ); + + } + + } + + function handleTouchStartDolly() { + + const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX; + const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + dollyStart.set( 0, distance ); + + } + + function handleTouchStartDollyPan() { + + if ( scope.enableZoom ) handleTouchStartDolly(); + + if ( scope.enablePan ) handleTouchStartPan(); + + } + + function handleTouchStartDollyRotate() { + + if ( scope.enableZoom ) handleTouchStartDolly(); + + if ( scope.enableRotate ) handleTouchStartRotate(); + + } + + function handleTouchMoveRotate( event ) { + + if ( pointers.length == 1 ) { + + rotateEnd.set( event.pageX, event.pageY ); + + } else { + + const position = getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + rotateEnd.set( x, y ); + + } + + rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed ); + + const element = scope.domElement; + + rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height + + rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); + + rotateStart.copy( rotateEnd ); + + } + + function handleTouchMovePan( event ) { + + if ( pointers.length === 1 ) { + + panEnd.set( event.pageX, event.pageY ); + + } else { + + const position = getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + panEnd.set( x, y ); + + } + + panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed ); + + pan( panDelta.x, panDelta.y ); + + panStart.copy( panEnd ); + + } + + function handleTouchMoveDolly( event ) { + + const position = getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + dollyEnd.set( 0, distance ); + + dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) ); + + dollyOut( dollyDelta.y ); + + dollyStart.copy( dollyEnd ); + + } + + function handleTouchMoveDollyPan( event ) { + + if ( scope.enableZoom ) handleTouchMoveDolly( event ); + + if ( scope.enablePan ) handleTouchMovePan( event ); + + } + + function handleTouchMoveDollyRotate( event ) { + + if ( scope.enableZoom ) handleTouchMoveDolly( event ); + + if ( scope.enableRotate ) handleTouchMoveRotate( event ); + + } + + // + // event handlers - FSM: listen for events and reset state + // + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + if ( pointers.length === 0 ) { + + scope.domElement.setPointerCapture( event.pointerId ); + + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); + + } + + // + + addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + onTouchStart( event ); + + } else { + + onMouseDown( event ); + + } + + } + + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchMove( event ); + + } else { + + onMouseMove( event ); + + } + + } + + function onPointerUp( event ) { + + removePointer( event ); + + if ( pointers.length === 0 ) { + + scope.domElement.releasePointerCapture( event.pointerId ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + } + + scope.dispatchEvent( _endEvent ); + + state = STATE.NONE; + + } + + function onPointerCancel( event ) { + + removePointer( event ); + + } + + function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = scope.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = scope.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = scope.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; + + } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( scope.enableZoom === false ) return; + + handleMouseDownDolly( event ); + + state = STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( scope.enablePan === false ) return; + + handleMouseDownPan( event ); + + state = STATE.PAN; + + } else { + + if ( scope.enableRotate === false ) return; + + handleMouseDownRotate( event ); + + state = STATE.ROTATE; + + } + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( scope.enableRotate === false ) return; + + handleMouseDownRotate( event ); + + state = STATE.ROTATE; + + } else { + + if ( scope.enablePan === false ) return; + + handleMouseDownPan( event ); + + state = STATE.PAN; + + } + + break; + + default: + + state = STATE.NONE; + + } + + if ( state !== STATE.NONE ) { + + scope.dispatchEvent( _startEvent ); + + } + + } + + function onMouseMove( event ) { + + switch ( state ) { + + case STATE.ROTATE: + + if ( scope.enableRotate === false ) return; + + handleMouseMoveRotate( event ); + + break; + + case STATE.DOLLY: + + if ( scope.enableZoom === false ) return; + + handleMouseMoveDolly( event ); + + break; + + case STATE.PAN: + + if ( scope.enablePan === false ) return; + + handleMouseMovePan( event ); + + break; + + } + + } + + function onMouseWheel( event ) { + + if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return; + + event.preventDefault(); + + scope.dispatchEvent( _startEvent ); + + handleMouseWheel( event ); + + scope.dispatchEvent( _endEvent ); + + } + + function onKeyDown( event ) { + + if ( scope.enabled === false || scope.enablePan === false ) return; + + handleKeyDown( event ); + + } + + function onTouchStart( event ) { + + trackPointer( event ); + + switch ( pointers.length ) { + + case 1: + + switch ( scope.touches.ONE ) { + + case TOUCH.ROTATE: + + if ( scope.enableRotate === false ) return; + + handleTouchStartRotate(); + + state = STATE.TOUCH_ROTATE; + + break; + + case TOUCH.PAN: + + if ( scope.enablePan === false ) return; + + handleTouchStartPan(); + + state = STATE.TOUCH_PAN; + + break; + + default: + + state = STATE.NONE; + + } + + break; + + case 2: + + switch ( scope.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( scope.enableZoom === false && scope.enablePan === false ) return; + + handleTouchStartDollyPan(); + + state = STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( scope.enableZoom === false && scope.enableRotate === false ) return; + + handleTouchStartDollyRotate(); + + state = STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + state = STATE.NONE; + + } + + break; + + default: + + state = STATE.NONE; + + } + + if ( state !== STATE.NONE ) { + + scope.dispatchEvent( _startEvent ); + + } + + } + + function onTouchMove( event ) { + + trackPointer( event ); + + switch ( state ) { + + case STATE.TOUCH_ROTATE: + + if ( scope.enableRotate === false ) return; + + handleTouchMoveRotate( event ); + + scope.update(); + + break; + + case STATE.TOUCH_PAN: + + if ( scope.enablePan === false ) return; + + handleTouchMovePan( event ); + + scope.update(); + + break; + + case STATE.TOUCH_DOLLY_PAN: + + if ( scope.enableZoom === false && scope.enablePan === false ) return; + + handleTouchMoveDollyPan( event ); + + scope.update(); + + break; + + case STATE.TOUCH_DOLLY_ROTATE: + + if ( scope.enableZoom === false && scope.enableRotate === false ) return; + + handleTouchMoveDollyRotate( event ); + + scope.update(); + + break; + + default: + + state = STATE.NONE; + + } + + } + + function onContextMenu( event ) { + + if ( scope.enabled === false ) return; + + event.preventDefault(); + + } + + function addPointer( event ) { + + pointers.push( event ); + + } + + function removePointer( event ) { + + delete pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < pointers.length; i ++ ) { + + if ( pointers[ i ].pointerId == event.pointerId ) { + + pointers.splice( i, 1 ); + return; + + } + + } + + } + + function trackPointer( event ) { + + let position = pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + function getSecondPointerPosition( event ) { + + const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ]; + + return pointerPositions[ pointer.pointerId ]; + + } + + // + + scope.domElement.addEventListener( 'contextmenu', onContextMenu ); + + scope.domElement.addEventListener( 'pointerdown', onPointerDown ); + scope.domElement.addEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); + + // force an update at start + + this.update(); + + } + +} + + +// This set of controls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). +// This is very similar to OrbitControls, another set of touch behavior +// +// Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate +// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish +// Pan - left mouse, or arrow keys / touch: one-finger move + +class MapControls extends OrbitControls { + + constructor( object, domElement ) { + + super( object, domElement ); + + this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up + + this.mouseButtons.LEFT = MOUSE.PAN; + this.mouseButtons.RIGHT = MOUSE.ROTATE; + + this.touches.ONE = TOUCH.PAN; + this.touches.TWO = TOUCH.DOLLY_ROTATE; + + } + +} + +export { OrbitControls, MapControls }; diff --git a/renderer/jsm/controls/PointerLockControls.js b/renderer/jsm/controls/PointerLockControls.js new file mode 100644 index 0000000..9bdebd2 --- /dev/null +++ b/renderer/jsm/controls/PointerLockControls.js @@ -0,0 +1,157 @@ +import { + Euler, + EventDispatcher, + Vector3 +} from 'three'; + +const _euler = new Euler( 0, 0, 0, 'YXZ' ); +const _vector = new Vector3(); + +const _changeEvent = { type: 'change' }; +const _lockEvent = { type: 'lock' }; +const _unlockEvent = { type: 'unlock' }; + +const _PI_2 = Math.PI / 2; + +class PointerLockControls extends EventDispatcher { + + constructor( camera, domElement ) { + + super(); + + this.domElement = domElement; + this.isLocked = false; + + // Set to constrain the pitch of the camera + // Range is 0 to Math.PI radians + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians + + this.pointerSpeed = 1.0; + + const scope = this; + + function onMouseMove( event ) { + + if ( scope.isLocked === false ) return; + + const movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; + const movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; + + _euler.setFromQuaternion( camera.quaternion ); + + _euler.y -= movementX * 0.002 * scope.pointerSpeed; + _euler.x -= movementY * 0.002 * scope.pointerSpeed; + + _euler.x = Math.max( _PI_2 - scope.maxPolarAngle, Math.min( _PI_2 - scope.minPolarAngle, _euler.x ) ); + + camera.quaternion.setFromEuler( _euler ); + + scope.dispatchEvent( _changeEvent ); + + } + + function onPointerlockChange() { + + if ( scope.domElement.ownerDocument.pointerLockElement === scope.domElement ) { + + scope.dispatchEvent( _lockEvent ); + + scope.isLocked = true; + + } else { + + scope.dispatchEvent( _unlockEvent ); + + scope.isLocked = false; + + } + + } + + function onPointerlockError() { + + console.error( 'THREE.PointerLockControls: Unable to use Pointer Lock API' ); + + } + + this.connect = function () { + + scope.domElement.ownerDocument.addEventListener( 'mousemove', onMouseMove ); + scope.domElement.ownerDocument.addEventListener( 'pointerlockchange', onPointerlockChange ); + scope.domElement.ownerDocument.addEventListener( 'pointerlockerror', onPointerlockError ); + + }; + + this.disconnect = function () { + + scope.domElement.ownerDocument.removeEventListener( 'mousemove', onMouseMove ); + scope.domElement.ownerDocument.removeEventListener( 'pointerlockchange', onPointerlockChange ); + scope.domElement.ownerDocument.removeEventListener( 'pointerlockerror', onPointerlockError ); + + }; + + this.dispose = function () { + + this.disconnect(); + + }; + + this.getObject = function () { // retaining this method for backward compatibility + + return camera; + + }; + + this.getDirection = function () { + + const direction = new Vector3( 0, 0, - 1 ); + + return function ( v ) { + + return v.copy( direction ).applyQuaternion( camera.quaternion ); + + }; + + }(); + + this.moveForward = function ( distance ) { + + // move forward parallel to the xz-plane + // assumes camera.up is y-up + + _vector.setFromMatrixColumn( camera.matrix, 0 ); + + _vector.crossVectors( camera.up, _vector ); + + camera.position.addScaledVector( _vector, distance ); + + }; + + this.moveRight = function ( distance ) { + + _vector.setFromMatrixColumn( camera.matrix, 0 ); + + camera.position.addScaledVector( _vector, distance ); + + }; + + this.lock = function () { + + this.domElement.requestPointerLock(); + + }; + + this.unlock = function () { + + scope.domElement.ownerDocument.exitPointerLock(); + + }; + + this.connect(); + + } + +} + +export { PointerLockControls }; diff --git a/renderer/jsm/controls/TrackballControls.js b/renderer/jsm/controls/TrackballControls.js new file mode 100644 index 0000000..77ef51c --- /dev/null +++ b/renderer/jsm/controls/TrackballControls.js @@ -0,0 +1,814 @@ +import { + EventDispatcher, + MOUSE, + Quaternion, + Vector2, + Vector3 +} from 'three'; + +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; + +class TrackballControls extends EventDispatcher { + + constructor( object, domElement ) { + + super(); + + const scope = this; + const STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }; + + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll + + // API + + this.enabled = true; + + this.screen = { left: 0, top: 0, width: 0, height: 0 }; + + this.rotateSpeed = 1.0; + this.zoomSpeed = 1.2; + this.panSpeed = 0.3; + + this.noRotate = false; + this.noZoom = false; + this.noPan = false; + + this.staticMoving = false; + this.dynamicDampingFactor = 0.2; + + this.minDistance = 0; + this.maxDistance = Infinity; + + this.keys = [ 'KeyA' /*A*/, 'KeyS' /*S*/, 'KeyD' /*D*/ ]; + + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + // internals + + this.target = new Vector3(); + + const EPS = 0.000001; + + const lastPosition = new Vector3(); + let lastZoom = 1; + + let _state = STATE.NONE, + _keyState = STATE.NONE, + + _touchZoomDistanceStart = 0, + _touchZoomDistanceEnd = 0, + + _lastAngle = 0; + + const _eye = new Vector3(), + + _movePrev = new Vector2(), + _moveCurr = new Vector2(), + + _lastAxis = new Vector3(), + + _zoomStart = new Vector2(), + _zoomEnd = new Vector2(), + + _panStart = new Vector2(), + _panEnd = new Vector2(), + + _pointers = [], + _pointerPositions = {}; + + // for reset + + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.up0 = this.object.up.clone(); + this.zoom0 = this.object.zoom; + + // methods + + this.handleResize = function () { + + const box = scope.domElement.getBoundingClientRect(); + // adjustments come from similar code in the jquery offset() function + const d = scope.domElement.ownerDocument.documentElement; + scope.screen.left = box.left + window.pageXOffset - d.clientLeft; + scope.screen.top = box.top + window.pageYOffset - d.clientTop; + scope.screen.width = box.width; + scope.screen.height = box.height; + + }; + + const getMouseOnScreen = ( function () { + + const vector = new Vector2(); + + return function getMouseOnScreen( pageX, pageY ) { + + vector.set( + ( pageX - scope.screen.left ) / scope.screen.width, + ( pageY - scope.screen.top ) / scope.screen.height + ); + + return vector; + + }; + + }() ); + + const getMouseOnCircle = ( function () { + + const vector = new Vector2(); + + return function getMouseOnCircle( pageX, pageY ) { + + vector.set( + ( ( pageX - scope.screen.width * 0.5 - scope.screen.left ) / ( scope.screen.width * 0.5 ) ), + ( ( scope.screen.height + 2 * ( scope.screen.top - pageY ) ) / scope.screen.width ) // screen.width intentional + ); + + return vector; + + }; + + }() ); + + this.rotateCamera = ( function () { + + const axis = new Vector3(), + quaternion = new Quaternion(), + eyeDirection = new Vector3(), + objectUpDirection = new Vector3(), + objectSidewaysDirection = new Vector3(), + moveDirection = new Vector3(); + + return function rotateCamera() { + + moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 ); + let angle = moveDirection.length(); + + if ( angle ) { + + _eye.copy( scope.object.position ).sub( scope.target ); + + eyeDirection.copy( _eye ).normalize(); + objectUpDirection.copy( scope.object.up ).normalize(); + objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize(); + + objectUpDirection.setLength( _moveCurr.y - _movePrev.y ); + objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x ); + + moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) ); + + axis.crossVectors( moveDirection, _eye ).normalize(); + + angle *= scope.rotateSpeed; + quaternion.setFromAxisAngle( axis, angle ); + + _eye.applyQuaternion( quaternion ); + scope.object.up.applyQuaternion( quaternion ); + + _lastAxis.copy( axis ); + _lastAngle = angle; + + } else if ( ! scope.staticMoving && _lastAngle ) { + + _lastAngle *= Math.sqrt( 1.0 - scope.dynamicDampingFactor ); + _eye.copy( scope.object.position ).sub( scope.target ); + quaternion.setFromAxisAngle( _lastAxis, _lastAngle ); + _eye.applyQuaternion( quaternion ); + scope.object.up.applyQuaternion( quaternion ); + + } + + _movePrev.copy( _moveCurr ); + + }; + + }() ); + + + this.zoomCamera = function () { + + let factor; + + if ( _state === STATE.TOUCH_ZOOM_PAN ) { + + factor = _touchZoomDistanceStart / _touchZoomDistanceEnd; + _touchZoomDistanceStart = _touchZoomDistanceEnd; + + if ( scope.object.isPerspectiveCamera ) { + + _eye.multiplyScalar( factor ); + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom /= factor; + scope.object.updateProjectionMatrix(); + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + } else { + + factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * scope.zoomSpeed; + + if ( factor !== 1.0 && factor > 0.0 ) { + + if ( scope.object.isPerspectiveCamera ) { + + _eye.multiplyScalar( factor ); + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom /= factor; + scope.object.updateProjectionMatrix(); + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + } + + if ( scope.staticMoving ) { + + _zoomStart.copy( _zoomEnd ); + + } else { + + _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor; + + } + + } + + }; + + this.panCamera = ( function () { + + const mouseChange = new Vector2(), + objectUp = new Vector3(), + pan = new Vector3(); + + return function panCamera() { + + mouseChange.copy( _panEnd ).sub( _panStart ); + + if ( mouseChange.lengthSq() ) { + + if ( scope.object.isOrthographicCamera ) { + + const scale_x = ( scope.object.right - scope.object.left ) / scope.object.zoom / scope.domElement.clientWidth; + const scale_y = ( scope.object.top - scope.object.bottom ) / scope.object.zoom / scope.domElement.clientWidth; + + mouseChange.x *= scale_x; + mouseChange.y *= scale_y; + + } + + mouseChange.multiplyScalar( _eye.length() * scope.panSpeed ); + + pan.copy( _eye ).cross( scope.object.up ).setLength( mouseChange.x ); + pan.add( objectUp.copy( scope.object.up ).setLength( mouseChange.y ) ); + + scope.object.position.add( pan ); + scope.target.add( pan ); + + if ( scope.staticMoving ) { + + _panStart.copy( _panEnd ); + + } else { + + _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( scope.dynamicDampingFactor ) ); + + } + + } + + }; + + }() ); + + this.checkDistances = function () { + + if ( ! scope.noZoom || ! scope.noPan ) { + + if ( _eye.lengthSq() > scope.maxDistance * scope.maxDistance ) { + + scope.object.position.addVectors( scope.target, _eye.setLength( scope.maxDistance ) ); + _zoomStart.copy( _zoomEnd ); + + } + + if ( _eye.lengthSq() < scope.minDistance * scope.minDistance ) { + + scope.object.position.addVectors( scope.target, _eye.setLength( scope.minDistance ) ); + _zoomStart.copy( _zoomEnd ); + + } + + } + + }; + + this.update = function () { + + _eye.subVectors( scope.object.position, scope.target ); + + if ( ! scope.noRotate ) { + + scope.rotateCamera(); + + } + + if ( ! scope.noZoom ) { + + scope.zoomCamera(); + + } + + if ( ! scope.noPan ) { + + scope.panCamera(); + + } + + scope.object.position.addVectors( scope.target, _eye ); + + if ( scope.object.isPerspectiveCamera ) { + + scope.checkDistances(); + + scope.object.lookAt( scope.target ); + + if ( lastPosition.distanceToSquared( scope.object.position ) > EPS ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + + } + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.lookAt( scope.target ); + + if ( lastPosition.distanceToSquared( scope.object.position ) > EPS || lastZoom !== scope.object.zoom ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastZoom = scope.object.zoom; + + } + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + }; + + this.reset = function () { + + _state = STATE.NONE; + _keyState = STATE.NONE; + + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.up.copy( scope.up0 ); + scope.object.zoom = scope.zoom0; + + scope.object.updateProjectionMatrix(); + + _eye.subVectors( scope.object.position, scope.target ); + + scope.object.lookAt( scope.target ); + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastZoom = scope.object.zoom; + + }; + + // listeners + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + if ( _pointers.length === 0 ) { + + scope.domElement.setPointerCapture( event.pointerId ); + + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); + + } + + // + + addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + onTouchStart( event ); + + } else { + + onMouseDown( event ); + + } + + } + + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchMove( event ); + + } else { + + onMouseMove( event ); + + } + + } + + function onPointerUp( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchEnd( event ); + + } else { + + onMouseUp(); + + } + + // + + removePointer( event ); + + if ( _pointers.length === 0 ) { + + scope.domElement.releasePointerCapture( event.pointerId ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + } + + + } + + function onPointerCancel( event ) { + + removePointer( event ); + + } + + function keydown( event ) { + + if ( scope.enabled === false ) return; + + window.removeEventListener( 'keydown', keydown ); + + if ( _keyState !== STATE.NONE ) { + + return; + + } else if ( event.code === scope.keys[ STATE.ROTATE ] && ! scope.noRotate ) { + + _keyState = STATE.ROTATE; + + } else if ( event.code === scope.keys[ STATE.ZOOM ] && ! scope.noZoom ) { + + _keyState = STATE.ZOOM; + + } else if ( event.code === scope.keys[ STATE.PAN ] && ! scope.noPan ) { + + _keyState = STATE.PAN; + + } + + } + + function keyup() { + + if ( scope.enabled === false ) return; + + _keyState = STATE.NONE; + + window.addEventListener( 'keydown', keydown ); + + } + + function onMouseDown( event ) { + + if ( _state === STATE.NONE ) { + + switch ( event.button ) { + + case scope.mouseButtons.LEFT: + _state = STATE.ROTATE; + break; + + case scope.mouseButtons.MIDDLE: + _state = STATE.ZOOM; + break; + + case scope.mouseButtons.RIGHT: + _state = STATE.PAN; + break; + + } + + } + + const state = ( _keyState !== STATE.NONE ) ? _keyState : _state; + + if ( state === STATE.ROTATE && ! scope.noRotate ) { + + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + _movePrev.copy( _moveCurr ); + + } else if ( state === STATE.ZOOM && ! scope.noZoom ) { + + _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + _zoomEnd.copy( _zoomStart ); + + } else if ( state === STATE.PAN && ! scope.noPan ) { + + _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + _panEnd.copy( _panStart ); + + } + + scope.dispatchEvent( _startEvent ); + + } + + function onMouseMove( event ) { + + const state = ( _keyState !== STATE.NONE ) ? _keyState : _state; + + if ( state === STATE.ROTATE && ! scope.noRotate ) { + + _movePrev.copy( _moveCurr ); + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + + } else if ( state === STATE.ZOOM && ! scope.noZoom ) { + + _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + + } else if ( state === STATE.PAN && ! scope.noPan ) { + + _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + + } + + } + + function onMouseUp() { + + _state = STATE.NONE; + + scope.dispatchEvent( _endEvent ); + + } + + function onMouseWheel( event ) { + + if ( scope.enabled === false ) return; + + if ( scope.noZoom === true ) return; + + event.preventDefault(); + + switch ( event.deltaMode ) { + + case 2: + // Zoom in pages + _zoomStart.y -= event.deltaY * 0.025; + break; + + case 1: + // Zoom in lines + _zoomStart.y -= event.deltaY * 0.01; + break; + + default: + // undefined, 0, assume pixels + _zoomStart.y -= event.deltaY * 0.00025; + break; + + } + + scope.dispatchEvent( _startEvent ); + scope.dispatchEvent( _endEvent ); + + } + + function onTouchStart( event ) { + + trackPointer( event ); + + switch ( _pointers.length ) { + + case 1: + _state = STATE.TOUCH_ROTATE; + _moveCurr.copy( getMouseOnCircle( _pointers[ 0 ].pageX, _pointers[ 0 ].pageY ) ); + _movePrev.copy( _moveCurr ); + break; + + default: // 2 or more + _state = STATE.TOUCH_ZOOM_PAN; + const dx = _pointers[ 0 ].pageX - _pointers[ 1 ].pageX; + const dy = _pointers[ 0 ].pageY - _pointers[ 1 ].pageY; + _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy ); + + const x = ( _pointers[ 0 ].pageX + _pointers[ 1 ].pageX ) / 2; + const y = ( _pointers[ 0 ].pageY + _pointers[ 1 ].pageY ) / 2; + _panStart.copy( getMouseOnScreen( x, y ) ); + _panEnd.copy( _panStart ); + break; + + } + + scope.dispatchEvent( _startEvent ); + + } + + function onTouchMove( event ) { + + trackPointer( event ); + + switch ( _pointers.length ) { + + case 1: + _movePrev.copy( _moveCurr ); + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + break; + + default: // 2 or more + + const position = getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy ); + + const x = ( event.pageX + position.x ) / 2; + const y = ( event.pageY + position.y ) / 2; + _panEnd.copy( getMouseOnScreen( x, y ) ); + break; + + } + + } + + function onTouchEnd( event ) { + + switch ( _pointers.length ) { + + case 0: + _state = STATE.NONE; + break; + + case 1: + _state = STATE.TOUCH_ROTATE; + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + _movePrev.copy( _moveCurr ); + break; + + case 2: + _state = STATE.TOUCH_ZOOM_PAN; + + for ( let i = 0; i < _pointers.length; i ++ ) { + + if ( _pointers[ i ].pointerId !== event.pointerId ) { + + const position = _pointerPositions[ _pointers[ i ].pointerId ]; + _moveCurr.copy( getMouseOnCircle( position.x, position.y ) ); + _movePrev.copy( _moveCurr ); + break; + + } + + } + + break; + + } + + scope.dispatchEvent( _endEvent ); + + } + + function contextmenu( event ) { + + if ( scope.enabled === false ) return; + + event.preventDefault(); + + } + + function addPointer( event ) { + + _pointers.push( event ); + + } + + function removePointer( event ) { + + delete _pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < _pointers.length; i ++ ) { + + if ( _pointers[ i ].pointerId == event.pointerId ) { + + _pointers.splice( i, 1 ); + return; + + } + + } + + } + + function trackPointer( event ) { + + let position = _pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + _pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + function getSecondPointerPosition( event ) { + + const pointer = ( event.pointerId === _pointers[ 0 ].pointerId ) ? _pointers[ 1 ] : _pointers[ 0 ]; + + return _pointerPositions[ pointer.pointerId ]; + + } + + this.dispose = function () { + + scope.domElement.removeEventListener( 'contextmenu', contextmenu ); + + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + window.removeEventListener( 'keydown', keydown ); + window.removeEventListener( 'keyup', keyup ); + + }; + + this.domElement.addEventListener( 'contextmenu', contextmenu ); + + this.domElement.addEventListener( 'pointerdown', onPointerDown ); + this.domElement.addEventListener( 'pointercancel', onPointerCancel ); + this.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); + + + window.addEventListener( 'keydown', keydown ); + window.addEventListener( 'keyup', keyup ); + + this.handleResize(); + + // force an update at start + this.update(); + + } + +} + +export { TrackballControls }; diff --git a/renderer/jsm/controls/TransformControls.js b/renderer/jsm/controls/TransformControls.js new file mode 100644 index 0000000..4beff97 --- /dev/null +++ b/renderer/jsm/controls/TransformControls.js @@ -0,0 +1,1557 @@ +import { + BoxGeometry, + BufferGeometry, + CylinderGeometry, + DoubleSide, + Euler, + Float32BufferAttribute, + Line, + LineBasicMaterial, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + OctahedronGeometry, + PlaneGeometry, + Quaternion, + Raycaster, + SphereGeometry, + TorusGeometry, + Vector3 +} from 'three'; + +const _raycaster = new Raycaster(); + +const _tempVector = new Vector3(); +const _tempVector2 = new Vector3(); +const _tempQuaternion = new Quaternion(); +const _unit = { + X: new Vector3( 1, 0, 0 ), + Y: new Vector3( 0, 1, 0 ), + Z: new Vector3( 0, 0, 1 ) +}; + +const _changeEvent = { type: 'change' }; +const _mouseDownEvent = { type: 'mouseDown' }; +const _mouseUpEvent = { type: 'mouseUp', mode: null }; +const _objectChangeEvent = { type: 'objectChange' }; + +class TransformControls extends Object3D { + + constructor( camera, domElement ) { + + super(); + + if ( domElement === undefined ) { + + console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' ); + domElement = document; + + } + + this.isTransformControls = true; + + this.visible = false; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll + + const _gizmo = new TransformControlsGizmo(); + this._gizmo = _gizmo; + this.add( _gizmo ); + + const _plane = new TransformControlsPlane(); + this._plane = _plane; + this.add( _plane ); + + const scope = this; + + // Defined getter, setter and store for a property + function defineProperty( propName, defaultValue ) { + + let propValue = defaultValue; + + Object.defineProperty( scope, propName, { + + get: function () { + + return propValue !== undefined ? propValue : defaultValue; + + }, + + set: function ( value ) { + + if ( propValue !== value ) { + + propValue = value; + _plane[ propName ] = value; + _gizmo[ propName ] = value; + + scope.dispatchEvent( { type: propName + '-changed', value: value } ); + scope.dispatchEvent( _changeEvent ); + + } + + } + + } ); + + scope[ propName ] = defaultValue; + _plane[ propName ] = defaultValue; + _gizmo[ propName ] = defaultValue; + + } + + // Define properties with getters/setter + // Setting the defined property will automatically trigger change event + // Defined properties are passed down to gizmo and plane + + defineProperty( 'camera', camera ); + defineProperty( 'object', undefined ); + defineProperty( 'enabled', true ); + defineProperty( 'axis', null ); + defineProperty( 'mode', 'translate' ); + defineProperty( 'translationSnap', null ); + defineProperty( 'rotationSnap', null ); + defineProperty( 'scaleSnap', null ); + defineProperty( 'space', 'world' ); + defineProperty( 'size', 1 ); + defineProperty( 'dragging', false ); + defineProperty( 'showX', true ); + defineProperty( 'showY', true ); + defineProperty( 'showZ', true ); + + // Reusable utility variables + + const worldPosition = new Vector3(); + const worldPositionStart = new Vector3(); + const worldQuaternion = new Quaternion(); + const worldQuaternionStart = new Quaternion(); + const cameraPosition = new Vector3(); + const cameraQuaternion = new Quaternion(); + const pointStart = new Vector3(); + const pointEnd = new Vector3(); + const rotationAxis = new Vector3(); + const rotationAngle = 0; + const eye = new Vector3(); + + // TODO: remove properties unused in plane and gizmo + + defineProperty( 'worldPosition', worldPosition ); + defineProperty( 'worldPositionStart', worldPositionStart ); + defineProperty( 'worldQuaternion', worldQuaternion ); + defineProperty( 'worldQuaternionStart', worldQuaternionStart ); + defineProperty( 'cameraPosition', cameraPosition ); + defineProperty( 'cameraQuaternion', cameraQuaternion ); + defineProperty( 'pointStart', pointStart ); + defineProperty( 'pointEnd', pointEnd ); + defineProperty( 'rotationAxis', rotationAxis ); + defineProperty( 'rotationAngle', rotationAngle ); + defineProperty( 'eye', eye ); + + this._offset = new Vector3(); + this._startNorm = new Vector3(); + this._endNorm = new Vector3(); + this._cameraScale = new Vector3(); + + this._parentPosition = new Vector3(); + this._parentQuaternion = new Quaternion(); + this._parentQuaternionInv = new Quaternion(); + this._parentScale = new Vector3(); + + this._worldScaleStart = new Vector3(); + this._worldQuaternionInv = new Quaternion(); + this._worldScale = new Vector3(); + + this._positionStart = new Vector3(); + this._quaternionStart = new Quaternion(); + this._scaleStart = new Vector3(); + + this._getPointer = getPointer.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerHover = onPointerHover.bind( this ); + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointermove', this._onPointerHover ); + this.domElement.addEventListener( 'pointerup', this._onPointerUp ); + + } + + // updateMatrixWorld updates key transformation variables + updateMatrixWorld() { + + if ( this.object !== undefined ) { + + this.object.updateMatrixWorld(); + + if ( this.object.parent === null ) { + + console.error( 'TransformControls: The attached 3D object must be a part of the scene graph.' ); + + } else { + + this.object.parent.matrixWorld.decompose( this._parentPosition, this._parentQuaternion, this._parentScale ); + + } + + this.object.matrixWorld.decompose( this.worldPosition, this.worldQuaternion, this._worldScale ); + + this._parentQuaternionInv.copy( this._parentQuaternion ).invert(); + this._worldQuaternionInv.copy( this.worldQuaternion ).invert(); + + } + + this.camera.updateMatrixWorld(); + this.camera.matrixWorld.decompose( this.cameraPosition, this.cameraQuaternion, this._cameraScale ); + + if ( this.camera.isOrthographicCamera ) { + + this.camera.getWorldDirection( this.eye ).negate(); + + } else { + + this.eye.copy( this.cameraPosition ).sub( this.worldPosition ).normalize(); + + } + + super.updateMatrixWorld( this ); + + } + + pointerHover( pointer ) { + + if ( this.object === undefined || this.dragging === true ) return; + + _raycaster.setFromCamera( pointer, this.camera ); + + const intersect = intersectObjectWithRay( this._gizmo.picker[ this.mode ], _raycaster ); + + if ( intersect ) { + + this.axis = intersect.object.name; + + } else { + + this.axis = null; + + } + + } + + pointerDown( pointer ) { + + if ( this.object === undefined || this.dragging === true || pointer.button !== 0 ) return; + + if ( this.axis !== null ) { + + _raycaster.setFromCamera( pointer, this.camera ); + + const planeIntersect = intersectObjectWithRay( this._plane, _raycaster, true ); + + if ( planeIntersect ) { + + this.object.updateMatrixWorld(); + this.object.parent.updateMatrixWorld(); + + this._positionStart.copy( this.object.position ); + this._quaternionStart.copy( this.object.quaternion ); + this._scaleStart.copy( this.object.scale ); + + this.object.matrixWorld.decompose( this.worldPositionStart, this.worldQuaternionStart, this._worldScaleStart ); + + this.pointStart.copy( planeIntersect.point ).sub( this.worldPositionStart ); + + } + + this.dragging = true; + _mouseDownEvent.mode = this.mode; + this.dispatchEvent( _mouseDownEvent ); + + } + + } + + pointerMove( pointer ) { + + const axis = this.axis; + const mode = this.mode; + const object = this.object; + let space = this.space; + + if ( mode === 'scale' ) { + + space = 'local'; + + } else if ( axis === 'E' || axis === 'XYZE' || axis === 'XYZ' ) { + + space = 'world'; + + } + + if ( object === undefined || axis === null || this.dragging === false || pointer.button !== - 1 ) return; + + _raycaster.setFromCamera( pointer, this.camera ); + + const planeIntersect = intersectObjectWithRay( this._plane, _raycaster, true ); + + if ( ! planeIntersect ) return; + + this.pointEnd.copy( planeIntersect.point ).sub( this.worldPositionStart ); + + if ( mode === 'translate' ) { + + // Apply translate + + this._offset.copy( this.pointEnd ).sub( this.pointStart ); + + if ( space === 'local' && axis !== 'XYZ' ) { + + this._offset.applyQuaternion( this._worldQuaternionInv ); + + } + + if ( axis.indexOf( 'X' ) === - 1 ) this._offset.x = 0; + if ( axis.indexOf( 'Y' ) === - 1 ) this._offset.y = 0; + if ( axis.indexOf( 'Z' ) === - 1 ) this._offset.z = 0; + + if ( space === 'local' && axis !== 'XYZ' ) { + + this._offset.applyQuaternion( this._quaternionStart ).divide( this._parentScale ); + + } else { + + this._offset.applyQuaternion( this._parentQuaternionInv ).divide( this._parentScale ); + + } + + object.position.copy( this._offset ).add( this._positionStart ); + + // Apply translation snap + + if ( this.translationSnap ) { + + if ( space === 'local' ) { + + object.position.applyQuaternion( _tempQuaternion.copy( this._quaternionStart ).invert() ); + + if ( axis.search( 'X' ) !== - 1 ) { + + object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap; + + } + + if ( axis.search( 'Y' ) !== - 1 ) { + + object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap; + + } + + if ( axis.search( 'Z' ) !== - 1 ) { + + object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap; + + } + + object.position.applyQuaternion( this._quaternionStart ); + + } + + if ( space === 'world' ) { + + if ( object.parent ) { + + object.position.add( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) ); + + } + + if ( axis.search( 'X' ) !== - 1 ) { + + object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap; + + } + + if ( axis.search( 'Y' ) !== - 1 ) { + + object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap; + + } + + if ( axis.search( 'Z' ) !== - 1 ) { + + object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap; + + } + + if ( object.parent ) { + + object.position.sub( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) ); + + } + + } + + } + + } else if ( mode === 'scale' ) { + + if ( axis.search( 'XYZ' ) !== - 1 ) { + + let d = this.pointEnd.length() / this.pointStart.length(); + + if ( this.pointEnd.dot( this.pointStart ) < 0 ) d *= - 1; + + _tempVector2.set( d, d, d ); + + } else { + + _tempVector.copy( this.pointStart ); + _tempVector2.copy( this.pointEnd ); + + _tempVector.applyQuaternion( this._worldQuaternionInv ); + _tempVector2.applyQuaternion( this._worldQuaternionInv ); + + _tempVector2.divide( _tempVector ); + + if ( axis.search( 'X' ) === - 1 ) { + + _tempVector2.x = 1; + + } + + if ( axis.search( 'Y' ) === - 1 ) { + + _tempVector2.y = 1; + + } + + if ( axis.search( 'Z' ) === - 1 ) { + + _tempVector2.z = 1; + + } + + } + + // Apply scale + + object.scale.copy( this._scaleStart ).multiply( _tempVector2 ); + + if ( this.scaleSnap ) { + + if ( axis.search( 'X' ) !== - 1 ) { + + object.scale.x = Math.round( object.scale.x / this.scaleSnap ) * this.scaleSnap || this.scaleSnap; + + } + + if ( axis.search( 'Y' ) !== - 1 ) { + + object.scale.y = Math.round( object.scale.y / this.scaleSnap ) * this.scaleSnap || this.scaleSnap; + + } + + if ( axis.search( 'Z' ) !== - 1 ) { + + object.scale.z = Math.round( object.scale.z / this.scaleSnap ) * this.scaleSnap || this.scaleSnap; + + } + + } + + } else if ( mode === 'rotate' ) { + + this._offset.copy( this.pointEnd ).sub( this.pointStart ); + + const ROTATION_SPEED = 20 / this.worldPosition.distanceTo( _tempVector.setFromMatrixPosition( this.camera.matrixWorld ) ); + + if ( axis === 'E' ) { + + this.rotationAxis.copy( this.eye ); + this.rotationAngle = this.pointEnd.angleTo( this.pointStart ); + + this._startNorm.copy( this.pointStart ).normalize(); + this._endNorm.copy( this.pointEnd ).normalize(); + + this.rotationAngle *= ( this._endNorm.cross( this._startNorm ).dot( this.eye ) < 0 ? 1 : - 1 ); + + } else if ( axis === 'XYZE' ) { + + this.rotationAxis.copy( this._offset ).cross( this.eye ).normalize(); + this.rotationAngle = this._offset.dot( _tempVector.copy( this.rotationAxis ).cross( this.eye ) ) * ROTATION_SPEED; + + } else if ( axis === 'X' || axis === 'Y' || axis === 'Z' ) { + + this.rotationAxis.copy( _unit[ axis ] ); + + _tempVector.copy( _unit[ axis ] ); + + if ( space === 'local' ) { + + _tempVector.applyQuaternion( this.worldQuaternion ); + + } + + this.rotationAngle = this._offset.dot( _tempVector.cross( this.eye ).normalize() ) * ROTATION_SPEED; + + } + + // Apply rotation snap + + if ( this.rotationSnap ) this.rotationAngle = Math.round( this.rotationAngle / this.rotationSnap ) * this.rotationSnap; + + // Apply rotate + if ( space === 'local' && axis !== 'E' && axis !== 'XYZE' ) { + + object.quaternion.copy( this._quaternionStart ); + object.quaternion.multiply( _tempQuaternion.setFromAxisAngle( this.rotationAxis, this.rotationAngle ) ).normalize(); + + } else { + + this.rotationAxis.applyQuaternion( this._parentQuaternionInv ); + object.quaternion.copy( _tempQuaternion.setFromAxisAngle( this.rotationAxis, this.rotationAngle ) ); + object.quaternion.multiply( this._quaternionStart ).normalize(); + + } + + } + + this.dispatchEvent( _changeEvent ); + this.dispatchEvent( _objectChangeEvent ); + + } + + pointerUp( pointer ) { + + if ( pointer.button !== 0 ) return; + + if ( this.dragging && ( this.axis !== null ) ) { + + _mouseUpEvent.mode = this.mode; + this.dispatchEvent( _mouseUpEvent ); + + } + + this.dragging = false; + this.axis = null; + + } + + dispose() { + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.removeEventListener( 'pointermove', this._onPointerHover ); + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + + this.traverse( function ( child ) { + + if ( child.geometry ) child.geometry.dispose(); + if ( child.material ) child.material.dispose(); + + } ); + + } + + // Set current object + attach( object ) { + + this.object = object; + this.visible = true; + + return this; + + } + + // Detach from object + detach() { + + this.object = undefined; + this.visible = false; + this.axis = null; + + return this; + + } + + reset() { + + if ( ! this.enabled ) return; + + if ( this.dragging ) { + + this.object.position.copy( this._positionStart ); + this.object.quaternion.copy( this._quaternionStart ); + this.object.scale.copy( this._scaleStart ); + + this.dispatchEvent( _changeEvent ); + this.dispatchEvent( _objectChangeEvent ); + + this.pointStart.copy( this.pointEnd ); + + } + + } + + getRaycaster() { + + return _raycaster; + + } + + // TODO: deprecate + + getMode() { + + return this.mode; + + } + + setMode( mode ) { + + this.mode = mode; + + } + + setTranslationSnap( translationSnap ) { + + this.translationSnap = translationSnap; + + } + + setRotationSnap( rotationSnap ) { + + this.rotationSnap = rotationSnap; + + } + + setScaleSnap( scaleSnap ) { + + this.scaleSnap = scaleSnap; + + } + + setSize( size ) { + + this.size = size; + + } + + setSpace( space ) { + + this.space = space; + + } + +} + +// mouse / touch event handlers + +function getPointer( event ) { + + if ( this.domElement.ownerDocument.pointerLockElement ) { + + return { + x: 0, + y: 0, + button: event.button + }; + + } else { + + const rect = this.domElement.getBoundingClientRect(); + + return { + x: ( event.clientX - rect.left ) / rect.width * 2 - 1, + y: - ( event.clientY - rect.top ) / rect.height * 2 + 1, + button: event.button + }; + + } + +} + +function onPointerHover( event ) { + + if ( ! this.enabled ) return; + + switch ( event.pointerType ) { + + case 'mouse': + case 'pen': + this.pointerHover( this._getPointer( event ) ); + break; + + } + +} + +function onPointerDown( event ) { + + if ( ! this.enabled ) return; + + if ( ! document.pointerLockElement ) { + + this.domElement.setPointerCapture( event.pointerId ); + + } + + this.domElement.addEventListener( 'pointermove', this._onPointerMove ); + + this.pointerHover( this._getPointer( event ) ); + this.pointerDown( this._getPointer( event ) ); + +} + +function onPointerMove( event ) { + + if ( ! this.enabled ) return; + + this.pointerMove( this._getPointer( event ) ); + +} + +function onPointerUp( event ) { + + if ( ! this.enabled ) return; + + this.domElement.releasePointerCapture( event.pointerId ); + + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + + this.pointerUp( this._getPointer( event ) ); + +} + +function intersectObjectWithRay( object, raycaster, includeInvisible ) { + + const allIntersections = raycaster.intersectObject( object, true ); + + for ( let i = 0; i < allIntersections.length; i ++ ) { + + if ( allIntersections[ i ].object.visible || includeInvisible ) { + + return allIntersections[ i ]; + + } + + } + + return false; + +} + +// + +// Reusable utility variables + +const _tempEuler = new Euler(); +const _alignVector = new Vector3( 0, 1, 0 ); +const _zeroVector = new Vector3( 0, 0, 0 ); +const _lookAtMatrix = new Matrix4(); +const _tempQuaternion2 = new Quaternion(); +const _identityQuaternion = new Quaternion(); +const _dirVector = new Vector3(); +const _tempMatrix = new Matrix4(); + +const _unitX = new Vector3( 1, 0, 0 ); +const _unitY = new Vector3( 0, 1, 0 ); +const _unitZ = new Vector3( 0, 0, 1 ); + +const _v1 = new Vector3(); +const _v2 = new Vector3(); +const _v3 = new Vector3(); + +class TransformControlsGizmo extends Object3D { + + constructor() { + + super(); + + this.isTransformControlsGizmo = true; + + this.type = 'TransformControlsGizmo'; + + // shared materials + + const gizmoMaterial = new MeshBasicMaterial( { + depthTest: false, + depthWrite: false, + fog: false, + toneMapped: false, + transparent: true + } ); + + const gizmoLineMaterial = new LineBasicMaterial( { + depthTest: false, + depthWrite: false, + fog: false, + toneMapped: false, + transparent: true + } ); + + // Make unique material for each axis/color + + const matInvisible = gizmoMaterial.clone(); + matInvisible.opacity = 0.15; + + const matHelper = gizmoLineMaterial.clone(); + matHelper.opacity = 0.5; + + const matRed = gizmoMaterial.clone(); + matRed.color.setHex( 0xff0000 ); + + const matGreen = gizmoMaterial.clone(); + matGreen.color.setHex( 0x00ff00 ); + + const matBlue = gizmoMaterial.clone(); + matBlue.color.setHex( 0x0000ff ); + + const matRedTransparent = gizmoMaterial.clone(); + matRedTransparent.color.setHex( 0xff0000 ); + matRedTransparent.opacity = 0.5; + + const matGreenTransparent = gizmoMaterial.clone(); + matGreenTransparent.color.setHex( 0x00ff00 ); + matGreenTransparent.opacity = 0.5; + + const matBlueTransparent = gizmoMaterial.clone(); + matBlueTransparent.color.setHex( 0x0000ff ); + matBlueTransparent.opacity = 0.5; + + const matWhiteTransparent = gizmoMaterial.clone(); + matWhiteTransparent.opacity = 0.25; + + const matYellowTransparent = gizmoMaterial.clone(); + matYellowTransparent.color.setHex( 0xffff00 ); + matYellowTransparent.opacity = 0.25; + + const matYellow = gizmoMaterial.clone(); + matYellow.color.setHex( 0xffff00 ); + + const matGray = gizmoMaterial.clone(); + matGray.color.setHex( 0x787878 ); + + // reusable geometry + + const arrowGeometry = new CylinderGeometry( 0, 0.04, 0.1, 12 ); + arrowGeometry.translate( 0, 0.05, 0 ); + + const scaleHandleGeometry = new BoxGeometry( 0.08, 0.08, 0.08 ); + scaleHandleGeometry.translate( 0, 0.04, 0 ); + + const lineGeometry = new BufferGeometry(); + lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) ); + + const lineGeometry2 = new CylinderGeometry( 0.0075, 0.0075, 0.5, 3 ); + lineGeometry2.translate( 0, 0.25, 0 ); + + function CircleGeometry( radius, arc ) { + + const geometry = new TorusGeometry( radius, 0.0075, 3, 64, arc * Math.PI * 2 ); + geometry.rotateY( Math.PI / 2 ); + geometry.rotateX( Math.PI / 2 ); + return geometry; + + } + + // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position + + function TranslateHelperGeometry() { + + const geometry = new BufferGeometry(); + + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) ); + + return geometry; + + } + + // Gizmo definitions - custom hierarchy definitions for setupGizmo() function + + const gizmoTranslate = { + X: [ + [ new Mesh( arrowGeometry, matRed ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + [ new Mesh( arrowGeometry, matRed ), [ - 0.5, 0, 0 ], [ 0, 0, Math.PI / 2 ]], + [ new Mesh( lineGeometry2, matRed ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]] + ], + Y: [ + [ new Mesh( arrowGeometry, matGreen ), [ 0, 0.5, 0 ]], + [ new Mesh( arrowGeometry, matGreen ), [ 0, - 0.5, 0 ], [ Math.PI, 0, 0 ]], + [ new Mesh( lineGeometry2, matGreen ) ] + ], + Z: [ + [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]], + [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, - 0.5 ], [ - Math.PI / 2, 0, 0 ]], + [ new Mesh( lineGeometry2, matBlue ), null, [ Math.PI / 2, 0, 0 ]] + ], + XYZ: [ + [ new Mesh( new OctahedronGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ]] + ], + XY: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matBlueTransparent.clone() ), [ 0.15, 0.15, 0 ]] + ], + YZ: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matRedTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]] + ], + XZ: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matGreenTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]] + ] + }; + + const pickerTranslate = { + X: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0.3, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ - 0.3, 0, 0 ], [ 0, 0, Math.PI / 2 ]] + ], + Y: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0.3, 0 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, - 0.3, 0 ], [ 0, 0, Math.PI ]] + ], + Z: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0, 0.3 ], [ Math.PI / 2, 0, 0 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0, - 0.3 ], [ - Math.PI / 2, 0, 0 ]] + ], + XYZ: [ + [ new Mesh( new OctahedronGeometry( 0.2, 0 ), matInvisible ) ] + ], + XY: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0.15, 0.15, 0 ]] + ], + YZ: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]] + ], + XZ: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]] + ] + }; + + const helperTranslate = { + START: [ + [ new Mesh( new OctahedronGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ] + ], + END: [ + [ new Mesh( new OctahedronGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ] + ], + DELTA: [ + [ new Line( TranslateHelperGeometry(), matHelper ), null, null, null, 'helper' ] + ], + X: [ + [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ] + ], + Y: [ + [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ] + ], + Z: [ + [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ] + ] + }; + + const gizmoRotate = { + XYZE: [ + [ new Mesh( CircleGeometry( 0.5, 1 ), matGray ), null, [ 0, Math.PI / 2, 0 ]] + ], + X: [ + [ new Mesh( CircleGeometry( 0.5, 0.5 ), matRed ) ] + ], + Y: [ + [ new Mesh( CircleGeometry( 0.5, 0.5 ), matGreen ), null, [ 0, 0, - Math.PI / 2 ]] + ], + Z: [ + [ new Mesh( CircleGeometry( 0.5, 0.5 ), matBlue ), null, [ 0, Math.PI / 2, 0 ]] + ], + E: [ + [ new Mesh( CircleGeometry( 0.75, 1 ), matYellowTransparent ), null, [ 0, Math.PI / 2, 0 ]] + ] + }; + + const helperRotate = { + AXIS: [ + [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ] + ] + }; + + const pickerRotate = { + XYZE: [ + [ new Mesh( new SphereGeometry( 0.25, 10, 8 ), matInvisible ) ] + ], + X: [ + [ new Mesh( new TorusGeometry( 0.5, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, - Math.PI / 2, - Math.PI / 2 ]], + ], + Y: [ + [ new Mesh( new TorusGeometry( 0.5, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]], + ], + Z: [ + [ new Mesh( new TorusGeometry( 0.5, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + ], + E: [ + [ new Mesh( new TorusGeometry( 0.75, 0.1, 2, 24 ), matInvisible ) ] + ] + }; + + const gizmoScale = { + X: [ + [ new Mesh( scaleHandleGeometry, matRed ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + [ new Mesh( lineGeometry2, matRed ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + [ new Mesh( scaleHandleGeometry, matRed ), [ - 0.5, 0, 0 ], [ 0, 0, Math.PI / 2 ]], + ], + Y: [ + [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, 0.5, 0 ]], + [ new Mesh( lineGeometry2, matGreen ) ], + [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, - 0.5, 0 ], [ 0, 0, Math.PI ]], + ], + Z: [ + [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]], + [ new Mesh( lineGeometry2, matBlue ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]], + [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, - 0.5 ], [ - Math.PI / 2, 0, 0 ]] + ], + XY: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matBlueTransparent ), [ 0.15, 0.15, 0 ]] + ], + YZ: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matRedTransparent ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]] + ], + XZ: [ + [ new Mesh( new BoxGeometry( 0.15, 0.15, 0.01 ), matGreenTransparent ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]] + ], + XYZ: [ + [ new Mesh( new BoxGeometry( 0.1, 0.1, 0.1 ), matWhiteTransparent.clone() ) ], + ] + }; + + const pickerScale = { + X: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0.3, 0, 0 ], [ 0, 0, - Math.PI / 2 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ - 0.3, 0, 0 ], [ 0, 0, Math.PI / 2 ]] + ], + Y: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0.3, 0 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, - 0.3, 0 ], [ 0, 0, Math.PI ]] + ], + Z: [ + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0, 0.3 ], [ Math.PI / 2, 0, 0 ]], + [ new Mesh( new CylinderGeometry( 0.2, 0, 0.6, 4 ), matInvisible ), [ 0, 0, - 0.3 ], [ - Math.PI / 2, 0, 0 ]] + ], + XY: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0.15, 0.15, 0 ]], + ], + YZ: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]], + ], + XZ: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.01 ), matInvisible ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]], + ], + XYZ: [ + [ new Mesh( new BoxGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 0 ]], + ] + }; + + const helperScale = { + X: [ + [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ] + ], + Y: [ + [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ] + ], + Z: [ + [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ] + ] + }; + + // Creates an Object3D with gizmos described in custom hierarchy definition. + + function setupGizmo( gizmoMap ) { + + const gizmo = new Object3D(); + + for ( const name in gizmoMap ) { + + for ( let i = gizmoMap[ name ].length; i --; ) { + + const object = gizmoMap[ name ][ i ][ 0 ].clone(); + const position = gizmoMap[ name ][ i ][ 1 ]; + const rotation = gizmoMap[ name ][ i ][ 2 ]; + const scale = gizmoMap[ name ][ i ][ 3 ]; + const tag = gizmoMap[ name ][ i ][ 4 ]; + + // name and tag properties are essential for picking and updating logic. + object.name = name; + object.tag = tag; + + if ( position ) { + + object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] ); + + } + + if ( rotation ) { + + object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] ); + + } + + if ( scale ) { + + object.scale.set( scale[ 0 ], scale[ 1 ], scale[ 2 ] ); + + } + + object.updateMatrix(); + + const tempGeometry = object.geometry.clone(); + tempGeometry.applyMatrix4( object.matrix ); + object.geometry = tempGeometry; + object.renderOrder = Infinity; + + object.position.set( 0, 0, 0 ); + object.rotation.set( 0, 0, 0 ); + object.scale.set( 1, 1, 1 ); + + gizmo.add( object ); + + } + + } + + return gizmo; + + } + + // Gizmo creation + + this.gizmo = {}; + this.picker = {}; + this.helper = {}; + + this.add( this.gizmo[ 'translate' ] = setupGizmo( gizmoTranslate ) ); + this.add( this.gizmo[ 'rotate' ] = setupGizmo( gizmoRotate ) ); + this.add( this.gizmo[ 'scale' ] = setupGizmo( gizmoScale ) ); + this.add( this.picker[ 'translate' ] = setupGizmo( pickerTranslate ) ); + this.add( this.picker[ 'rotate' ] = setupGizmo( pickerRotate ) ); + this.add( this.picker[ 'scale' ] = setupGizmo( pickerScale ) ); + this.add( this.helper[ 'translate' ] = setupGizmo( helperTranslate ) ); + this.add( this.helper[ 'rotate' ] = setupGizmo( helperRotate ) ); + this.add( this.helper[ 'scale' ] = setupGizmo( helperScale ) ); + + // Pickers should be hidden always + + this.picker[ 'translate' ].visible = false; + this.picker[ 'rotate' ].visible = false; + this.picker[ 'scale' ].visible = false; + + } + + // updateMatrixWorld will update transformations and appearance of individual handles + + updateMatrixWorld( force ) { + + const space = ( this.mode === 'scale' ) ? 'local' : this.space; // scale always oriented to local rotation + + const quaternion = ( space === 'local' ) ? this.worldQuaternion : _identityQuaternion; + + // Show only gizmos for current transform mode + + this.gizmo[ 'translate' ].visible = this.mode === 'translate'; + this.gizmo[ 'rotate' ].visible = this.mode === 'rotate'; + this.gizmo[ 'scale' ].visible = this.mode === 'scale'; + + this.helper[ 'translate' ].visible = this.mode === 'translate'; + this.helper[ 'rotate' ].visible = this.mode === 'rotate'; + this.helper[ 'scale' ].visible = this.mode === 'scale'; + + + let handles = []; + handles = handles.concat( this.picker[ this.mode ].children ); + handles = handles.concat( this.gizmo[ this.mode ].children ); + handles = handles.concat( this.helper[ this.mode ].children ); + + for ( let i = 0; i < handles.length; i ++ ) { + + const handle = handles[ i ]; + + // hide aligned to camera + + handle.visible = true; + handle.rotation.set( 0, 0, 0 ); + handle.position.copy( this.worldPosition ); + + let factor; + + if ( this.camera.isOrthographicCamera ) { + + factor = ( this.camera.top - this.camera.bottom ) / this.camera.zoom; + + } else { + + factor = this.worldPosition.distanceTo( this.cameraPosition ) * Math.min( 1.9 * Math.tan( Math.PI * this.camera.fov / 360 ) / this.camera.zoom, 7 ); + + } + + handle.scale.set( 1, 1, 1 ).multiplyScalar( factor * this.size / 4 ); + + // TODO: simplify helpers and consider decoupling from gizmo + + if ( handle.tag === 'helper' ) { + + handle.visible = false; + + if ( handle.name === 'AXIS' ) { + + handle.visible = !! this.axis; + + if ( this.axis === 'X' ) { + + _tempQuaternion.setFromEuler( _tempEuler.set( 0, 0, 0 ) ); + handle.quaternion.copy( quaternion ).multiply( _tempQuaternion ); + + if ( Math.abs( _alignVector.copy( _unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) { + + handle.visible = false; + + } + + } + + if ( this.axis === 'Y' ) { + + _tempQuaternion.setFromEuler( _tempEuler.set( 0, 0, Math.PI / 2 ) ); + handle.quaternion.copy( quaternion ).multiply( _tempQuaternion ); + + if ( Math.abs( _alignVector.copy( _unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) { + + handle.visible = false; + + } + + } + + if ( this.axis === 'Z' ) { + + _tempQuaternion.setFromEuler( _tempEuler.set( 0, Math.PI / 2, 0 ) ); + handle.quaternion.copy( quaternion ).multiply( _tempQuaternion ); + + if ( Math.abs( _alignVector.copy( _unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) { + + handle.visible = false; + + } + + } + + if ( this.axis === 'XYZE' ) { + + _tempQuaternion.setFromEuler( _tempEuler.set( 0, Math.PI / 2, 0 ) ); + _alignVector.copy( this.rotationAxis ); + handle.quaternion.setFromRotationMatrix( _lookAtMatrix.lookAt( _zeroVector, _alignVector, _unitY ) ); + handle.quaternion.multiply( _tempQuaternion ); + handle.visible = this.dragging; + + } + + if ( this.axis === 'E' ) { + + handle.visible = false; + + } + + + } else if ( handle.name === 'START' ) { + + handle.position.copy( this.worldPositionStart ); + handle.visible = this.dragging; + + } else if ( handle.name === 'END' ) { + + handle.position.copy( this.worldPosition ); + handle.visible = this.dragging; + + } else if ( handle.name === 'DELTA' ) { + + handle.position.copy( this.worldPositionStart ); + handle.quaternion.copy( this.worldQuaternionStart ); + _tempVector.set( 1e-10, 1e-10, 1e-10 ).add( this.worldPositionStart ).sub( this.worldPosition ).multiplyScalar( - 1 ); + _tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() ); + handle.scale.copy( _tempVector ); + handle.visible = this.dragging; + + } else { + + handle.quaternion.copy( quaternion ); + + if ( this.dragging ) { + + handle.position.copy( this.worldPositionStart ); + + } else { + + handle.position.copy( this.worldPosition ); + + } + + if ( this.axis ) { + + handle.visible = this.axis.search( handle.name ) !== - 1; + + } + + } + + // If updating helper, skip rest of the loop + continue; + + } + + // Align handles to current local or world rotation + + handle.quaternion.copy( quaternion ); + + if ( this.mode === 'translate' || this.mode === 'scale' ) { + + // Hide translate and scale axis facing the camera + + const AXIS_HIDE_THRESHOLD = 0.99; + const PLANE_HIDE_THRESHOLD = 0.2; + + if ( handle.name === 'X' ) { + + if ( Math.abs( _alignVector.copy( _unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + if ( handle.name === 'Y' ) { + + if ( Math.abs( _alignVector.copy( _unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + if ( handle.name === 'Z' ) { + + if ( Math.abs( _alignVector.copy( _unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + if ( handle.name === 'XY' ) { + + if ( Math.abs( _alignVector.copy( _unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + if ( handle.name === 'YZ' ) { + + if ( Math.abs( _alignVector.copy( _unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + if ( handle.name === 'XZ' ) { + + if ( Math.abs( _alignVector.copy( _unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_THRESHOLD ) { + + handle.scale.set( 1e-10, 1e-10, 1e-10 ); + handle.visible = false; + + } + + } + + } else if ( this.mode === 'rotate' ) { + + // Align handles to current local or world rotation + + _tempQuaternion2.copy( quaternion ); + _alignVector.copy( this.eye ).applyQuaternion( _tempQuaternion.copy( quaternion ).invert() ); + + if ( handle.name.search( 'E' ) !== - 1 ) { + + handle.quaternion.setFromRotationMatrix( _lookAtMatrix.lookAt( this.eye, _zeroVector, _unitY ) ); + + } + + if ( handle.name === 'X' ) { + + _tempQuaternion.setFromAxisAngle( _unitX, Math.atan2( - _alignVector.y, _alignVector.z ) ); + _tempQuaternion.multiplyQuaternions( _tempQuaternion2, _tempQuaternion ); + handle.quaternion.copy( _tempQuaternion ); + + } + + if ( handle.name === 'Y' ) { + + _tempQuaternion.setFromAxisAngle( _unitY, Math.atan2( _alignVector.x, _alignVector.z ) ); + _tempQuaternion.multiplyQuaternions( _tempQuaternion2, _tempQuaternion ); + handle.quaternion.copy( _tempQuaternion ); + + } + + if ( handle.name === 'Z' ) { + + _tempQuaternion.setFromAxisAngle( _unitZ, Math.atan2( _alignVector.y, _alignVector.x ) ); + _tempQuaternion.multiplyQuaternions( _tempQuaternion2, _tempQuaternion ); + handle.quaternion.copy( _tempQuaternion ); + + } + + } + + // Hide disabled axes + handle.visible = handle.visible && ( handle.name.indexOf( 'X' ) === - 1 || this.showX ); + handle.visible = handle.visible && ( handle.name.indexOf( 'Y' ) === - 1 || this.showY ); + handle.visible = handle.visible && ( handle.name.indexOf( 'Z' ) === - 1 || this.showZ ); + handle.visible = handle.visible && ( handle.name.indexOf( 'E' ) === - 1 || ( this.showX && this.showY && this.showZ ) ); + + // highlight selected axis + + handle.material._color = handle.material._color || handle.material.color.clone(); + handle.material._opacity = handle.material._opacity || handle.material.opacity; + + handle.material.color.copy( handle.material._color ); + handle.material.opacity = handle.material._opacity; + + if ( this.enabled && this.axis ) { + + if ( handle.name === this.axis ) { + + handle.material.color.setHex( 0xffff00 ); + handle.material.opacity = 1.0; + + } else if ( this.axis.split( '' ).some( function ( a ) { + + return handle.name === a; + + } ) ) { + + handle.material.color.setHex( 0xffff00 ); + handle.material.opacity = 1.0; + + } + + } + + } + + super.updateMatrixWorld( force ); + + } + +} + +// + +class TransformControlsPlane extends Mesh { + + constructor() { + + super( + new PlaneGeometry( 100000, 100000, 2, 2 ), + new MeshBasicMaterial( { visible: false, wireframe: true, side: DoubleSide, transparent: true, opacity: 0.1, toneMapped: false } ) + ); + + this.isTransformControlsPlane = true; + + this.type = 'TransformControlsPlane'; + + } + + updateMatrixWorld( force ) { + + let space = this.space; + + this.position.copy( this.worldPosition ); + + if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation + + _v1.copy( _unitX ).applyQuaternion( space === 'local' ? this.worldQuaternion : _identityQuaternion ); + _v2.copy( _unitY ).applyQuaternion( space === 'local' ? this.worldQuaternion : _identityQuaternion ); + _v3.copy( _unitZ ).applyQuaternion( space === 'local' ? this.worldQuaternion : _identityQuaternion ); + + // Align the plane for current transform mode, axis and space. + + _alignVector.copy( _v2 ); + + switch ( this.mode ) { + + case 'translate': + case 'scale': + switch ( this.axis ) { + + case 'X': + _alignVector.copy( this.eye ).cross( _v1 ); + _dirVector.copy( _v1 ).cross( _alignVector ); + break; + case 'Y': + _alignVector.copy( this.eye ).cross( _v2 ); + _dirVector.copy( _v2 ).cross( _alignVector ); + break; + case 'Z': + _alignVector.copy( this.eye ).cross( _v3 ); + _dirVector.copy( _v3 ).cross( _alignVector ); + break; + case 'XY': + _dirVector.copy( _v3 ); + break; + case 'YZ': + _dirVector.copy( _v1 ); + break; + case 'XZ': + _alignVector.copy( _v3 ); + _dirVector.copy( _v2 ); + break; + case 'XYZ': + case 'E': + _dirVector.set( 0, 0, 0 ); + break; + + } + + break; + case 'rotate': + default: + // special case for rotate + _dirVector.set( 0, 0, 0 ); + + } + + if ( _dirVector.length() === 0 ) { + + // If in rotate mode, make the plane parallel to camera + this.quaternion.copy( this.cameraQuaternion ); + + } else { + + _tempMatrix.lookAt( _tempVector.set( 0, 0, 0 ), _dirVector, _alignVector ); + + this.quaternion.setFromRotationMatrix( _tempMatrix ); + + } + + super.updateMatrixWorld( force ); + + } + +} + +export { TransformControls, TransformControlsGizmo, TransformControlsPlane }; diff --git a/renderer/jsm/csm/CSM.js b/renderer/jsm/csm/CSM.js new file mode 100644 index 0000000..055275a --- /dev/null +++ b/renderer/jsm/csm/CSM.js @@ -0,0 +1,386 @@ +import { + Vector2, + Vector3, + DirectionalLight, + MathUtils, + ShaderChunk, + Matrix4, + Box3 +} from 'three'; +import { CSMFrustum } from './CSMFrustum.js'; +import { CSMShader } from './CSMShader.js'; + +const _cameraToLightMatrix = new Matrix4(); +const _lightSpaceFrustum = new CSMFrustum(); +const _center = new Vector3(); +const _bbox = new Box3(); +const _uniformArray = []; +const _logArray = []; +const _lightOrientationMatrix = new Matrix4(); +const _lightOrientationMatrixInverse = new Matrix4(); +const _up = new Vector3( 0, 1, 0 ); + +export class CSM { + + constructor( data ) { + + data = data || {}; + + this.camera = data.camera; + this.parent = data.parent; + this.cascades = data.cascades || 3; + this.maxFar = data.maxFar || 100000; + this.mode = data.mode || 'practical'; + this.shadowMapSize = data.shadowMapSize || 2048; + this.shadowBias = data.shadowBias || 0.000001; + this.lightDirection = data.lightDirection || new Vector3( 1, - 1, 1 ).normalize(); + this.lightIntensity = data.lightIntensity || 1; + this.lightNear = data.lightNear || 1; + this.lightFar = data.lightFar || 2000; + this.lightMargin = data.lightMargin || 200; + this.customSplitsCallback = data.customSplitsCallback; + this.fade = false; + this.mainFrustum = new CSMFrustum(); + this.frustums = []; + this.breaks = []; + + this.lights = []; + this.shaders = new Map(); + + this.createLights(); + this.updateFrustums(); + this.injectInclude(); + + } + + createLights() { + + for ( let i = 0; i < this.cascades; i ++ ) { + + const light = new DirectionalLight( 0xffffff, this.lightIntensity ); + light.castShadow = true; + light.shadow.mapSize.width = this.shadowMapSize; + light.shadow.mapSize.height = this.shadowMapSize; + + light.shadow.camera.near = this.lightNear; + light.shadow.camera.far = this.lightFar; + light.shadow.bias = this.shadowBias; + + this.parent.add( light ); + this.parent.add( light.target ); + this.lights.push( light ); + + } + + } + + initCascades() { + + const camera = this.camera; + camera.updateProjectionMatrix(); + this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar ); + this.mainFrustum.split( this.breaks, this.frustums ); + + } + + updateShadowBounds() { + + const frustums = this.frustums; + for ( let i = 0; i < frustums.length; i ++ ) { + + const light = this.lights[ i ]; + const shadowCam = light.shadow.camera; + const frustum = this.frustums[ i ]; + + // Get the two points that represent that furthest points on the frustum assuming + // that's either the diagonal across the far plane or the diagonal across the whole + // frustum itself. + const nearVerts = frustum.vertices.near; + const farVerts = frustum.vertices.far; + const point1 = farVerts[ 0 ]; + let point2; + if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) { + + point2 = farVerts[ 2 ]; + + } else { + + point2 = nearVerts[ 2 ]; + + } + + let squaredBBWidth = point1.distanceTo( point2 ); + if ( this.fade ) { + + // expand the shadow extents by the fade margin if fade is enabled. + const camera = this.camera; + const far = Math.max( camera.far, this.maxFar ); + const linearDepth = frustum.vertices.far[ 0 ].z / ( far - camera.near ); + const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near ); + + squaredBBWidth += margin; + + } + + shadowCam.left = - squaredBBWidth / 2; + shadowCam.right = squaredBBWidth / 2; + shadowCam.top = squaredBBWidth / 2; + shadowCam.bottom = - squaredBBWidth / 2; + shadowCam.updateProjectionMatrix(); + + } + + } + + getBreaks() { + + const camera = this.camera; + const far = Math.min( camera.far, this.maxFar ); + this.breaks.length = 0; + + switch ( this.mode ) { + + case 'uniform': + uniformSplit( this.cascades, camera.near, far, this.breaks ); + break; + case 'logarithmic': + logarithmicSplit( this.cascades, camera.near, far, this.breaks ); + break; + case 'practical': + practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks ); + break; + case 'custom': + if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' ); + this.customSplitsCallback( this.cascades, camera.near, far, this.breaks ); + break; + + } + + function uniformSplit( amount, near, far, target ) { + + for ( let i = 1; i < amount; i ++ ) { + + target.push( ( near + ( far - near ) * i / amount ) / far ); + + } + + target.push( 1 ); + + } + + function logarithmicSplit( amount, near, far, target ) { + + for ( let i = 1; i < amount; i ++ ) { + + target.push( ( near * ( far / near ) ** ( i / amount ) ) / far ); + + } + + target.push( 1 ); + + } + + function practicalSplit( amount, near, far, lambda, target ) { + + _uniformArray.length = 0; + _logArray.length = 0; + logarithmicSplit( amount, near, far, _logArray ); + uniformSplit( amount, near, far, _uniformArray ); + + for ( let i = 1; i < amount; i ++ ) { + + target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) ); + + } + + target.push( 1 ); + + } + + } + + update() { + + const camera = this.camera; + const frustums = this.frustums; + + // for each frustum we need to find its min-max box aligned with the light orientation + // the position in _lightOrientationMatrix does not matter, as we transform there and back + _lightOrientationMatrix.lookAt( new Vector3(), this.lightDirection, _up ); + _lightOrientationMatrixInverse.copy( _lightOrientationMatrix ).invert(); + + for ( let i = 0; i < frustums.length; i ++ ) { + + const light = this.lights[ i ]; + const shadowCam = light.shadow.camera; + const texelWidth = ( shadowCam.right - shadowCam.left ) / this.shadowMapSize; + const texelHeight = ( shadowCam.top - shadowCam.bottom ) / this.shadowMapSize; + _cameraToLightMatrix.multiplyMatrices( _lightOrientationMatrixInverse, camera.matrixWorld ); + frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum ); + + const nearVerts = _lightSpaceFrustum.vertices.near; + const farVerts = _lightSpaceFrustum.vertices.far; + _bbox.makeEmpty(); + for ( let j = 0; j < 4; j ++ ) { + + _bbox.expandByPoint( nearVerts[ j ] ); + _bbox.expandByPoint( farVerts[ j ] ); + + } + + _bbox.getCenter( _center ); + _center.z = _bbox.max.z + this.lightMargin; + _center.x = Math.floor( _center.x / texelWidth ) * texelWidth; + _center.y = Math.floor( _center.y / texelHeight ) * texelHeight; + _center.applyMatrix4( _lightOrientationMatrix ); + + light.position.copy( _center ); + light.target.position.copy( _center ); + + light.target.position.x += this.lightDirection.x; + light.target.position.y += this.lightDirection.y; + light.target.position.z += this.lightDirection.z; + + } + + } + + injectInclude() { + + ShaderChunk.lights_fragment_begin = CSMShader.lights_fragment_begin; + ShaderChunk.lights_pars_begin = CSMShader.lights_pars_begin; + + } + + setupMaterial( material ) { + + material.defines = material.defines || {}; + material.defines.USE_CSM = 1; + material.defines.CSM_CASCADES = this.cascades; + + if ( this.fade ) { + + material.defines.CSM_FADE = ''; + + } + + const breaksVec2 = []; + const scope = this; + const shaders = this.shaders; + + material.onBeforeCompile = function ( shader ) { + + const far = Math.min( scope.camera.far, scope.maxFar ); + scope.getExtendedBreaks( breaksVec2 ); + + shader.uniforms.CSM_cascades = { value: breaksVec2 }; + shader.uniforms.cameraNear = { value: scope.camera.near }; + shader.uniforms.shadowFar = { value: far }; + + shaders.set( material, shader ); + + }; + + shaders.set( material, null ); + + } + + updateUniforms() { + + const far = Math.min( this.camera.far, this.maxFar ); + const shaders = this.shaders; + + shaders.forEach( function ( shader, material ) { + + if ( shader !== null ) { + + const uniforms = shader.uniforms; + this.getExtendedBreaks( uniforms.CSM_cascades.value ); + uniforms.cameraNear.value = this.camera.near; + uniforms.shadowFar.value = far; + + } + + if ( ! this.fade && 'CSM_FADE' in material.defines ) { + + delete material.defines.CSM_FADE; + material.needsUpdate = true; + + } else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) { + + material.defines.CSM_FADE = ''; + material.needsUpdate = true; + + } + + }, this ); + + } + + getExtendedBreaks( target ) { + + while ( target.length < this.breaks.length ) { + + target.push( new Vector2() ); + + } + + target.length = this.breaks.length; + + for ( let i = 0; i < this.cascades; i ++ ) { + + const amount = this.breaks[ i ]; + const prev = this.breaks[ i - 1 ] || 0; + target[ i ].x = prev; + target[ i ].y = amount; + + } + + } + + updateFrustums() { + + this.getBreaks(); + this.initCascades(); + this.updateShadowBounds(); + this.updateUniforms(); + + } + + remove() { + + for ( let i = 0; i < this.lights.length; i ++ ) { + + this.parent.remove( this.lights[ i ].target ); + this.parent.remove( this.lights[ i ] ); + + } + + } + + dispose() { + + const shaders = this.shaders; + shaders.forEach( function ( shader, material ) { + + delete material.onBeforeCompile; + delete material.defines.USE_CSM; + delete material.defines.CSM_CASCADES; + delete material.defines.CSM_FADE; + + if ( shader !== null ) { + + delete shader.uniforms.CSM_cascades; + delete shader.uniforms.cameraNear; + delete shader.uniforms.shadowFar; + + } + + material.needsUpdate = true; + + } ); + shaders.clear(); + + } + +} diff --git a/renderer/jsm/csm/CSMFrustum.js b/renderer/jsm/csm/CSMFrustum.js new file mode 100644 index 0000000..2d968be --- /dev/null +++ b/renderer/jsm/csm/CSMFrustum.js @@ -0,0 +1,152 @@ +import { Vector3, Matrix4 } from 'three'; + +const inverseProjectionMatrix = new Matrix4(); + +class CSMFrustum { + + constructor( data ) { + + data = data || {}; + + this.vertices = { + near: [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ], + far: [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ] + }; + + if ( data.projectionMatrix !== undefined ) { + + this.setFromProjectionMatrix( data.projectionMatrix, data.maxFar || 10000 ); + + } + + } + + setFromProjectionMatrix( projectionMatrix, maxFar ) { + + const isOrthographic = projectionMatrix.elements[ 2 * 4 + 3 ] === 0; + + inverseProjectionMatrix.copy( projectionMatrix ).invert(); + + // 3 --- 0 vertices.near/far order + // | | + // 2 --- 1 + // clip space spans from [-1, 1] + + this.vertices.near[ 0 ].set( 1, 1, - 1 ); + this.vertices.near[ 1 ].set( 1, - 1, - 1 ); + this.vertices.near[ 2 ].set( - 1, - 1, - 1 ); + this.vertices.near[ 3 ].set( - 1, 1, - 1 ); + this.vertices.near.forEach( function ( v ) { + + v.applyMatrix4( inverseProjectionMatrix ); + + } ); + + this.vertices.far[ 0 ].set( 1, 1, 1 ); + this.vertices.far[ 1 ].set( 1, - 1, 1 ); + this.vertices.far[ 2 ].set( - 1, - 1, 1 ); + this.vertices.far[ 3 ].set( - 1, 1, 1 ); + this.vertices.far.forEach( function ( v ) { + + v.applyMatrix4( inverseProjectionMatrix ); + + const absZ = Math.abs( v.z ); + if ( isOrthographic ) { + + v.z *= Math.min( maxFar / absZ, 1.0 ); + + } else { + + v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) ); + + } + + } ); + + return this.vertices; + + } + + split( breaks, target ) { + + while ( breaks.length > target.length ) { + + target.push( new CSMFrustum() ); + + } + + target.length = breaks.length; + + for ( let i = 0; i < breaks.length; i ++ ) { + + const cascade = target[ i ]; + + if ( i === 0 ) { + + for ( let j = 0; j < 4; j ++ ) { + + cascade.vertices.near[ j ].copy( this.vertices.near[ j ] ); + + } + + } else { + + for ( let j = 0; j < 4; j ++ ) { + + cascade.vertices.near[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] ); + + } + + } + + if ( i === breaks.length - 1 ) { + + for ( let j = 0; j < 4; j ++ ) { + + cascade.vertices.far[ j ].copy( this.vertices.far[ j ] ); + + } + + } else { + + for ( let j = 0; j < 4; j ++ ) { + + cascade.vertices.far[ j ].lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] ); + + } + + } + + } + + } + + toSpace( cameraMatrix, target ) { + + for ( let i = 0; i < 4; i ++ ) { + + target.vertices.near[ i ] + .copy( this.vertices.near[ i ] ) + .applyMatrix4( cameraMatrix ); + + target.vertices.far[ i ] + .copy( this.vertices.far[ i ] ) + .applyMatrix4( cameraMatrix ); + + } + + } + +} + +export { CSMFrustum }; diff --git a/renderer/jsm/csm/CSMHelper.js b/renderer/jsm/csm/CSMHelper.js new file mode 100644 index 0000000..d1cfed8 --- /dev/null +++ b/renderer/jsm/csm/CSMHelper.js @@ -0,0 +1,193 @@ +import { + Group, + Mesh, + LineSegments, + BufferGeometry, + LineBasicMaterial, + Box3Helper, + Box3, + PlaneGeometry, + MeshBasicMaterial, + BufferAttribute, + DoubleSide +} from 'three'; + +class CSMHelper extends Group { + + constructor( csm ) { + + super(); + this.csm = csm; + this.displayFrustum = true; + this.displayPlanes = true; + this.displayShadowBounds = true; + + const 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 ] ); + const positions = new Float32Array( 24 ); + const frustumGeometry = new BufferGeometry(); + frustumGeometry.setIndex( new BufferAttribute( indices, 1 ) ); + frustumGeometry.setAttribute( 'position', new BufferAttribute( positions, 3, false ) ); + const frustumLines = new LineSegments( frustumGeometry, new LineBasicMaterial() ); + this.add( frustumLines ); + + this.frustumLines = frustumLines; + this.cascadeLines = []; + this.cascadePlanes = []; + this.shadowLines = []; + + } + + updateVisibility() { + + const displayFrustum = this.displayFrustum; + const displayPlanes = this.displayPlanes; + const displayShadowBounds = this.displayShadowBounds; + + const frustumLines = this.frustumLines; + const cascadeLines = this.cascadeLines; + const cascadePlanes = this.cascadePlanes; + const shadowLines = this.shadowLines; + for ( let i = 0, l = cascadeLines.length; i < l; i ++ ) { + + const cascadeLine = cascadeLines[ i ]; + const cascadePlane = cascadePlanes[ i ]; + const shadowLineGroup = shadowLines[ i ]; + + cascadeLine.visible = displayFrustum; + cascadePlane.visible = displayFrustum && displayPlanes; + shadowLineGroup.visible = displayShadowBounds; + + } + + frustumLines.visible = displayFrustum; + + } + + update() { + + const csm = this.csm; + const camera = csm.camera; + const cascades = csm.cascades; + const mainFrustum = csm.mainFrustum; + const frustums = csm.frustums; + const lights = csm.lights; + + const frustumLines = this.frustumLines; + const frustumLinePositions = frustumLines.geometry.getAttribute( 'position' ); + const cascadeLines = this.cascadeLines; + const cascadePlanes = this.cascadePlanes; + const shadowLines = this.shadowLines; + + this.position.copy( camera.position ); + this.quaternion.copy( camera.quaternion ); + this.scale.copy( camera.scale ); + this.updateMatrixWorld( true ); + + while ( cascadeLines.length > cascades ) { + + this.remove( cascadeLines.pop() ); + this.remove( cascadePlanes.pop() ); + this.remove( shadowLines.pop() ); + + } + + while ( cascadeLines.length < cascades ) { + + const cascadeLine = new Box3Helper( new Box3(), 0xffffff ); + const planeMat = new MeshBasicMaterial( { transparent: true, opacity: 0.1, depthWrite: false, side: DoubleSide } ); + const cascadePlane = new Mesh( new PlaneGeometry(), planeMat ); + const shadowLineGroup = new Group(); + const shadowLine = new Box3Helper( new Box3(), 0xffff00 ); + shadowLineGroup.add( shadowLine ); + + this.add( cascadeLine ); + this.add( cascadePlane ); + this.add( shadowLineGroup ); + + cascadeLines.push( cascadeLine ); + cascadePlanes.push( cascadePlane ); + shadowLines.push( shadowLineGroup ); + + } + + for ( let i = 0; i < cascades; i ++ ) { + + const frustum = frustums[ i ]; + const light = lights[ i ]; + const shadowCam = light.shadow.camera; + const farVerts = frustum.vertices.far; + + const cascadeLine = cascadeLines[ i ]; + const cascadePlane = cascadePlanes[ i ]; + const shadowLineGroup = shadowLines[ i ]; + const shadowLine = shadowLineGroup.children[ 0 ]; + + cascadeLine.box.min.copy( farVerts[ 2 ] ); + cascadeLine.box.max.copy( farVerts[ 0 ] ); + cascadeLine.box.max.z += 1e-4; + + cascadePlane.position.addVectors( farVerts[ 0 ], farVerts[ 2 ] ); + cascadePlane.position.multiplyScalar( 0.5 ); + cascadePlane.scale.subVectors( farVerts[ 0 ], farVerts[ 2 ] ); + cascadePlane.scale.z = 1e-4; + + this.remove( shadowLineGroup ); + shadowLineGroup.position.copy( shadowCam.position ); + shadowLineGroup.quaternion.copy( shadowCam.quaternion ); + shadowLineGroup.scale.copy( shadowCam.scale ); + shadowLineGroup.updateMatrixWorld( true ); + this.attach( shadowLineGroup ); + + shadowLine.box.min.set( shadowCam.bottom, shadowCam.left, - shadowCam.far ); + shadowLine.box.max.set( shadowCam.top, shadowCam.right, - shadowCam.near ); + + } + + const nearVerts = mainFrustum.vertices.near; + const farVerts = mainFrustum.vertices.far; + frustumLinePositions.setXYZ( 0, farVerts[ 0 ].x, farVerts[ 0 ].y, farVerts[ 0 ].z ); + frustumLinePositions.setXYZ( 1, farVerts[ 3 ].x, farVerts[ 3 ].y, farVerts[ 3 ].z ); + frustumLinePositions.setXYZ( 2, farVerts[ 2 ].x, farVerts[ 2 ].y, farVerts[ 2 ].z ); + frustumLinePositions.setXYZ( 3, farVerts[ 1 ].x, farVerts[ 1 ].y, farVerts[ 1 ].z ); + + frustumLinePositions.setXYZ( 4, nearVerts[ 0 ].x, nearVerts[ 0 ].y, nearVerts[ 0 ].z ); + frustumLinePositions.setXYZ( 5, nearVerts[ 3 ].x, nearVerts[ 3 ].y, nearVerts[ 3 ].z ); + frustumLinePositions.setXYZ( 6, nearVerts[ 2 ].x, nearVerts[ 2 ].y, nearVerts[ 2 ].z ); + frustumLinePositions.setXYZ( 7, nearVerts[ 1 ].x, nearVerts[ 1 ].y, nearVerts[ 1 ].z ); + frustumLinePositions.needsUpdate = true; + + } + + dispose() { + + const frustumLines = this.frustumLines; + const cascadeLines = this.cascadeLines; + const cascadePlanes = this.cascadePlanes; + const shadowLines = this.shadowLines; + + frustumLines.geometry.dispose(); + frustumLines.material.dispose(); + + const cascades = this.csm.cascades; + + for ( let i = 0; i < cascades; i ++ ) { + + const cascadeLine = cascadeLines[ i ]; + const cascadePlane = cascadePlanes[ i ]; + const shadowLineGroup = shadowLines[ i ]; + const shadowLine = shadowLineGroup.children[ 0 ]; + + cascadeLine.dispose(); // Box3Helper + + cascadePlane.geometry.dispose(); + cascadePlane.material.dispose(); + + shadowLine.dispose(); // Box3Helper + + } + + } + +} + +export { CSMHelper }; diff --git a/renderer/jsm/csm/CSMShader.js b/renderer/jsm/csm/CSMShader.js new file mode 100644 index 0000000..40fa71f --- /dev/null +++ b/renderer/jsm/csm/CSMShader.js @@ -0,0 +1,252 @@ +import { ShaderChunk } from 'three'; + +const CSMShader = { + lights_fragment_begin: /* glsl */` +GeometricContext geometry; + +geometry.position = - vViewPosition; +geometry.normal = normal; +geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + +#ifdef CLEARCOAT + + geometry.clearcoatNormal = clearcoatNormal; + +#endif + +IncidentLight directLight; + +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + getPointLightInfo( pointLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + getSpotLightInfo( spotLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) + vec2 cascade; + float cascadeCenter; + float closestEdge; + float margin; + float csmx; + float csmy; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + // NOTE: Depth gets larger away from the camera. + // cascade.x is closer, cascade.y is further + cascade = CSM_cascades[ i ]; + cascadeCenter = ( cascade.x + cascade.y ) / 2.0; + closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; + margin = 0.25 * pow( closestEdge, 2.0 ); + csmx = cascade.x - margin / 2.0; + csmy = cascade.y + margin / 2.0; + if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + + float dist = min( linearDepth - csmx, csmy - linearDepth ); + float ratio = clamp( dist / margin, 0.0, 1.0 ); + + vec3 prevColor = directLight.color; + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; + directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + + ReflectedLight prevLight = reflectedLight; + RE_Direct( directLight, geometry, material, reflectedLight ); + + bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; + float blendRatio = shouldBlend ? ratio : 1.0; + + reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); + reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); + reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); + reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + + } + #endif + + } + #pragma unroll_loop_end + #else + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + + directionalLightShadow = directionalLightShadows[ i ]; + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometry, material, reflectedLight ); + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) + // compute the lights not casting shadows (if any) + + #pragma unroll_loop_start + for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, geometry, directLight ); + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + #pragma unroll_loop_end + + #endif + +#endif + + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometry, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + + RectAreaLight rectAreaLight; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + + } + #pragma unroll_loop_end + + #endif + +#endif + +#if defined( RE_IndirectSpecular ) + + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); + +#endif +`, + lights_pars_begin: /* glsl */` +#if defined( USE_CSM ) && defined( CSM_CASCADES ) +uniform vec2 CSM_cascades[CSM_CASCADES]; +uniform float cameraNear; +uniform float shadowFar; +#endif + ` + ShaderChunk.lights_pars_begin +}; + +export { CSMShader }; diff --git a/renderer/jsm/curves/CurveExtras.js b/renderer/jsm/curves/CurveExtras.js new file mode 100644 index 0000000..51efb84 --- /dev/null +++ b/renderer/jsm/curves/CurveExtras.js @@ -0,0 +1,422 @@ +import { + Curve, + Vector3 +} from 'three'; + +/** + * A bunch of parametric curves + * + * Formulas collected from various sources + * http://mathworld.wolfram.com/HeartCurve.html + * http://en.wikipedia.org/wiki/Viviani%27s_curve + * http://www.mi.sanu.ac.rs/vismath/taylorapril2011/Taylor.pdf + * https://prideout.net/blog/old/blog/index.html@p=44.html + */ + +// GrannyKnot + +class GrannyKnot extends Curve { + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t = 2 * Math.PI * t; + + const x = - 0.22 * Math.cos( t ) - 1.28 * Math.sin( t ) - 0.44 * Math.cos( 3 * t ) - 0.78 * Math.sin( 3 * t ); + const y = - 0.1 * Math.cos( 2 * t ) - 0.27 * Math.sin( 2 * t ) + 0.38 * Math.cos( 4 * t ) + 0.46 * Math.sin( 4 * t ); + const z = 0.7 * Math.cos( 3 * t ) - 0.4 * Math.sin( 3 * t ); + + return point.set( x, y, z ).multiplyScalar( 20 ); + + } + +} + +// HeartCurve + +class HeartCurve extends Curve { + + constructor( scale = 5 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t *= 2 * Math.PI; + + const x = 16 * Math.pow( Math.sin( t ), 3 ); + const y = 13 * Math.cos( t ) - 5 * Math.cos( 2 * t ) - 2 * Math.cos( 3 * t ) - Math.cos( 4 * t ); + const z = 0; + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// Viviani's Curve + +class VivianiCurve extends Curve { + + constructor( scale = 70 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t = t * 4 * Math.PI; // normalized to 0..1 + const a = this.scale / 2; + + const x = a * ( 1 + Math.cos( t ) ); + const y = a * Math.sin( t ); + const z = 2 * a * Math.sin( t / 2 ); + + return point.set( x, y, z ); + + } + +} + +// KnotCurve + +class KnotCurve extends Curve { + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t *= 2 * Math.PI; + + const R = 10; + const s = 50; + + const x = s * Math.sin( t ); + const y = Math.cos( t ) * ( R + s * Math.cos( t ) ); + const z = Math.sin( t ) * ( R + s * Math.cos( t ) ); + + return point.set( x, y, z ); + + } + +} + + +// HelixCurve + +class HelixCurve extends Curve { + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const a = 30; // radius + const b = 150; // height + + const t2 = 2 * Math.PI * t * b / 30; + + const x = Math.cos( t2 ) * a; + const y = Math.sin( t2 ) * a; + const z = b * t; + + return point.set( x, y, z ); + + } + +} + +// TrefoilKnot + +class TrefoilKnot extends Curve { + + constructor( scale = 10 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t *= Math.PI * 2; + + const x = ( 2 + Math.cos( 3 * t ) ) * Math.cos( 2 * t ); + const y = ( 2 + Math.cos( 3 * t ) ) * Math.sin( 2 * t ); + const z = Math.sin( 3 * t ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// TorusKnot + +class TorusKnot extends Curve { + + constructor( scale = 10 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const p = 3; + const q = 4; + + t *= Math.PI * 2; + + const x = ( 2 + Math.cos( q * t ) ) * Math.cos( p * t ); + const y = ( 2 + Math.cos( q * t ) ) * Math.sin( p * t ); + const z = Math.sin( q * t ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// CinquefoilKnot + +class CinquefoilKnot extends Curve { + + constructor( scale = 10 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const p = 2; + const q = 5; + + t *= Math.PI * 2; + + const x = ( 2 + Math.cos( q * t ) ) * Math.cos( p * t ); + const y = ( 2 + Math.cos( q * t ) ) * Math.sin( p * t ); + const z = Math.sin( q * t ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + + +// TrefoilPolynomialKnot + +class TrefoilPolynomialKnot extends Curve { + + constructor( scale = 10 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t = t * 4 - 2; + + const x = Math.pow( t, 3 ) - 3 * t; + const y = Math.pow( t, 4 ) - 4 * t * t; + const z = 1 / 5 * Math.pow( t, 5 ) - 2 * t; + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +function scaleTo( x, y, t ) { + + const r = y - x; + return t * r + x; + +} + +// FigureEightPolynomialKnot + +class FigureEightPolynomialKnot extends Curve { + + constructor( scale = 1 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t = scaleTo( - 4, 4, t ); + + const x = 2 / 5 * t * ( t * t - 7 ) * ( t * t - 10 ); + const y = Math.pow( t, 4 ) - 13 * t * t; + const z = 1 / 10 * t * ( t * t - 4 ) * ( t * t - 9 ) * ( t * t - 12 ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// DecoratedTorusKnot4a + +class DecoratedTorusKnot4a extends Curve { + + constructor( scale = 40 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t *= Math.PI * 2; + + const x = Math.cos( 2 * t ) * ( 1 + 0.6 * ( Math.cos( 5 * t ) + 0.75 * Math.cos( 10 * t ) ) ); + const y = Math.sin( 2 * t ) * ( 1 + 0.6 * ( Math.cos( 5 * t ) + 0.75 * Math.cos( 10 * t ) ) ); + const z = 0.35 * Math.sin( 5 * t ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// DecoratedTorusKnot4b + +class DecoratedTorusKnot4b extends Curve { + + constructor( scale = 40 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const fi = t * Math.PI * 2; + + const x = Math.cos( 2 * fi ) * ( 1 + 0.45 * Math.cos( 3 * fi ) + 0.4 * Math.cos( 9 * fi ) ); + const y = Math.sin( 2 * fi ) * ( 1 + 0.45 * Math.cos( 3 * fi ) + 0.4 * Math.cos( 9 * fi ) ); + const z = 0.2 * Math.sin( 9 * fi ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + + +// DecoratedTorusKnot5a + +class DecoratedTorusKnot5a extends Curve { + + constructor( scale = 40 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const fi = t * Math.PI * 2; + + const x = Math.cos( 3 * fi ) * ( 1 + 0.3 * Math.cos( 5 * fi ) + 0.5 * Math.cos( 10 * fi ) ); + const y = Math.sin( 3 * fi ) * ( 1 + 0.3 * Math.cos( 5 * fi ) + 0.5 * Math.cos( 10 * fi ) ); + const z = 0.2 * Math.sin( 20 * fi ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +// DecoratedTorusKnot5c + +class DecoratedTorusKnot5c extends Curve { + + constructor( scale = 40 ) { + + super(); + + this.scale = scale; + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const fi = t * Math.PI * 2; + + const x = Math.cos( 4 * fi ) * ( 1 + 0.5 * ( Math.cos( 5 * fi ) + 0.4 * Math.cos( 20 * fi ) ) ); + const y = Math.sin( 4 * fi ) * ( 1 + 0.5 * ( Math.cos( 5 * fi ) + 0.4 * Math.cos( 20 * fi ) ) ); + const z = 0.35 * Math.sin( 15 * fi ); + + return point.set( x, y, z ).multiplyScalar( this.scale ); + + } + +} + +export { + GrannyKnot, + HeartCurve, + VivianiCurve, + KnotCurve, + HelixCurve, + TrefoilKnot, + TorusKnot, + CinquefoilKnot, + TrefoilPolynomialKnot, + FigureEightPolynomialKnot, + DecoratedTorusKnot4a, + DecoratedTorusKnot4b, + DecoratedTorusKnot5a, + DecoratedTorusKnot5c +}; diff --git a/renderer/jsm/curves/NURBSCurve.js b/renderer/jsm/curves/NURBSCurve.js new file mode 100644 index 0000000..8be8dde --- /dev/null +++ b/renderer/jsm/curves/NURBSCurve.js @@ -0,0 +1,80 @@ +import { + Curve, + Vector3, + Vector4 +} from 'three'; +import * as NURBSUtils from '../curves/NURBSUtils.js'; + +/** + * NURBS curve object + * + * Derives from Curve, overriding getPoint and getTangent. + * + * Implementation is based on (x, y [, z=0 [, w=1]]) control points with w=weight. + * + **/ + +class NURBSCurve extends Curve { + + constructor( + degree, + knots /* array of reals */, + controlPoints /* array of Vector(2|3|4) */, + startKnot /* index in knots */, + endKnot /* index in knots */ + ) { + + super(); + + this.degree = degree; + this.knots = knots; + this.controlPoints = []; + // Used by periodic NURBS to remove hidden spans + this.startKnot = startKnot || 0; + this.endKnot = endKnot || ( this.knots.length - 1 ); + + for ( let i = 0; i < controlPoints.length; ++ i ) { + + // ensure Vector4 for control points + const point = controlPoints[ i ]; + this.controlPoints[ i ] = new Vector4( point.x, point.y, point.z, point.w ); + + } + + } + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const u = this.knots[ this.startKnot ] + t * ( this.knots[ this.endKnot ] - this.knots[ this.startKnot ] ); // linear mapping t->u + + // following results in (wx, wy, wz, w) homogeneous point + const hpoint = NURBSUtils.calcBSplinePoint( this.degree, this.knots, this.controlPoints, u ); + + if ( hpoint.w !== 1.0 ) { + + // project to 3D space: (wx, wy, wz, w) -> (x, y, z, 1) + hpoint.divideScalar( hpoint.w ); + + } + + return point.set( hpoint.x, hpoint.y, hpoint.z ); + + } + + getTangent( t, optionalTarget = new Vector3() ) { + + const tangent = optionalTarget; + + const u = this.knots[ 0 ] + t * ( this.knots[ this.knots.length - 1 ] - this.knots[ 0 ] ); + const ders = NURBSUtils.calcNURBSDerivatives( this.degree, this.knots, this.controlPoints, u, 1 ); + tangent.copy( ders[ 1 ] ).normalize(); + + return tangent; + + } + +} + +export { NURBSCurve }; diff --git a/renderer/jsm/curves/NURBSSurface.js b/renderer/jsm/curves/NURBSSurface.js new file mode 100644 index 0000000..577ecfc --- /dev/null +++ b/renderer/jsm/curves/NURBSSurface.js @@ -0,0 +1,52 @@ +import { + Vector4 +} from 'three'; +import * as NURBSUtils from '../curves/NURBSUtils.js'; + +/** + * NURBS surface object + * + * Implementation is based on (x, y [, z=0 [, w=1]]) control points with w=weight. + **/ + +class NURBSSurface { + + constructor( degree1, degree2, knots1, knots2 /* arrays of reals */, controlPoints /* array^2 of Vector(2|3|4) */ ) { + + this.degree1 = degree1; + this.degree2 = degree2; + this.knots1 = knots1; + this.knots2 = knots2; + this.controlPoints = []; + + const len1 = knots1.length - degree1 - 1; + const len2 = knots2.length - degree2 - 1; + + // ensure Vector4 for control points + for ( let i = 0; i < len1; ++ i ) { + + this.controlPoints[ i ] = []; + + for ( let j = 0; j < len2; ++ j ) { + + const point = controlPoints[ i ][ j ]; + this.controlPoints[ i ][ j ] = new Vector4( point.x, point.y, point.z, point.w ); + + } + + } + + } + + getPoint( t1, t2, target ) { + + const u = this.knots1[ 0 ] + t1 * ( this.knots1[ this.knots1.length - 1 ] - this.knots1[ 0 ] ); // linear mapping t1->u + const v = this.knots2[ 0 ] + t2 * ( this.knots2[ this.knots2.length - 1 ] - this.knots2[ 0 ] ); // linear mapping t2->u + + NURBSUtils.calcSurfacePoint( this.degree1, this.degree2, this.knots1, this.knots2, this.controlPoints, u, v, target ); + + } + +} + +export { NURBSSurface }; diff --git a/renderer/jsm/curves/NURBSUtils.js b/renderer/jsm/curves/NURBSUtils.js new file mode 100644 index 0000000..fc77fdb --- /dev/null +++ b/renderer/jsm/curves/NURBSUtils.js @@ -0,0 +1,487 @@ +import { + Vector3, + Vector4 +} from 'three'; + +/** + * NURBS utils + * + * See NURBSCurve and NURBSSurface. + **/ + + +/************************************************************** + * NURBS Utils + **************************************************************/ + +/* +Finds knot vector span. + +p : degree +u : parametric value +U : knot vector + +returns the span +*/ +function findSpan( p, u, U ) { + + const n = U.length - p - 1; + + if ( u >= U[ n ] ) { + + return n - 1; + + } + + if ( u <= U[ p ] ) { + + return p; + + } + + let low = p; + let high = n; + let mid = Math.floor( ( low + high ) / 2 ); + + while ( u < U[ mid ] || u >= U[ mid + 1 ] ) { + + if ( u < U[ mid ] ) { + + high = mid; + + } else { + + low = mid; + + } + + mid = Math.floor( ( low + high ) / 2 ); + + } + + return mid; + +} + + +/* +Calculate basis functions. See The NURBS Book, page 70, algorithm A2.2 + +span : span in which u lies +u : parametric point +p : degree +U : knot vector + +returns array[p+1] with basis functions values. +*/ +function calcBasisFunctions( span, u, p, U ) { + + const N = []; + const left = []; + const right = []; + N[ 0 ] = 1.0; + + for ( let j = 1; j <= p; ++ j ) { + + left[ j ] = u - U[ span + 1 - j ]; + right[ j ] = U[ span + j ] - u; + + let saved = 0.0; + + for ( let r = 0; r < j; ++ r ) { + + const rv = right[ r + 1 ]; + const lv = left[ j - r ]; + const temp = N[ r ] / ( rv + lv ); + N[ r ] = saved + rv * temp; + saved = lv * temp; + + } + + N[ j ] = saved; + + } + + return N; + +} + + +/* +Calculate B-Spline curve points. See The NURBS Book, page 82, algorithm A3.1. + +p : degree of B-Spline +U : knot vector +P : control points (x, y, z, w) +u : parametric point + +returns point for given u +*/ +function calcBSplinePoint( p, U, P, u ) { + + const span = findSpan( p, u, U ); + const N = calcBasisFunctions( span, u, p, U ); + const C = new Vector4( 0, 0, 0, 0 ); + + for ( let j = 0; j <= p; ++ j ) { + + const point = P[ span - p + j ]; + const Nj = N[ j ]; + const wNj = point.w * Nj; + C.x += point.x * wNj; + C.y += point.y * wNj; + C.z += point.z * wNj; + C.w += point.w * Nj; + + } + + return C; + +} + + +/* +Calculate basis functions derivatives. See The NURBS Book, page 72, algorithm A2.3. + +span : span in which u lies +u : parametric point +p : degree +n : number of derivatives to calculate +U : knot vector + +returns array[n+1][p+1] with basis functions derivatives +*/ +function calcBasisFunctionDerivatives( span, u, p, n, U ) { + + const zeroArr = []; + for ( let i = 0; i <= p; ++ i ) + zeroArr[ i ] = 0.0; + + const ders = []; + + for ( let i = 0; i <= n; ++ i ) + ders[ i ] = zeroArr.slice( 0 ); + + const ndu = []; + + for ( let i = 0; i <= p; ++ i ) + ndu[ i ] = zeroArr.slice( 0 ); + + ndu[ 0 ][ 0 ] = 1.0; + + const left = zeroArr.slice( 0 ); + const right = zeroArr.slice( 0 ); + + for ( let j = 1; j <= p; ++ j ) { + + left[ j ] = u - U[ span + 1 - j ]; + right[ j ] = U[ span + j ] - u; + + let saved = 0.0; + + for ( let r = 0; r < j; ++ r ) { + + const rv = right[ r + 1 ]; + const lv = left[ j - r ]; + ndu[ j ][ r ] = rv + lv; + + const temp = ndu[ r ][ j - 1 ] / ndu[ j ][ r ]; + ndu[ r ][ j ] = saved + rv * temp; + saved = lv * temp; + + } + + ndu[ j ][ j ] = saved; + + } + + for ( let j = 0; j <= p; ++ j ) { + + ders[ 0 ][ j ] = ndu[ j ][ p ]; + + } + + for ( let r = 0; r <= p; ++ r ) { + + let s1 = 0; + let s2 = 1; + + const a = []; + for ( let i = 0; i <= p; ++ i ) { + + a[ i ] = zeroArr.slice( 0 ); + + } + + a[ 0 ][ 0 ] = 1.0; + + for ( let k = 1; k <= n; ++ k ) { + + let d = 0.0; + const rk = r - k; + const pk = p - k; + + if ( r >= k ) { + + a[ s2 ][ 0 ] = a[ s1 ][ 0 ] / ndu[ pk + 1 ][ rk ]; + d = a[ s2 ][ 0 ] * ndu[ rk ][ pk ]; + + } + + const j1 = ( rk >= - 1 ) ? 1 : - rk; + const j2 = ( r - 1 <= pk ) ? k - 1 : p - r; + + for ( let j = j1; j <= j2; ++ j ) { + + a[ s2 ][ j ] = ( a[ s1 ][ j ] - a[ s1 ][ j - 1 ] ) / ndu[ pk + 1 ][ rk + j ]; + d += a[ s2 ][ j ] * ndu[ rk + j ][ pk ]; + + } + + if ( r <= pk ) { + + a[ s2 ][ k ] = - a[ s1 ][ k - 1 ] / ndu[ pk + 1 ][ r ]; + d += a[ s2 ][ k ] * ndu[ r ][ pk ]; + + } + + ders[ k ][ r ] = d; + + const j = s1; + s1 = s2; + s2 = j; + + } + + } + + let r = p; + + for ( let k = 1; k <= n; ++ k ) { + + for ( let j = 0; j <= p; ++ j ) { + + ders[ k ][ j ] *= r; + + } + + r *= p - k; + + } + + return ders; + +} + + +/* + Calculate derivatives of a B-Spline. See The NURBS Book, page 93, algorithm A3.2. + + p : degree + U : knot vector + P : control points + u : Parametric points + nd : number of derivatives + + returns array[d+1] with derivatives + */ +function calcBSplineDerivatives( p, U, P, u, nd ) { + + const du = nd < p ? nd : p; + const CK = []; + const span = findSpan( p, u, U ); + const nders = calcBasisFunctionDerivatives( span, u, p, du, U ); + const Pw = []; + + for ( let i = 0; i < P.length; ++ i ) { + + const point = P[ i ].clone(); + const w = point.w; + + point.x *= w; + point.y *= w; + point.z *= w; + + Pw[ i ] = point; + + } + + for ( let k = 0; k <= du; ++ k ) { + + const point = Pw[ span - p ].clone().multiplyScalar( nders[ k ][ 0 ] ); + + for ( let j = 1; j <= p; ++ j ) { + + point.add( Pw[ span - p + j ].clone().multiplyScalar( nders[ k ][ j ] ) ); + + } + + CK[ k ] = point; + + } + + for ( let k = du + 1; k <= nd + 1; ++ k ) { + + CK[ k ] = new Vector4( 0, 0, 0 ); + + } + + return CK; + +} + + +/* +Calculate "K over I" + +returns k!/(i!(k-i)!) +*/ +function calcKoverI( k, i ) { + + let nom = 1; + + for ( let j = 2; j <= k; ++ j ) { + + nom *= j; + + } + + let denom = 1; + + for ( let j = 2; j <= i; ++ j ) { + + denom *= j; + + } + + for ( let j = 2; j <= k - i; ++ j ) { + + denom *= j; + + } + + return nom / denom; + +} + + +/* +Calculate derivatives (0-nd) of rational curve. See The NURBS Book, page 127, algorithm A4.2. + +Pders : result of function calcBSplineDerivatives + +returns array with derivatives for rational curve. +*/ +function calcRationalCurveDerivatives( Pders ) { + + const nd = Pders.length; + const Aders = []; + const wders = []; + + for ( let i = 0; i < nd; ++ i ) { + + const point = Pders[ i ]; + Aders[ i ] = new Vector3( point.x, point.y, point.z ); + wders[ i ] = point.w; + + } + + const CK = []; + + for ( let k = 0; k < nd; ++ k ) { + + const v = Aders[ k ].clone(); + + for ( let i = 1; i <= k; ++ i ) { + + v.sub( CK[ k - i ].clone().multiplyScalar( calcKoverI( k, i ) * wders[ i ] ) ); + + } + + CK[ k ] = v.divideScalar( wders[ 0 ] ); + + } + + return CK; + +} + + +/* +Calculate NURBS curve derivatives. See The NURBS Book, page 127, algorithm A4.2. + +p : degree +U : knot vector +P : control points in homogeneous space +u : parametric points +nd : number of derivatives + +returns array with derivatives. +*/ +function calcNURBSDerivatives( p, U, P, u, nd ) { + + const Pders = calcBSplineDerivatives( p, U, P, u, nd ); + return calcRationalCurveDerivatives( Pders ); + +} + + +/* +Calculate rational B-Spline surface point. See The NURBS Book, page 134, algorithm A4.3. + +p1, p2 : degrees of B-Spline surface +U1, U2 : knot vectors +P : control points (x, y, z, w) +u, v : parametric values + +returns point for given (u, v) +*/ +function calcSurfacePoint( p, q, U, V, P, u, v, target ) { + + const uspan = findSpan( p, u, U ); + const vspan = findSpan( q, v, V ); + const Nu = calcBasisFunctions( uspan, u, p, U ); + const Nv = calcBasisFunctions( vspan, v, q, V ); + const temp = []; + + for ( let l = 0; l <= q; ++ l ) { + + temp[ l ] = new Vector4( 0, 0, 0, 0 ); + for ( let k = 0; k <= p; ++ k ) { + + const point = P[ uspan - p + k ][ vspan - q + l ].clone(); + const w = point.w; + point.x *= w; + point.y *= w; + point.z *= w; + temp[ l ].add( point.multiplyScalar( Nu[ k ] ) ); + + } + + } + + const Sw = new Vector4( 0, 0, 0, 0 ); + for ( let l = 0; l <= q; ++ l ) { + + Sw.add( temp[ l ].multiplyScalar( Nv[ l ] ) ); + + } + + Sw.divideScalar( Sw.w ); + target.set( Sw.x, Sw.y, Sw.z ); + +} + + + +export { + findSpan, + calcBasisFunctions, + calcBSplinePoint, + calcBasisFunctionDerivatives, + calcBSplineDerivatives, + calcKoverI, + calcRationalCurveDerivatives, + calcNURBSDerivatives, + calcSurfacePoint, +}; diff --git a/renderer/jsm/effects/AnaglyphEffect.js b/renderer/jsm/effects/AnaglyphEffect.js new file mode 100644 index 0000000..a3118cb --- /dev/null +++ b/renderer/jsm/effects/AnaglyphEffect.js @@ -0,0 +1,168 @@ +import { + LinearFilter, + Matrix3, + Mesh, + NearestFilter, + OrthographicCamera, + PlaneGeometry, + RGBAFormat, + Scene, + ShaderMaterial, + StereoCamera, + WebGLRenderTarget +} from 'three'; + +class AnaglyphEffect { + + constructor( renderer, width = 512, height = 512 ) { + + // Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4 + + this.colorMatrixLeft = new Matrix3().fromArray( [ + 0.456100, - 0.0400822, - 0.0152161, + 0.500484, - 0.0378246, - 0.0205971, + 0.176381, - 0.0157589, - 0.00546856 + ] ); + + this.colorMatrixRight = new Matrix3().fromArray( [ + - 0.0434706, 0.378476, - 0.0721527, + - 0.0879388, 0.73364, - 0.112961, + - 0.00155529, - 0.0184503, 1.2264 + ] ); + + const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + + const _scene = new Scene(); + + const _stereo = new StereoCamera(); + + const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }; + + const _renderTargetL = new WebGLRenderTarget( width, height, _params ); + const _renderTargetR = new WebGLRenderTarget( width, height, _params ); + + const _material = new ShaderMaterial( { + + uniforms: { + + 'mapLeft': { value: _renderTargetL.texture }, + 'mapRight': { value: _renderTargetR.texture }, + + 'colorMatrixLeft': { value: this.colorMatrixLeft }, + 'colorMatrixRight': { value: this.colorMatrixRight } + + }, + + vertexShader: [ + + 'varying vec2 vUv;', + + 'void main() {', + + ' vUv = vec2( uv.x, uv.y );', + ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', + + '}' + + ].join( '\n' ), + + fragmentShader: [ + + 'uniform sampler2D mapLeft;', + 'uniform sampler2D mapRight;', + 'varying vec2 vUv;', + + 'uniform mat3 colorMatrixLeft;', + 'uniform mat3 colorMatrixRight;', + + // These functions implement sRGB linearization and gamma correction + + 'float lin( float c ) {', + ' return c <= 0.04045 ? c * 0.0773993808 :', + ' pow( c * 0.9478672986 + 0.0521327014, 2.4 );', + '}', + + 'vec4 lin( vec4 c ) {', + ' return vec4( lin( c.r ), lin( c.g ), lin( c.b ), c.a );', + '}', + + 'float dev( float c ) {', + ' return c <= 0.0031308 ? c * 12.92', + ' : pow( c, 0.41666 ) * 1.055 - 0.055;', + '}', + + + 'void main() {', + + ' vec2 uv = vUv;', + + ' vec4 colorL = lin( texture2D( mapLeft, uv ) );', + ' vec4 colorR = lin( texture2D( mapRight, uv ) );', + + ' vec3 color = clamp(', + ' colorMatrixLeft * colorL.rgb +', + ' colorMatrixRight * colorR.rgb, 0., 1. );', + + ' gl_FragColor = vec4(', + ' dev( color.r ), dev( color.g ), dev( color.b ),', + ' max( colorL.a, colorR.a ) );', + + '}' + + ].join( '\n' ) + + } ); + + const _mesh = new Mesh( new PlaneGeometry( 2, 2 ), _material ); + _scene.add( _mesh ); + + this.setSize = function ( width, height ) { + + renderer.setSize( width, height ); + + const pixelRatio = renderer.getPixelRatio(); + + _renderTargetL.setSize( width * pixelRatio, height * pixelRatio ); + _renderTargetR.setSize( width * pixelRatio, height * pixelRatio ); + + }; + + this.render = function ( scene, camera ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + _stereo.update( camera ); + + renderer.setRenderTarget( _renderTargetL ); + renderer.clear(); + renderer.render( scene, _stereo.cameraL ); + + renderer.setRenderTarget( _renderTargetR ); + renderer.clear(); + renderer.render( scene, _stereo.cameraR ); + + renderer.setRenderTarget( null ); + renderer.render( _scene, _camera ); + + renderer.setRenderTarget( currentRenderTarget ); + + }; + + this.dispose = function () { + + _renderTargetL.dispose(); + _renderTargetR.dispose(); + _mesh.geometry.dispose(); + _mesh.material.dispose(); + + }; + + } + +} + +export { AnaglyphEffect }; diff --git a/renderer/jsm/effects/AsciiEffect.js b/renderer/jsm/effects/AsciiEffect.js new file mode 100644 index 0000000..af5eb7f --- /dev/null +++ b/renderer/jsm/effects/AsciiEffect.js @@ -0,0 +1,263 @@ +/** + * Ascii generation is based on https://github.com/hassadee/jsascii/blob/master/jsascii.js + * + * 16 April 2012 - @blurspline + */ + +class AsciiEffect { + + constructor( renderer, charSet = ' .:-=+*#%@', options = {} ) { + + // ' .,:;=|iI+hHOE#`$'; + // darker bolder character set from https://github.com/saw/Canvas-ASCII-Art/ + // ' .\'`^",:;Il!i~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$'.split(''); + + // Some ASCII settings + + const fResolution = options[ 'resolution' ] || 0.15; // Higher for more details + const iScale = options[ 'scale' ] || 1; + const bColor = options[ 'color' ] || false; // nice but slows down rendering! + const bAlpha = options[ 'alpha' ] || false; // Transparency + const bBlock = options[ 'block' ] || false; // blocked characters. like good O dos + const bInvert = options[ 'invert' ] || false; // black is white, white is black + const strResolution = options[ 'strResolution' ] || 'low'; + + let width, height; + + const domElement = document.createElement( 'div' ); + domElement.style.cursor = 'default'; + + const oAscii = document.createElement( 'table' ); + domElement.appendChild( oAscii ); + + let iWidth, iHeight; + let oImg; + + this.setSize = function ( w, h ) { + + width = w; + height = h; + + renderer.setSize( w, h ); + + initAsciiSize(); + + }; + + + this.render = function ( scene, camera ) { + + renderer.render( scene, camera ); + asciifyImage( oAscii ); + + }; + + this.domElement = domElement; + + + // Throw in ascii library from https://github.com/hassadee/jsascii/blob/master/jsascii.js (MIT License) + + function initAsciiSize() { + + iWidth = Math.floor( width * fResolution ); + iHeight = Math.floor( height * fResolution ); + + oCanvas.width = iWidth; + oCanvas.height = iHeight; + // oCanvas.style.display = "none"; + // oCanvas.style.width = iWidth; + // oCanvas.style.height = iHeight; + + oImg = renderer.domElement; + + if ( oImg.style.backgroundColor ) { + + oAscii.rows[ 0 ].cells[ 0 ].style.backgroundColor = oImg.style.backgroundColor; + oAscii.rows[ 0 ].cells[ 0 ].style.color = oImg.style.color; + + } + + oAscii.cellSpacing = 0; + oAscii.cellPadding = 0; + + const oStyle = oAscii.style; + oStyle.whiteSpace = 'pre'; + oStyle.margin = '0px'; + oStyle.padding = '0px'; + oStyle.letterSpacing = fLetterSpacing + 'px'; + oStyle.fontFamily = strFont; + oStyle.fontSize = fFontSize + 'px'; + oStyle.lineHeight = fLineHeight + 'px'; + oStyle.textAlign = 'left'; + oStyle.textDecoration = 'none'; + + } + + + const aDefaultCharList = ( ' .,:;i1tfLCG08@' ).split( '' ); + const aDefaultColorCharList = ( ' CGO08@' ).split( '' ); + const strFont = 'courier new, monospace'; + + const oCanvasImg = renderer.domElement; + + const oCanvas = document.createElement( 'canvas' ); + if ( ! oCanvas.getContext ) { + + return; + + } + + const oCtx = oCanvas.getContext( '2d' ); + if ( ! oCtx.getImageData ) { + + return; + + } + + let aCharList = ( bColor ? aDefaultColorCharList : aDefaultCharList ); + + if ( charSet ) aCharList = charSet; + + // Setup dom + + const fFontSize = ( 2 / fResolution ) * iScale; + const fLineHeight = ( 2 / fResolution ) * iScale; + + // adjust letter-spacing for all combinations of scale and resolution to get it to fit the image width. + + let fLetterSpacing = 0; + + if ( strResolution == 'low' ) { + + switch ( iScale ) { + + case 1 : fLetterSpacing = - 1; break; + case 2 : + case 3 : fLetterSpacing = - 2.1; break; + case 4 : fLetterSpacing = - 3.1; break; + case 5 : fLetterSpacing = - 4.15; break; + + } + + } + + if ( strResolution == 'medium' ) { + + switch ( iScale ) { + + case 1 : fLetterSpacing = 0; break; + case 2 : fLetterSpacing = - 1; break; + case 3 : fLetterSpacing = - 1.04; break; + case 4 : + case 5 : fLetterSpacing = - 2.1; break; + + } + + } + + if ( strResolution == 'high' ) { + + switch ( iScale ) { + + case 1 : + case 2 : fLetterSpacing = 0; break; + case 3 : + case 4 : + case 5 : fLetterSpacing = - 1; break; + + } + + } + + + // can't get a span or div to flow like an img element, but a table works? + + + // convert img element to ascii + + function asciifyImage( oAscii ) { + + oCtx.clearRect( 0, 0, iWidth, iHeight ); + oCtx.drawImage( oCanvasImg, 0, 0, iWidth, iHeight ); + const oImgData = oCtx.getImageData( 0, 0, iWidth, iHeight ).data; + + // Coloring loop starts now + let strChars = ''; + + // console.time('rendering'); + + for ( let y = 0; y < iHeight; y += 2 ) { + + for ( let x = 0; x < iWidth; x ++ ) { + + const iOffset = ( y * iWidth + x ) * 4; + + const iRed = oImgData[ iOffset ]; + const iGreen = oImgData[ iOffset + 1 ]; + const iBlue = oImgData[ iOffset + 2 ]; + const iAlpha = oImgData[ iOffset + 3 ]; + let iCharIdx; + + let fBrightness; + + fBrightness = ( 0.3 * iRed + 0.59 * iGreen + 0.11 * iBlue ) / 255; + // fBrightness = (0.3*iRed + 0.5*iGreen + 0.3*iBlue) / 255; + + if ( iAlpha == 0 ) { + + // should calculate alpha instead, but quick hack :) + //fBrightness *= (iAlpha / 255); + fBrightness = 1; + + } + + iCharIdx = Math.floor( ( 1 - fBrightness ) * ( aCharList.length - 1 ) ); + + if ( bInvert ) { + + iCharIdx = aCharList.length - iCharIdx - 1; + + } + + // good for debugging + //fBrightness = Math.floor(fBrightness * 10); + //strThisChar = fBrightness; + + let strThisChar = aCharList[ iCharIdx ]; + + if ( strThisChar === undefined || strThisChar == ' ' ) + strThisChar = ' '; + + if ( bColor ) { + + strChars += '' + strThisChar + ''; + + } else { + + strChars += strThisChar; + + } + + } + + strChars += '
'; + + } + + oAscii.innerHTML = `${strChars}`; + + // console.timeEnd('rendering'); + + // return oAscii; + + } + + } + +} + +export { AsciiEffect }; diff --git a/renderer/jsm/effects/OutlineEffect.js b/renderer/jsm/effects/OutlineEffect.js new file mode 100644 index 0000000..90edbd4 --- /dev/null +++ b/renderer/jsm/effects/OutlineEffect.js @@ -0,0 +1,553 @@ +import { + BackSide, + Color, + ShaderMaterial, + UniformsLib, + UniformsUtils +} from 'three'; + +/** + * Reference: https://en.wikipedia.org/wiki/Cel_shading + * + * API + * + * 1. Traditional + * + * const effect = new OutlineEffect( renderer ); + * + * function render() { + * + * effect.render( scene, camera ); + * + * } + * + * 2. VR compatible + * + * const effect = new OutlineEffect( renderer ); + * let renderingOutline = false; + * + * scene.onAfterRender = function () { + * + * if ( renderingOutline ) return; + * + * renderingOutline = true; + * + * effect.renderOutline( scene, camera ); + * + * renderingOutline = false; + * + * }; + * + * function render() { + * + * renderer.render( scene, camera ); + * + * } + * + * // How to set default outline parameters + * new OutlineEffect( renderer, { + * defaultThickness: 0.01, + * defaultColor: [ 0, 0, 0 ], + * defaultAlpha: 0.8, + * defaultKeepAlive: true // keeps outline material in cache even if material is removed from scene + * } ); + * + * // How to set outline parameters for each material + * material.userData.outlineParameters = { + * thickness: 0.01, + * color: [ 0, 0, 0 ], + * alpha: 0.8, + * visible: true, + * keepAlive: true + * }; + */ + +class OutlineEffect { + + constructor( renderer, parameters = {} ) { + + this.enabled = true; + + const defaultThickness = parameters.defaultThickness !== undefined ? parameters.defaultThickness : 0.003; + const defaultColor = new Color().fromArray( parameters.defaultColor !== undefined ? parameters.defaultColor : [ 0, 0, 0 ] ); + const defaultAlpha = parameters.defaultAlpha !== undefined ? parameters.defaultAlpha : 1.0; + const defaultKeepAlive = parameters.defaultKeepAlive !== undefined ? parameters.defaultKeepAlive : false; + + // object.material.uuid -> outlineMaterial or + // object.material[ n ].uuid -> outlineMaterial + // save at the outline material creation and release + // if it's unused removeThresholdCount frames + // unless keepAlive is true. + const cache = {}; + + const removeThresholdCount = 60; + + // outlineMaterial.uuid -> object.material or + // outlineMaterial.uuid -> object.material[ n ] + // save before render and release after render. + const originalMaterials = {}; + + // object.uuid -> originalOnBeforeRender + // save before render and release after render. + const originalOnBeforeRenders = {}; + + //this.cache = cache; // for debug + + const uniformsOutline = { + outlineThickness: { value: defaultThickness }, + outlineColor: { value: defaultColor }, + outlineAlpha: { value: defaultAlpha } + }; + + const vertexShader = [ + '#include ', + '#include ', + '#include ', + '#include ', + '#include ', + '#include ', + '#include ', + '#include ', + + 'uniform float outlineThickness;', + + 'vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {', + ' float thickness = outlineThickness;', + ' const float ratio = 1.0;', // TODO: support outline thickness ratio for each vertex + ' vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );', + // NOTE: subtract pos2 from pos because BackSide objectNormal is negative + ' vec4 norm = normalize( pos - pos2 );', + ' return pos + norm * thickness * pos.w * ratio;', + '}', + + 'void main() {', + + ' #include ', + + ' #include ', + ' #include ', + ' #include ', + ' #include ', + + ' #include ', + ' #include ', + ' #include ', + ' #include ', + ' #include ', + + ' vec3 outlineNormal = - objectNormal;', // the outline material is always rendered with BackSide + + ' gl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );', + + ' #include ', + ' #include ', + ' #include ', + + '}', + + ].join( '\n' ); + + const fragmentShader = [ + + '#include ', + '#include ', + '#include ', + '#include ', + + 'uniform vec3 outlineColor;', + 'uniform float outlineAlpha;', + + 'void main() {', + + ' #include ', + ' #include ', + + ' gl_FragColor = vec4( outlineColor, outlineAlpha );', + + ' #include ', + ' #include ', + ' #include ', + ' #include ', + + '}' + + ].join( '\n' ); + + function createMaterial() { + + return new ShaderMaterial( { + type: 'OutlineEffect', + uniforms: UniformsUtils.merge( [ + UniformsLib[ 'fog' ], + UniformsLib[ 'displacementmap' ], + uniformsOutline + ] ), + vertexShader: vertexShader, + fragmentShader: fragmentShader, + side: BackSide + } ); + + } + + function getOutlineMaterialFromCache( originalMaterial ) { + + let data = cache[ originalMaterial.uuid ]; + + if ( data === undefined ) { + + data = { + material: createMaterial(), + used: true, + keepAlive: defaultKeepAlive, + count: 0 + }; + + cache[ originalMaterial.uuid ] = data; + + } + + data.used = true; + + return data.material; + + } + + function getOutlineMaterial( originalMaterial ) { + + const outlineMaterial = getOutlineMaterialFromCache( originalMaterial ); + + originalMaterials[ outlineMaterial.uuid ] = originalMaterial; + + updateOutlineMaterial( outlineMaterial, originalMaterial ); + + return outlineMaterial; + + } + + function isCompatible( object ) { + + const geometry = object.geometry; + let hasNormals = false; + + if ( object.geometry !== undefined ) { + + if ( geometry.isBufferGeometry ) { + + hasNormals = geometry.attributes.normal !== undefined; + + } else { + + hasNormals = true; // the renderer always produces a normal attribute for Geometry + + } + + } + + return ( object.isMesh === true && object.material !== undefined && hasNormals === true ); + + } + + function setOutlineMaterial( object ) { + + if ( isCompatible( object ) === false ) return; + + if ( Array.isArray( object.material ) ) { + + for ( let i = 0, il = object.material.length; i < il; i ++ ) { + + object.material[ i ] = getOutlineMaterial( object.material[ i ] ); + + } + + } else { + + object.material = getOutlineMaterial( object.material ); + + } + + originalOnBeforeRenders[ object.uuid ] = object.onBeforeRender; + object.onBeforeRender = onBeforeRender; + + } + + function restoreOriginalMaterial( object ) { + + if ( isCompatible( object ) === false ) return; + + if ( Array.isArray( object.material ) ) { + + for ( let i = 0, il = object.material.length; i < il; i ++ ) { + + object.material[ i ] = originalMaterials[ object.material[ i ].uuid ]; + + } + + } else { + + object.material = originalMaterials[ object.material.uuid ]; + + } + + object.onBeforeRender = originalOnBeforeRenders[ object.uuid ]; + + } + + function onBeforeRender( renderer, scene, camera, geometry, material ) { + + const originalMaterial = originalMaterials[ material.uuid ]; + + // just in case + if ( originalMaterial === undefined ) return; + + updateUniforms( material, originalMaterial ); + + } + + function updateUniforms( material, originalMaterial ) { + + const outlineParameters = originalMaterial.userData.outlineParameters; + + material.uniforms.outlineAlpha.value = originalMaterial.opacity; + + if ( outlineParameters !== undefined ) { + + if ( outlineParameters.thickness !== undefined ) material.uniforms.outlineThickness.value = outlineParameters.thickness; + if ( outlineParameters.color !== undefined ) material.uniforms.outlineColor.value.fromArray( outlineParameters.color ); + if ( outlineParameters.alpha !== undefined ) material.uniforms.outlineAlpha.value = outlineParameters.alpha; + + } + + if ( originalMaterial.displacementMap ) { + + material.uniforms.displacementMap.value = originalMaterial.displacementMap; + material.uniforms.displacementScale.value = originalMaterial.displacementScale; + material.uniforms.displacementBias.value = originalMaterial.displacementBias; + + } + + } + + function updateOutlineMaterial( material, originalMaterial ) { + + if ( material.name === 'invisible' ) return; + + const outlineParameters = originalMaterial.userData.outlineParameters; + + material.fog = originalMaterial.fog; + material.toneMapped = originalMaterial.toneMapped; + material.premultipliedAlpha = originalMaterial.premultipliedAlpha; + material.displacementMap = originalMaterial.displacementMap; + + if ( outlineParameters !== undefined ) { + + if ( originalMaterial.visible === false ) { + + material.visible = false; + + } else { + + material.visible = ( outlineParameters.visible !== undefined ) ? outlineParameters.visible : true; + + } + + material.transparent = ( outlineParameters.alpha !== undefined && outlineParameters.alpha < 1.0 ) ? true : originalMaterial.transparent; + + if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive; + + } else { + + material.transparent = originalMaterial.transparent; + material.visible = originalMaterial.visible; + + } + + if ( originalMaterial.wireframe === true || originalMaterial.depthTest === false ) material.visible = false; + + if ( originalMaterial.clippingPlanes ) { + + material.clipping = true; + + material.clippingPlanes = originalMaterial.clippingPlanes; + material.clipIntersection = originalMaterial.clipIntersection; + material.clipShadows = originalMaterial.clipShadows; + + } + + material.version = originalMaterial.version; // update outline material if necessary + + } + + function cleanupCache() { + + let keys; + + // clear originialMaterials + keys = Object.keys( originalMaterials ); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + originalMaterials[ keys[ i ] ] = undefined; + + } + + // clear originalOnBeforeRenders + keys = Object.keys( originalOnBeforeRenders ); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + originalOnBeforeRenders[ keys[ i ] ] = undefined; + + } + + // remove unused outlineMaterial from cache + keys = Object.keys( cache ); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + const key = keys[ i ]; + + if ( cache[ key ].used === false ) { + + cache[ key ].count ++; + + if ( cache[ key ].keepAlive === false && cache[ key ].count > removeThresholdCount ) { + + delete cache[ key ]; + + } + + } else { + + cache[ key ].used = false; + cache[ key ].count = 0; + + } + + } + + } + + this.render = function ( scene, camera ) { + + if ( this.enabled === false ) { + + renderer.render( scene, camera ); + return; + + } + + const currentAutoClear = renderer.autoClear; + renderer.autoClear = this.autoClear; + + renderer.render( scene, camera ); + + renderer.autoClear = currentAutoClear; + + this.renderOutline( scene, camera ); + + }; + + this.renderOutline = function ( scene, camera ) { + + const currentAutoClear = renderer.autoClear; + const currentSceneAutoUpdate = scene.matrixWorldAutoUpdate; + const currentSceneBackground = scene.background; + const currentShadowMapEnabled = renderer.shadowMap.enabled; + + scene.matrixWorldAutoUpdate = false; + scene.background = null; + renderer.autoClear = false; + renderer.shadowMap.enabled = false; + + scene.traverse( setOutlineMaterial ); + + renderer.render( scene, camera ); + + scene.traverse( restoreOriginalMaterial ); + + cleanupCache(); + + scene.matrixWorldAutoUpdate = currentSceneAutoUpdate; + scene.background = currentSceneBackground; + renderer.autoClear = currentAutoClear; + renderer.shadowMap.enabled = currentShadowMapEnabled; + + }; + + /* + * See #9918 + * + * The following property copies and wrapper methods enable + * OutlineEffect to be called from other *Effect, like + * + * effect = new StereoEffect( new OutlineEffect( renderer ) ); + * + * function render () { + * + * effect.render( scene, camera ); + * + * } + */ + this.autoClear = renderer.autoClear; + this.domElement = renderer.domElement; + this.shadowMap = renderer.shadowMap; + + this.clear = function ( color, depth, stencil ) { + + renderer.clear( color, depth, stencil ); + + }; + + this.getPixelRatio = function () { + + return renderer.getPixelRatio(); + + }; + + this.setPixelRatio = function ( value ) { + + renderer.setPixelRatio( value ); + + }; + + this.getSize = function ( target ) { + + return renderer.getSize( target ); + + }; + + this.setSize = function ( width, height, updateStyle ) { + + renderer.setSize( width, height, updateStyle ); + + }; + + this.setViewport = function ( x, y, width, height ) { + + renderer.setViewport( x, y, width, height ); + + }; + + this.setScissor = function ( x, y, width, height ) { + + renderer.setScissor( x, y, width, height ); + + }; + + this.setScissorTest = function ( boolean ) { + + renderer.setScissorTest( boolean ); + + }; + + this.setRenderTarget = function ( renderTarget ) { + + renderer.setRenderTarget( renderTarget ); + + }; + + } + +} + +export { OutlineEffect }; diff --git a/renderer/jsm/effects/ParallaxBarrierEffect.js b/renderer/jsm/effects/ParallaxBarrierEffect.js new file mode 100644 index 0000000..3ad41f7 --- /dev/null +++ b/renderer/jsm/effects/ParallaxBarrierEffect.js @@ -0,0 +1,116 @@ +import { + LinearFilter, + Mesh, + NearestFilter, + OrthographicCamera, + PlaneGeometry, + RGBAFormat, + Scene, + ShaderMaterial, + StereoCamera, + WebGLRenderTarget +} from 'three'; + +class ParallaxBarrierEffect { + + constructor( renderer ) { + + const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + + const _scene = new Scene(); + + const _stereo = new StereoCamera(); + + const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }; + + const _renderTargetL = new WebGLRenderTarget( 512, 512, _params ); + const _renderTargetR = new WebGLRenderTarget( 512, 512, _params ); + + const _material = new ShaderMaterial( { + + uniforms: { + + 'mapLeft': { value: _renderTargetL.texture }, + 'mapRight': { value: _renderTargetR.texture } + + }, + + vertexShader: [ + + 'varying vec2 vUv;', + + 'void main() {', + + ' vUv = vec2( uv.x, uv.y );', + ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', + + '}' + + ].join( '\n' ), + + fragmentShader: [ + + 'uniform sampler2D mapLeft;', + 'uniform sampler2D mapRight;', + 'varying vec2 vUv;', + + 'void main() {', + + ' vec2 uv = vUv;', + + ' if ( ( mod( gl_FragCoord.y, 2.0 ) ) > 1.00 ) {', + + ' gl_FragColor = texture2D( mapLeft, uv );', + + ' } else {', + + ' gl_FragColor = texture2D( mapRight, uv );', + + ' }', + + '}' + + ].join( '\n' ) + + } ); + + const mesh = new Mesh( new PlaneGeometry( 2, 2 ), _material ); + _scene.add( mesh ); + + this.setSize = function ( width, height ) { + + renderer.setSize( width, height ); + + const pixelRatio = renderer.getPixelRatio(); + + _renderTargetL.setSize( width * pixelRatio, height * pixelRatio ); + _renderTargetR.setSize( width * pixelRatio, height * pixelRatio ); + + }; + + this.render = function ( scene, camera ) { + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + _stereo.update( camera ); + + renderer.setRenderTarget( _renderTargetL ); + renderer.clear(); + renderer.render( scene, _stereo.cameraL ); + + renderer.setRenderTarget( _renderTargetR ); + renderer.clear(); + renderer.render( scene, _stereo.cameraR ); + + renderer.setRenderTarget( null ); + renderer.render( _scene, _camera ); + + }; + + } + +} + +export { ParallaxBarrierEffect }; diff --git a/renderer/jsm/effects/PeppersGhostEffect.js b/renderer/jsm/effects/PeppersGhostEffect.js new file mode 100644 index 0000000..1572096 --- /dev/null +++ b/renderer/jsm/effects/PeppersGhostEffect.js @@ -0,0 +1,153 @@ +import { + PerspectiveCamera, + Quaternion, + Vector3 +} from 'three'; + +/** + * peppers ghost effect based on http://www.instructables.com/id/Reflective-Prism/?ALLSTEPS + */ + +class PeppersGhostEffect { + + constructor( renderer ) { + + const scope = this; + + scope.cameraDistance = 15; + scope.reflectFromAbove = false; + + // Internals + let _halfWidth, _width, _height; + + const _cameraF = new PerspectiveCamera(); //front + const _cameraB = new PerspectiveCamera(); //back + const _cameraL = new PerspectiveCamera(); //left + const _cameraR = new PerspectiveCamera(); //right + + const _position = new Vector3(); + const _quaternion = new Quaternion(); + const _scale = new Vector3(); + + // Initialization + renderer.autoClear = false; + + this.setSize = function ( width, height ) { + + _halfWidth = width / 2; + if ( width < height ) { + + _width = width / 3; + _height = width / 3; + + } else { + + _width = height / 3; + _height = height / 3; + + } + + renderer.setSize( width, height ); + + }; + + this.render = function ( scene, camera ) { + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + camera.matrixWorld.decompose( _position, _quaternion, _scale ); + + // front + _cameraF.position.copy( _position ); + _cameraF.quaternion.copy( _quaternion ); + _cameraF.translateZ( scope.cameraDistance ); + _cameraF.lookAt( scene.position ); + + // back + _cameraB.position.copy( _position ); + _cameraB.quaternion.copy( _quaternion ); + _cameraB.translateZ( - ( scope.cameraDistance ) ); + _cameraB.lookAt( scene.position ); + _cameraB.rotation.z += 180 * ( Math.PI / 180 ); + + // left + _cameraL.position.copy( _position ); + _cameraL.quaternion.copy( _quaternion ); + _cameraL.translateX( - ( scope.cameraDistance ) ); + _cameraL.lookAt( scene.position ); + _cameraL.rotation.x += 90 * ( Math.PI / 180 ); + + // right + _cameraR.position.copy( _position ); + _cameraR.quaternion.copy( _quaternion ); + _cameraR.translateX( scope.cameraDistance ); + _cameraR.lookAt( scene.position ); + _cameraR.rotation.x += 90 * ( Math.PI / 180 ); + + + renderer.clear(); + renderer.setScissorTest( true ); + + renderer.setScissor( _halfWidth - ( _width / 2 ), ( _height * 2 ), _width, _height ); + renderer.setViewport( _halfWidth - ( _width / 2 ), ( _height * 2 ), _width, _height ); + + if ( scope.reflectFromAbove ) { + + renderer.render( scene, _cameraB ); + + } else { + + renderer.render( scene, _cameraF ); + + } + + renderer.setScissor( _halfWidth - ( _width / 2 ), 0, _width, _height ); + renderer.setViewport( _halfWidth - ( _width / 2 ), 0, _width, _height ); + + if ( scope.reflectFromAbove ) { + + renderer.render( scene, _cameraF ); + + } else { + + renderer.render( scene, _cameraB ); + + } + + renderer.setScissor( _halfWidth - ( _width / 2 ) - _width, _height, _width, _height ); + renderer.setViewport( _halfWidth - ( _width / 2 ) - _width, _height, _width, _height ); + + if ( scope.reflectFromAbove ) { + + renderer.render( scene, _cameraR ); + + } else { + + renderer.render( scene, _cameraL ); + + } + + renderer.setScissor( _halfWidth + ( _width / 2 ), _height, _width, _height ); + renderer.setViewport( _halfWidth + ( _width / 2 ), _height, _width, _height ); + + if ( scope.reflectFromAbove ) { + + renderer.render( scene, _cameraL ); + + } else { + + renderer.render( scene, _cameraR ); + + } + + renderer.setScissorTest( false ); + + }; + + } + +} + +export { PeppersGhostEffect }; diff --git a/renderer/jsm/effects/StereoEffect.js b/renderer/jsm/effects/StereoEffect.js new file mode 100644 index 0000000..e6e1b44 --- /dev/null +++ b/renderer/jsm/effects/StereoEffect.js @@ -0,0 +1,55 @@ +import { + StereoCamera, + Vector2 +} from 'three'; + +class StereoEffect { + + constructor( renderer ) { + + const _stereo = new StereoCamera(); + _stereo.aspect = 0.5; + const size = new Vector2(); + + this.setEyeSeparation = function ( eyeSep ) { + + _stereo.eyeSep = eyeSep; + + }; + + this.setSize = function ( width, height ) { + + renderer.setSize( width, height ); + + }; + + this.render = function ( scene, camera ) { + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + _stereo.update( camera ); + + renderer.getSize( size ); + + if ( renderer.autoClear ) renderer.clear(); + renderer.setScissorTest( true ); + + renderer.setScissor( 0, 0, size.width / 2, size.height ); + renderer.setViewport( 0, 0, size.width / 2, size.height ); + renderer.render( scene, _stereo.cameraL ); + + renderer.setScissor( size.width / 2, 0, size.width / 2, size.height ); + renderer.setViewport( size.width / 2, 0, size.width / 2, size.height ); + renderer.render( scene, _stereo.cameraR ); + + renderer.setScissorTest( false ); + + }; + + } + +} + +export { StereoEffect }; diff --git a/renderer/jsm/environments/DebugEnvironment.js b/renderer/jsm/environments/DebugEnvironment.js new file mode 100644 index 0000000..ce3db06 --- /dev/null +++ b/renderer/jsm/environments/DebugEnvironment.js @@ -0,0 +1,52 @@ +import { + BackSide, + BoxGeometry, + Mesh, + MeshLambertMaterial, + MeshStandardMaterial, + PointLight, + Scene, +} from 'three'; + +class DebugEnvironment extends Scene { + + constructor() { + + super(); + + const geometry = new BoxGeometry(); + geometry.deleteAttribute( 'uv' ); + const roomMaterial = new MeshStandardMaterial( { metalness: 0, side: BackSide } ); + const room = new Mesh( geometry, roomMaterial ); + room.scale.setScalar( 10 ); + this.add( room ); + + const mainLight = new PointLight( 0xffffff, 50, 0, 2 ); + this.add( mainLight ); + + const material1 = new MeshLambertMaterial( { color: 0xff0000, emissive: 0xffffff, emissiveIntensity: 10 } ); + + const light1 = new Mesh( geometry, material1 ); + light1.position.set( - 5, 2, 0 ); + light1.scale.set( 0.1, 1, 1 ); + this.add( light1 ); + + const material2 = new MeshLambertMaterial( { color: 0x00ff00, emissive: 0xffffff, emissiveIntensity: 10 } ); + + const light2 = new Mesh( geometry, material2 ); + light2.position.set( 0, 5, 0 ); + light2.scale.set( 1, 0.1, 1 ); + this.add( light2 ); + + const material3 = new MeshLambertMaterial( { color: 0x0000ff, emissive: 0xffffff, emissiveIntensity: 10 } ); + + const light3 = new Mesh( geometry, material3 ); + light3.position.set( 2, 1, 5 ); + light3.scale.set( 1.5, 2, 0.1 ); + this.add( light3 ); + + } + +} + +export { DebugEnvironment }; diff --git a/renderer/jsm/environments/RoomEnvironment.js b/renderer/jsm/environments/RoomEnvironment.js new file mode 100644 index 0000000..1846dfa --- /dev/null +++ b/renderer/jsm/environments/RoomEnvironment.js @@ -0,0 +1,144 @@ +/** + * https://github.com/google/model-viewer/blob/master/packages/model-viewer/src/three-components/EnvironmentScene.ts + */ + +import { + BackSide, + BoxGeometry, + Mesh, + MeshBasicMaterial, + MeshStandardMaterial, + PointLight, + Scene, +} from 'three'; + +class RoomEnvironment extends Scene { + + constructor() { + + super(); + + const geometry = new BoxGeometry(); + geometry.deleteAttribute( 'uv' ); + + const roomMaterial = new MeshStandardMaterial( { side: BackSide } ); + const boxMaterial = new MeshStandardMaterial(); + + const mainLight = new PointLight( 0xffffff, 5.0, 28, 2 ); + mainLight.position.set( 0.418, 16.199, 0.300 ); + this.add( mainLight ); + + const room = new Mesh( geometry, roomMaterial ); + room.position.set( - 0.757, 13.219, 0.717 ); + room.scale.set( 31.713, 28.305, 28.591 ); + this.add( room ); + + const box1 = new Mesh( geometry, boxMaterial ); + box1.position.set( - 10.906, 2.009, 1.846 ); + box1.rotation.set( 0, - 0.195, 0 ); + box1.scale.set( 2.328, 7.905, 4.651 ); + this.add( box1 ); + + const box2 = new Mesh( geometry, boxMaterial ); + box2.position.set( - 5.607, - 0.754, - 0.758 ); + box2.rotation.set( 0, 0.994, 0 ); + box2.scale.set( 1.970, 1.534, 3.955 ); + this.add( box2 ); + + const box3 = new Mesh( geometry, boxMaterial ); + box3.position.set( 6.167, 0.857, 7.803 ); + box3.rotation.set( 0, 0.561, 0 ); + box3.scale.set( 3.927, 6.285, 3.687 ); + this.add( box3 ); + + const box4 = new Mesh( geometry, boxMaterial ); + box4.position.set( - 2.017, 0.018, 6.124 ); + box4.rotation.set( 0, 0.333, 0 ); + box4.scale.set( 2.002, 4.566, 2.064 ); + this.add( box4 ); + + const box5 = new Mesh( geometry, boxMaterial ); + box5.position.set( 2.291, - 0.756, - 2.621 ); + box5.rotation.set( 0, - 0.286, 0 ); + box5.scale.set( 1.546, 1.552, 1.496 ); + this.add( box5 ); + + const box6 = new Mesh( geometry, boxMaterial ); + box6.position.set( - 2.193, - 0.369, - 5.547 ); + box6.rotation.set( 0, 0.516, 0 ); + box6.scale.set( 3.875, 3.487, 2.986 ); + this.add( box6 ); + + + // -x right + const light1 = new Mesh( geometry, createAreaLightMaterial( 50 ) ); + light1.position.set( - 16.116, 14.37, 8.208 ); + light1.scale.set( 0.1, 2.428, 2.739 ); + this.add( light1 ); + + // -x left + const light2 = new Mesh( geometry, createAreaLightMaterial( 50 ) ); + light2.position.set( - 16.109, 18.021, - 8.207 ); + light2.scale.set( 0.1, 2.425, 2.751 ); + this.add( light2 ); + + // +x + const light3 = new Mesh( geometry, createAreaLightMaterial( 17 ) ); + light3.position.set( 14.904, 12.198, - 1.832 ); + light3.scale.set( 0.15, 4.265, 6.331 ); + this.add( light3 ); + + // +z + const light4 = new Mesh( geometry, createAreaLightMaterial( 43 ) ); + light4.position.set( - 0.462, 8.89, 14.520 ); + light4.scale.set( 4.38, 5.441, 0.088 ); + this.add( light4 ); + + // -z + const light5 = new Mesh( geometry, createAreaLightMaterial( 20 ) ); + light5.position.set( 3.235, 11.486, - 12.541 ); + light5.scale.set( 2.5, 2.0, 0.1 ); + this.add( light5 ); + + // +y + const light6 = new Mesh( geometry, createAreaLightMaterial( 100 ) ); + light6.position.set( 0.0, 20.0, 0.0 ); + light6.scale.set( 1.0, 0.1, 1.0 ); + this.add( light6 ); + + } + + dispose() { + + const resources = new Set(); + + this.traverse( ( object ) => { + + if ( object.isMesh ) { + + resources.add( object.geometry ); + resources.add( object.material ); + + } + + } ); + + for ( const resource of resources ) { + + resource.dispose(); + + } + + } + +} + +function createAreaLightMaterial( intensity ) { + + const material = new MeshBasicMaterial(); + material.color.setScalar( intensity ); + return material; + +} + +export { RoomEnvironment }; diff --git a/renderer/jsm/exporters/ColladaExporter.js b/renderer/jsm/exporters/ColladaExporter.js new file mode 100644 index 0000000..5296638 --- /dev/null +++ b/renderer/jsm/exporters/ColladaExporter.js @@ -0,0 +1,725 @@ +import { + Color, + DoubleSide, + Matrix4, + MeshBasicMaterial +} from 'three'; + +/** + * https://github.com/gkjohnson/collada-exporter-js + * + * Usage: + * const exporter = new ColladaExporter(); + * + * const data = exporter.parse(mesh); + * + * Format Definition: + * https://www.khronos.org/collada/ + */ + +class ColladaExporter { + + parse( object, onDone, options = {} ) { + + options = Object.assign( { + version: '1.4.1', + author: null, + textureDirectory: '', + upAxis: 'Y_UP', + unitName: null, + unitMeter: null, + }, options ); + + if ( options.upAxis.match( /^[XYZ]_UP$/ ) === null ) { + + console.error( 'ColladaExporter: Invalid upAxis: valid values are X_UP, Y_UP or Z_UP.' ); + return null; + + } + + if ( options.unitName !== null && options.unitMeter === null ) { + + console.error( 'ColladaExporter: unitMeter needs to be specified if unitName is specified.' ); + return null; + + } + + if ( options.unitMeter !== null && options.unitName === null ) { + + console.error( 'ColladaExporter: unitName needs to be specified if unitMeter is specified.' ); + return null; + + } + + if ( options.textureDirectory !== '' ) { + + options.textureDirectory = `${ options.textureDirectory }/` + .replace( /\\/g, '/' ) + .replace( /\/+/g, '/' ); + + } + + const version = options.version; + + if ( version !== '1.4.1' && version !== '1.5.0' ) { + + console.warn( `ColladaExporter : Version ${ version } not supported for export. Only 1.4.1 and 1.5.0.` ); + return null; + + } + + // Convert the urdf xml into a well-formatted, indented format + function format( urdf ) { + + const IS_END_TAG = /^<\//; + const IS_SELF_CLOSING = /(\?>$)|(\/>$)/; + const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/; + + const pad = ( ch, num ) => ( num > 0 ? ch + pad( ch, num - 1 ) : '' ); + + let tagnum = 0; + + return urdf + .match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g ) + .map( tag => { + + if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) { + + tagnum --; + + } + + const res = `${ pad( ' ', tagnum ) }${ tag }`; + + if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) { + + tagnum ++; + + } + + return res; + + } ) + .join( '\n' ); + + } + + // Convert an image into a png format for saving + function base64ToBuffer( str ) { + + const b = atob( str ); + const buf = new Uint8Array( b.length ); + + for ( let i = 0, l = buf.length; i < l; i ++ ) { + + buf[ i ] = b.charCodeAt( i ); + + } + + return buf; + + } + + let canvas, ctx; + + function imageToData( image, ext ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + canvas = canvas || document.createElement( 'canvas' ); + ctx = ctx || canvas.getContext( '2d' ); + + canvas.width = image.width; + canvas.height = image.height; + + ctx.drawImage( image, 0, 0 ); + + // Get the base64 encoded data + const base64data = canvas + .toDataURL( `image/${ ext }`, 1 ) + .replace( /^data:image\/(png|jpg);base64,/, '' ); + + // Convert to a uint8 array + return base64ToBuffer( base64data ); + + } else { + + throw new Error( 'THREE.ColladaExporter: No valid image data found. Unable to process texture.' ); + + } + + } + + // gets the attribute array. Generate a new array if the attribute is interleaved + const getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ]; + const tempColor = new Color(); + + function attrBufferToArray( attr, isColor = false ) { + + if ( isColor ) { + + // convert the colors to srgb before export + // colors are always written as floats + const arr = new Float32Array( attr.count * 3 ); + for ( let i = 0, l = attr.count; i < l; i ++ ) { + + tempColor + .fromBufferAttribute( attr, i ) + .convertLinearToSRGB(); + + arr[ 3 * i + 0 ] = tempColor.r; + arr[ 3 * i + 1 ] = tempColor.g; + arr[ 3 * i + 2 ] = tempColor.b; + + } + + return arr; + + } else if ( attr.isInterleavedBufferAttribute ) { + + // use the typed array constructor to save on memory + const arr = new attr.array.constructor( attr.count * attr.itemSize ); + const size = attr.itemSize; + + for ( let i = 0, l = attr.count; i < l; i ++ ) { + + for ( let j = 0; j < size; j ++ ) { + + arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i ); + + } + + } + + return arr; + + } else { + + return attr.array; + + } + + } + + // Returns an array of the same type starting at the `st` index, + // and `ct` length + function subArray( arr, st, ct ) { + + if ( Array.isArray( arr ) ) return arr.slice( st, st + ct ); + else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct ); + + } + + // Returns the string for a geometry's attribute + function getAttribute( attr, name, params, type, isColor = false ) { + + const array = attrBufferToArray( attr, isColor ); + const res = + `` + + + `` + + array.join( ' ' ) + + '' + + + '' + + `` + + + params.map( n => `` ).join( '' ) + + + '' + + '' + + ''; + + return res; + + } + + // Returns the string for a node's transform information + let transMat; + function getTransform( o ) { + + // ensure the object's matrix is up to date + // before saving the transform + o.updateMatrix(); + + transMat = transMat || new Matrix4(); + transMat.copy( o.matrix ); + transMat.transpose(); + return `${ transMat.toArray().join( ' ' ) }`; + + } + + // Process the given piece of geometry into the geometry library + // Returns the mesh id + function processGeometry( bufferGeometry ) { + + let info = geometryInfo.get( bufferGeometry ); + + if ( ! info ) { + + const meshid = `Mesh${ libraryGeometries.length + 1 }`; + + const indexCount = + bufferGeometry.index ? + bufferGeometry.index.count * bufferGeometry.index.itemSize : + bufferGeometry.attributes.position.count; + + const groups = + bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ? + bufferGeometry.groups : + [ { start: 0, count: indexCount, materialIndex: 0 } ]; + + + const gname = bufferGeometry.name ? ` name="${ bufferGeometry.name }"` : ''; + let gnode = ``; + + // define the geometry node and the vertices for the geometry + const posName = `${ meshid }-position`; + const vertName = `${ meshid }-vertices`; + gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' ); + gnode += ``; + + // NOTE: We're not optimizing the attribute arrays here, so they're all the same length and + // can therefore share the same triangle indices. However, MeshLab seems to have trouble opening + // models with attributes that share an offset. + // MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/ + + // serialize normals + let triangleInputs = ``; + if ( 'normal' in bufferGeometry.attributes ) { + + const normName = `${ meshid }-normal`; + gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' ); + triangleInputs += ``; + + } + + // serialize uvs + if ( 'uv' in bufferGeometry.attributes ) { + + const uvName = `${ meshid }-texcoord`; + gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' ); + triangleInputs += ``; + + } + + // serialize lightmap uvs + if ( 'uv2' in bufferGeometry.attributes ) { + + const uvName = `${ meshid }-texcoord2`; + gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' ); + triangleInputs += ``; + + } + + // serialize colors + if ( 'color' in bufferGeometry.attributes ) { + + // colors are always written as floats + const colName = `${ meshid }-color`; + gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'R', 'G', 'B' ], 'float', true ); + triangleInputs += ``; + + } + + let indexArray = null; + if ( bufferGeometry.index ) { + + indexArray = attrBufferToArray( bufferGeometry.index ); + + } else { + + indexArray = new Array( indexCount ); + for ( let i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i; + + } + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const subarr = subArray( indexArray, group.start, group.count ); + const polycount = subarr.length / 3; + gnode += ``; + gnode += triangleInputs; + + gnode += `

${ subarr.join( ' ' ) }

`; + gnode += '
'; + + } + + gnode += '
'; + + libraryGeometries.push( gnode ); + + info = { meshid: meshid, bufferGeometry: bufferGeometry }; + geometryInfo.set( bufferGeometry, info ); + + } + + return info; + + } + + // Process the given texture into the image library + // Returns the image library + function processTexture( tex ) { + + let texid = imageMap.get( tex ); + + if ( texid === undefined ) { + + texid = `image-${ libraryImages.length + 1 }`; + + const ext = 'png'; + const name = tex.name || texid; + let imageNode = ``; + + if ( version === '1.5.0' ) { + + imageNode += `${ options.textureDirectory }${ name }.${ ext }`; + + } else { + + // version image node 1.4.1 + imageNode += `${ options.textureDirectory }${ name }.${ ext }`; + + } + + imageNode += ''; + + libraryImages.push( imageNode ); + imageMap.set( tex, texid ); + textures.push( { + directory: options.textureDirectory, + name, + ext, + data: imageToData( tex.image, ext ), + original: tex + } ); + + } + + return texid; + + } + + // Process the given material into the material and effect libraries + // Returns the material id + function processMaterial( m ) { + + let matid = materialMap.get( m ); + + if ( matid == null ) { + + matid = `Mat${ libraryEffects.length + 1 }`; + + let type = 'phong'; + + if ( m.isMeshLambertMaterial === true ) { + + type = 'lambert'; + + } else if ( m.isMeshBasicMaterial === true ) { + + type = 'constant'; + + if ( m.map !== null ) { + + // The Collada spec does not support diffuse texture maps with the + // constant shader type. + // mrdoob/three.js#15469 + console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' ); + + } + + } + + const emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 ); + const diffuse = m.color ? m.color : new Color( 0, 0, 0 ); + const specular = m.specular ? m.specular : new Color( 1, 1, 1 ); + const shininess = m.shininess || 0; + const reflectivity = m.reflectivity || 0; + + emissive.convertLinearToSRGB(); + specular.convertLinearToSRGB(); + diffuse.convertLinearToSRGB(); + + // Do not export and alpha map for the reasons mentioned in issue (#13792) + // in three.js alpha maps are black and white, but collada expects the alpha + // channel to specify the transparency + let transparencyNode = ''; + if ( m.transparent === true ) { + + transparencyNode += + '' + + ( + m.map ? + '' : + '1' + ) + + ''; + + if ( m.opacity < 1 ) { + + transparencyNode += `${ m.opacity }`; + + } + + } + + const techniqueNode = `<${ type }>` + + + '' + + + ( + m.emissiveMap ? + '' : + `${ emissive.r } ${ emissive.g } ${ emissive.b } 1` + ) + + + '' + + + ( + type !== 'constant' ? + '' + + + ( + m.map ? + '' : + `${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1` + ) + + '' + : '' + ) + + + ( + type !== 'constant' ? + '' + + + ( + m.normalMap ? '' : '' + ) + + '' + : '' + ) + + + ( + type === 'phong' ? + `${ specular.r } ${ specular.g } ${ specular.b } 1` + + + '' + + + ( + m.specularMap ? + '' : + `${ shininess }` + ) + + + '' + : '' + ) + + + `${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1` + + + `${ reflectivity }` + + + transparencyNode + + + ``; + + const effectnode = + `` + + '' + + + ( + m.map ? + '' + + `${ processTexture( m.map ) }` + + '' + + 'diffuse-surface' : + '' + ) + + + ( + m.specularMap ? + '' + + `${ processTexture( m.specularMap ) }` + + '' + + 'specular-surface' : + '' + ) + + + ( + m.emissiveMap ? + '' + + `${ processTexture( m.emissiveMap ) }` + + '' + + 'emissive-surface' : + '' + ) + + + ( + m.normalMap ? + '' + + `${ processTexture( m.normalMap ) }` + + '' + + 'bump-surface' : + '' + ) + + + techniqueNode + + + ( + m.side === DoubleSide ? + '1' : + '' + ) + + + '' + + + ''; + + const materialName = m.name ? ` name="${ m.name }"` : ''; + const materialNode = ``; + + libraryMaterials.push( materialNode ); + libraryEffects.push( effectnode ); + materialMap.set( m, matid ); + + } + + return matid; + + } + + // Recursively process the object into a scene + function processObject( o ) { + + let node = ``; + + node += getTransform( o ); + + if ( o.isMesh === true && o.geometry !== null ) { + + // function returns the id associated with the mesh and a "BufferGeometry" version + // of the geometry in case it's not a geometry. + const geomInfo = processGeometry( o.geometry ); + const meshid = geomInfo.meshid; + const geometry = geomInfo.bufferGeometry; + + // ids of the materials to bind to the geometry + let matids = null; + let matidsArray; + + // get a list of materials to bind to the sub groups of the geometry. + // If the amount of subgroups is greater than the materials, than reuse + // the materials. + const mat = o.material || new MeshBasicMaterial(); + const materials = Array.isArray( mat ) ? mat : [ mat ]; + + if ( geometry.groups.length > materials.length ) { + + matidsArray = new Array( geometry.groups.length ); + + } else { + + matidsArray = new Array( materials.length ); + + } + + matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) ); + + node += + `` + + + ( + matids.length > 0 ? + '' + + matids.map( ( id, i ) => + + `` + + + '' + + + '' + ).join( '' ) + + '' : + '' + ) + + + ''; + + } + + o.children.forEach( c => node += processObject( c ) ); + + node += ''; + + return node; + + } + + const geometryInfo = new WeakMap(); + const materialMap = new WeakMap(); + const imageMap = new WeakMap(); + const textures = []; + + const libraryImages = []; + const libraryGeometries = []; + const libraryEffects = []; + const libraryMaterials = []; + const libraryVisualScenes = processObject( object ); + + const specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/'; + let dae = + '' + + `` + + '' + + ( + '' + + 'three.js Collada Exporter' + + ( options.author !== null ? `${ options.author }` : '' ) + + '' + + `${ ( new Date() ).toISOString() }` + + `${ ( new Date() ).toISOString() }` + + ( options.unitName !== null ? `` : '' ) + + `${ options.upAxis }` + ) + + ''; + + dae += `${ libraryImages.join( '' ) }`; + + dae += `${ libraryEffects.join( '' ) }`; + + dae += `${ libraryMaterials.join( '' ) }`; + + dae += `${ libraryGeometries.join( '' ) }`; + + dae += `${ libraryVisualScenes }`; + + dae += ''; + + dae += ''; + + const res = { + data: format( dae ), + textures + }; + + if ( typeof onDone === 'function' ) { + + requestAnimationFrame( () => onDone( res ) ); + + } + + return res; + + } + +} + + +export { ColladaExporter }; diff --git a/renderer/jsm/exporters/DRACOExporter.js b/renderer/jsm/exporters/DRACOExporter.js new file mode 100644 index 0000000..669aa8f --- /dev/null +++ b/renderer/jsm/exporters/DRACOExporter.js @@ -0,0 +1,227 @@ +/** + * Export draco compressed files from threejs geometry objects. + * + * Draco files are compressed and usually are smaller than conventional 3D file formats. + * + * The exporter receives a options object containing + * - decodeSpeed, indicates how to tune the encoder regarding decode speed (0 gives better speed but worst quality) + * - encodeSpeed, indicates how to tune the encoder parameters (0 gives better speed but worst quality) + * - encoderMethod + * - quantization, indicates the presision of each type of data stored in the draco file in the order (POSITION, NORMAL, COLOR, TEX_COORD, GENERIC) + * - exportUvs + * - exportNormals + */ + +/* global DracoEncoderModule */ + +class DRACOExporter { + + parse( object, options = {} ) { + + options = Object.assign( { + decodeSpeed: 5, + encodeSpeed: 5, + encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, + quantization: [ 16, 8, 8, 8, 8 ], + exportUvs: true, + exportNormals: true, + exportColor: false, + }, options ); + + if ( DracoEncoderModule === undefined ) { + + throw new Error( 'THREE.DRACOExporter: required the draco_encoder to work.' ); + + } + + const geometry = object.geometry; + + const dracoEncoder = DracoEncoderModule(); + const encoder = new dracoEncoder.Encoder(); + let builder; + let dracoObject; + + if ( object.isMesh === true ) { + + builder = new dracoEncoder.MeshBuilder(); + dracoObject = new dracoEncoder.Mesh(); + + const vertices = geometry.getAttribute( 'position' ); + builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array ); + + const faces = geometry.getIndex(); + + if ( faces !== null ) { + + builder.AddFacesToMesh( dracoObject, faces.count / 3, faces.array ); + + } else { + + const faces = new ( vertices.count > 65535 ? Uint32Array : Uint16Array )( vertices.count ); + + for ( let i = 0; i < faces.length; i ++ ) { + + faces[ i ] = i; + + } + + builder.AddFacesToMesh( dracoObject, vertices.count, faces ); + + } + + if ( options.exportNormals === true ) { + + const normals = geometry.getAttribute( 'normal' ); + + if ( normals !== undefined ) { + + builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array ); + + } + + } + + if ( options.exportUvs === true ) { + + const uvs = geometry.getAttribute( 'uv' ); + + if ( uvs !== undefined ) { + + builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array ); + + } + + } + + if ( options.exportColor === true ) { + + const colors = geometry.getAttribute( 'color' ); + + if ( colors !== undefined ) { + + builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array ); + + } + + } + + } else if ( object.isPoints === true ) { + + builder = new dracoEncoder.PointCloudBuilder(); + dracoObject = new dracoEncoder.PointCloud(); + + const vertices = geometry.getAttribute( 'position' ); + builder.AddFloatAttribute( dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array ); + + if ( options.exportColor === true ) { + + const colors = geometry.getAttribute( 'color' ); + + if ( colors !== undefined ) { + + builder.AddFloatAttribute( dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array ); + + } + + } + + } else { + + throw new Error( 'DRACOExporter: Unsupported object type.' ); + + } + + //Compress using draco encoder + + const encodedData = new dracoEncoder.DracoInt8Array(); + + //Sets the desired encoding and decoding speed for the given options from 0 (slowest speed, but the best compression) to 10 (fastest, but the worst compression). + + const encodeSpeed = ( options.encodeSpeed !== undefined ) ? options.encodeSpeed : 5; + const decodeSpeed = ( options.decodeSpeed !== undefined ) ? options.decodeSpeed : 5; + + encoder.SetSpeedOptions( encodeSpeed, decodeSpeed ); + + // Sets the desired encoding method for a given geometry. + + if ( options.encoderMethod !== undefined ) { + + encoder.SetEncodingMethod( options.encoderMethod ); + + } + + // Sets the quantization (number of bits used to represent) compression options for a named attribute. + // The attribute values will be quantized in a box defined by the maximum extent of the attribute values. + if ( options.quantization !== undefined ) { + + for ( let i = 0; i < 5; i ++ ) { + + if ( options.quantization[ i ] !== undefined ) { + + encoder.SetAttributeQuantization( i, options.quantization[ i ] ); + + } + + } + + } + + let length; + + if ( object.isMesh === true ) { + + length = encoder.EncodeMeshToDracoBuffer( dracoObject, encodedData ); + + } else { + + length = encoder.EncodePointCloudToDracoBuffer( dracoObject, true, encodedData ); + + } + + dracoEncoder.destroy( dracoObject ); + + if ( length === 0 ) { + + throw new Error( 'THREE.DRACOExporter: Draco encoding failed.' ); + + } + + //Copy encoded data to buffer. + const outputData = new Int8Array( new ArrayBuffer( length ) ); + + for ( let i = 0; i < length; i ++ ) { + + outputData[ i ] = encodedData.GetValue( i ); + + } + + dracoEncoder.destroy( encodedData ); + dracoEncoder.destroy( encoder ); + dracoEncoder.destroy( builder ); + + return outputData; + + } + +} + +// Encoder methods + +DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1; +DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0; + +// Geometry type + +DRACOExporter.POINT_CLOUD = 0; +DRACOExporter.TRIANGULAR_MESH = 1; + +// Attribute type + +DRACOExporter.INVALID = - 1; +DRACOExporter.POSITION = 0; +DRACOExporter.NORMAL = 1; +DRACOExporter.COLOR = 2; +DRACOExporter.TEX_COORD = 3; +DRACOExporter.GENERIC = 4; + +export { DRACOExporter }; diff --git a/renderer/jsm/exporters/EXRExporter.js b/renderer/jsm/exporters/EXRExporter.js new file mode 100644 index 0000000..3039294 --- /dev/null +++ b/renderer/jsm/exporters/EXRExporter.js @@ -0,0 +1,501 @@ +/** + * @author sciecode / https://github.com/sciecode + * + * EXR format references: + * https://www.openexr.com/documentation/openexrfilelayout.pdf + */ + +import { + FloatType, + HalfFloatType, + RGBAFormat, + DataUtils, +} from 'three'; +import * as fflate from '../libs/fflate.module.js'; + +const textEncoder = new TextEncoder(); + +const NO_COMPRESSION = 0; +const ZIPS_COMPRESSION = 2; +const ZIP_COMPRESSION = 3; + +class EXRExporter { + + parse( renderer, renderTarget, options ) { + + if ( ! supported( renderer, renderTarget ) ) return undefined; + + const info = buildInfo( renderTarget, options ), + dataBuffer = getPixelData( renderer, renderTarget, info ), + rawContentBuffer = reorganizeDataBuffer( dataBuffer, info ), + chunks = compressData( rawContentBuffer, info ); + + return fillData( chunks, info ); + + } + +} + +function supported( renderer, renderTarget ) { + + if ( ! renderer || ! renderer.isWebGLRenderer ) { + + console.error( 'EXRExporter.parse: Unsupported first parameter, expected instance of WebGLRenderer.' ); + + return false; + + } + + if ( ! renderTarget || ! renderTarget.isWebGLRenderTarget ) { + + console.error( 'EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.' ); + + return false; + + } + + if ( renderTarget.texture.type !== FloatType && renderTarget.texture.type !== HalfFloatType ) { + + console.error( 'EXRExporter.parse: Unsupported WebGLRenderTarget texture type.' ); + + return false; + + } + + if ( renderTarget.texture.format !== RGBAFormat ) { + + console.error( 'EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.' ); + + return false; + + } + + + return true; + +} + +function buildInfo( renderTarget, options = {} ) { + + const compressionSizes = { + 0: 1, + 2: 1, + 3: 16 + }; + + const WIDTH = renderTarget.width, + HEIGHT = renderTarget.height, + TYPE = renderTarget.texture.type, + FORMAT = renderTarget.texture.format, + ENCODING = renderTarget.texture.encoding, + COMPRESSION = ( options.compression !== undefined ) ? options.compression : ZIP_COMPRESSION, + EXPORTER_TYPE = ( options.type !== undefined ) ? options.type : HalfFloatType, + OUT_TYPE = ( EXPORTER_TYPE === FloatType ) ? 2 : 1, + COMPRESSION_SIZE = compressionSizes[ COMPRESSION ], + NUM_CHANNELS = 4; + + return { + width: WIDTH, + height: HEIGHT, + type: TYPE, + format: FORMAT, + encoding: ENCODING, + compression: COMPRESSION, + blockLines: COMPRESSION_SIZE, + dataType: OUT_TYPE, + dataSize: 2 * OUT_TYPE, + numBlocks: Math.ceil( HEIGHT / COMPRESSION_SIZE ), + numInputChannels: 4, + numOutputChannels: NUM_CHANNELS, + }; + +} + +function getPixelData( renderer, rtt, info ) { + + let dataBuffer; + + if ( info.type === FloatType ) { + + dataBuffer = new Float32Array( info.width * info.height * info.numInputChannels ); + + } else { + + dataBuffer = new Uint16Array( info.width * info.height * info.numInputChannels ); + + } + + renderer.readRenderTargetPixels( rtt, 0, 0, info.width, info.height, dataBuffer ); + + return dataBuffer; + +} + +function reorganizeDataBuffer( inBuffer, info ) { + + const w = info.width, + h = info.height, + dec = { r: 0, g: 0, b: 0, a: 0 }, + offset = { value: 0 }, + cOffset = ( info.numOutputChannels == 4 ) ? 1 : 0, + getValue = ( info.type == FloatType ) ? getFloat32 : getFloat16, + setValue = ( info.dataType == 1 ) ? setFloat16 : setFloat32, + outBuffer = new Uint8Array( info.width * info.height * info.numOutputChannels * info.dataSize ), + dv = new DataView( outBuffer.buffer ); + + for ( let y = 0; y < h; ++ y ) { + + for ( let x = 0; x < w; ++ x ) { + + const i = y * w * 4 + x * 4; + + const r = getValue( inBuffer, i ); + const g = getValue( inBuffer, i + 1 ); + const b = getValue( inBuffer, i + 2 ); + const a = getValue( inBuffer, i + 3 ); + + const line = ( h - y - 1 ) * w * ( 3 + cOffset ) * info.dataSize; + + decodeLinear( dec, r, g, b, a ); + + offset.value = line + x * info.dataSize; + setValue( dv, dec.a, offset ); + + offset.value = line + ( cOffset ) * w * info.dataSize + x * info.dataSize; + setValue( dv, dec.b, offset ); + + offset.value = line + ( 1 + cOffset ) * w * info.dataSize + x * info.dataSize; + setValue( dv, dec.g, offset ); + + offset.value = line + ( 2 + cOffset ) * w * info.dataSize + x * info.dataSize; + setValue( dv, dec.r, offset ); + + } + + } + + return outBuffer; + +} + +function compressData( inBuffer, info ) { + + let compress, + tmpBuffer, + sum = 0; + + const chunks = { data: new Array(), totalSize: 0 }, + size = info.width * info.numOutputChannels * info.blockLines * info.dataSize; + + switch ( info.compression ) { + + case 0: + compress = compressNONE; + break; + + case 2: + case 3: + compress = compressZIP; + break; + + } + + if ( info.compression !== 0 ) { + + tmpBuffer = new Uint8Array( size ); + + } + + for ( let i = 0; i < info.numBlocks; ++ i ) { + + const arr = inBuffer.subarray( size * i, size * ( i + 1 ) ); + + const block = compress( arr, tmpBuffer ); + + sum += block.length; + + chunks.data.push( { dataChunk: block, size: block.length } ); + + } + + chunks.totalSize = sum; + + return chunks; + +} + +function compressNONE( data ) { + + return data; + +} + +function compressZIP( data, tmpBuffer ) { + + // + // Reorder the pixel data. + // + + let t1 = 0, + t2 = Math.floor( ( data.length + 1 ) / 2 ), + s = 0; + + const stop = data.length - 1; + + while ( true ) { + + if ( s > stop ) break; + tmpBuffer[ t1 ++ ] = data[ s ++ ]; + + if ( s > stop ) break; + tmpBuffer[ t2 ++ ] = data[ s ++ ]; + + } + + // + // Predictor. + // + + let p = tmpBuffer[ 0 ]; + + for ( let t = 1; t < tmpBuffer.length; t ++ ) { + + const d = tmpBuffer[ t ] - p + ( 128 + 256 ); + p = tmpBuffer[ t ]; + tmpBuffer[ t ] = d; + + } + + const deflate = fflate.zlibSync( tmpBuffer ); + + return deflate; + +} + +function fillHeader( outBuffer, chunks, info ) { + + const offset = { value: 0 }; + const dv = new DataView( outBuffer.buffer ); + + setUint32( dv, 20000630, offset ); // magic + setUint32( dv, 2, offset ); // mask + + // = HEADER = + + setString( dv, 'compression', offset ); + setString( dv, 'compression', offset ); + setUint32( dv, 1, offset ); + setUint8( dv, info.compression, offset ); + + setString( dv, 'screenWindowCenter', offset ); + setString( dv, 'v2f', offset ); + setUint32( dv, 8, offset ); + setUint32( dv, 0, offset ); + setUint32( dv, 0, offset ); + + setString( dv, 'screenWindowWidth', offset ); + setString( dv, 'float', offset ); + setUint32( dv, 4, offset ); + setFloat32( dv, 1.0, offset ); + + setString( dv, 'pixelAspectRatio', offset ); + setString( dv, 'float', offset ); + setUint32( dv, 4, offset ); + setFloat32( dv, 1.0, offset ); + + setString( dv, 'lineOrder', offset ); + setString( dv, 'lineOrder', offset ); + setUint32( dv, 1, offset ); + setUint8( dv, 0, offset ); + + setString( dv, 'dataWindow', offset ); + setString( dv, 'box2i', offset ); + setUint32( dv, 16, offset ); + setUint32( dv, 0, offset ); + setUint32( dv, 0, offset ); + setUint32( dv, info.width - 1, offset ); + setUint32( dv, info.height - 1, offset ); + + setString( dv, 'displayWindow', offset ); + setString( dv, 'box2i', offset ); + setUint32( dv, 16, offset ); + setUint32( dv, 0, offset ); + setUint32( dv, 0, offset ); + setUint32( dv, info.width - 1, offset ); + setUint32( dv, info.height - 1, offset ); + + setString( dv, 'channels', offset ); + setString( dv, 'chlist', offset ); + setUint32( dv, info.numOutputChannels * 18 + 1, offset ); + + setString( dv, 'A', offset ); + setUint32( dv, info.dataType, offset ); + offset.value += 4; + setUint32( dv, 1, offset ); + setUint32( dv, 1, offset ); + + setString( dv, 'B', offset ); + setUint32( dv, info.dataType, offset ); + offset.value += 4; + setUint32( dv, 1, offset ); + setUint32( dv, 1, offset ); + + setString( dv, 'G', offset ); + setUint32( dv, info.dataType, offset ); + offset.value += 4; + setUint32( dv, 1, offset ); + setUint32( dv, 1, offset ); + + setString( dv, 'R', offset ); + setUint32( dv, info.dataType, offset ); + offset.value += 4; + setUint32( dv, 1, offset ); + setUint32( dv, 1, offset ); + + setUint8( dv, 0, offset ); + + // null-byte + setUint8( dv, 0, offset ); + + // = OFFSET TABLE = + + let sum = offset.value + info.numBlocks * 8; + + for ( let i = 0; i < chunks.data.length; ++ i ) { + + setUint64( dv, sum, offset ); + + sum += chunks.data[ i ].size + 8; + + } + +} + +function fillData( chunks, info ) { + + const TableSize = info.numBlocks * 8, + HeaderSize = 259 + ( 18 * info.numOutputChannels ), // 259 + 18 * chlist + offset = { value: HeaderSize + TableSize }, + outBuffer = new Uint8Array( HeaderSize + TableSize + chunks.totalSize + info.numBlocks * 8 ), + dv = new DataView( outBuffer.buffer ); + + fillHeader( outBuffer, chunks, info ); + + for ( let i = 0; i < chunks.data.length; ++ i ) { + + const data = chunks.data[ i ].dataChunk; + const size = chunks.data[ i ].size; + + setUint32( dv, i * info.blockLines, offset ); + setUint32( dv, size, offset ); + + outBuffer.set( data, offset.value ); + offset.value += size; + + } + + return outBuffer; + +} + +function decodeLinear( dec, r, g, b, a ) { + + dec.r = r; + dec.g = g; + dec.b = b; + dec.a = a; + +} + +// function decodeSRGB( dec, r, g, b, a ) { + +// dec.r = r > 0.04045 ? Math.pow( r * 0.9478672986 + 0.0521327014, 2.4 ) : r * 0.0773993808; +// dec.g = g > 0.04045 ? Math.pow( g * 0.9478672986 + 0.0521327014, 2.4 ) : g * 0.0773993808; +// dec.b = b > 0.04045 ? Math.pow( b * 0.9478672986 + 0.0521327014, 2.4 ) : b * 0.0773993808; +// dec.a = a; + +// } + + +function setUint8( dv, value, offset ) { + + dv.setUint8( offset.value, value ); + + offset.value += 1; + +} + +function setUint32( dv, value, offset ) { + + dv.setUint32( offset.value, value, true ); + + offset.value += 4; + +} + +function setFloat16( dv, value, offset ) { + + dv.setUint16( offset.value, DataUtils.toHalfFloat( value ), true ); + + offset.value += 2; + +} + +function setFloat32( dv, value, offset ) { + + dv.setFloat32( offset.value, value, true ); + + offset.value += 4; + +} + +function setUint64( dv, value, offset ) { + + dv.setBigUint64( offset.value, BigInt( value ), true ); + + offset.value += 8; + +} + +function setString( dv, string, offset ) { + + const tmp = textEncoder.encode( string + '\0' ); + + for ( let i = 0; i < tmp.length; ++ i ) { + + setUint8( dv, tmp[ i ], offset ); + + } + +} + +function decodeFloat16( binary ) { + + const exponent = ( binary & 0x7C00 ) >> 10, + fraction = binary & 0x03FF; + + return ( binary >> 15 ? - 1 : 1 ) * ( + exponent ? + ( + exponent === 0x1F ? + fraction ? NaN : Infinity : + Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 ) + ) : + 6.103515625e-5 * ( fraction / 0x400 ) + ); + +} + +function getFloat16( arr, i ) { + + return decodeFloat16( arr[ i ] ); + +} + +function getFloat32( arr, i ) { + + return arr[ i ]; + +} + +export { EXRExporter, NO_COMPRESSION, ZIP_COMPRESSION, ZIPS_COMPRESSION }; diff --git a/renderer/jsm/exporters/GLTFExporter.js b/renderer/jsm/exporters/GLTFExporter.js new file mode 100644 index 0000000..ac67d35 --- /dev/null +++ b/renderer/jsm/exporters/GLTFExporter.js @@ -0,0 +1,2698 @@ +import { + BufferAttribute, + ClampToEdgeWrapping, + DoubleSide, + InterpolateDiscrete, + InterpolateLinear, + LinearEncoding, + LinearFilter, + LinearMipmapLinearFilter, + LinearMipmapNearestFilter, + MathUtils, + Matrix4, + MirroredRepeatWrapping, + NearestFilter, + NearestMipmapLinearFilter, + NearestMipmapNearestFilter, + PropertyBinding, + RGBAFormat, + RepeatWrapping, + Scene, + Source, + sRGBEncoding, + Vector3 +} from 'three'; + +class GLTFExporter { + + constructor() { + + this.pluginCallbacks = []; + + this.register( function ( writer ) { + + return new GLTFLightExtension( writer ); + + } ); + + this.register( function ( writer ) { + + return new GLTFMaterialsUnlitExtension( writer ); + + } ); + + this.register( function ( writer ) { + + return new GLTFMaterialsTransmissionExtension( writer ); + + } ); + + this.register( function ( writer ) { + + return new GLTFMaterialsVolumeExtension( writer ); + + } ); + + this.register( function ( writer ) { + + return new GLTFMaterialsClearcoatExtension( writer ); + + } ); + + this.register( function ( writer ) { + + return new GLTFMaterialsIridescenceExtension( writer ); + + } ); + + } + + register( callback ) { + + if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { + + this.pluginCallbacks.push( callback ); + + } + + return this; + + } + + unregister( callback ) { + + if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { + + this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); + + } + + return this; + + } + + /** + * Parse scenes and generate GLTF output + * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes + * @param {Function} onDone Callback on completed + * @param {Function} onError Callback on errors + * @param {Object} options options + */ + parse( input, onDone, onError, options ) { + + const writer = new GLTFWriter(); + const plugins = []; + + for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) { + + plugins.push( this.pluginCallbacks[ i ]( writer ) ); + + } + + writer.setPlugins( plugins ); + writer.write( input, onDone, options ).catch( onError ); + + } + + parseAsync( input, options ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.parse( input, resolve, reject, options ); + + } ); + + } + +} + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const WEBGL_CONSTANTS = { + POINTS: 0x0000, + LINES: 0x0001, + LINE_LOOP: 0x0002, + LINE_STRIP: 0x0003, + TRIANGLES: 0x0004, + TRIANGLE_STRIP: 0x0005, + TRIANGLE_FAN: 0x0006, + + UNSIGNED_BYTE: 0x1401, + UNSIGNED_SHORT: 0x1403, + FLOAT: 0x1406, + UNSIGNED_INT: 0x1405, + ARRAY_BUFFER: 0x8892, + ELEMENT_ARRAY_BUFFER: 0x8893, + + NEAREST: 0x2600, + LINEAR: 0x2601, + NEAREST_MIPMAP_NEAREST: 0x2700, + LINEAR_MIPMAP_NEAREST: 0x2701, + NEAREST_MIPMAP_LINEAR: 0x2702, + LINEAR_MIPMAP_LINEAR: 0x2703, + + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 +}; + +const THREE_TO_WEBGL = {}; + +THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST; +THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; +THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; +THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR; +THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; +THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; + +THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; +THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT; +THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT; + +const PATH_PROPERTIES = { + scale: 'scale', + position: 'translation', + quaternion: 'rotation', + morphTargetInfluences: 'weights' +}; + +// GLB constants +// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification + +const GLB_HEADER_BYTES = 12; +const GLB_HEADER_MAGIC = 0x46546C67; +const GLB_VERSION = 2; + +const GLB_CHUNK_PREFIX_BYTES = 8; +const GLB_CHUNK_TYPE_JSON = 0x4E4F534A; +const GLB_CHUNK_TYPE_BIN = 0x004E4942; + +//------------------------------------------------------------------------------ +// Utility functions +//------------------------------------------------------------------------------ + +/** + * Compare two arrays + * @param {Array} array1 Array 1 to compare + * @param {Array} array2 Array 2 to compare + * @return {Boolean} Returns true if both arrays are equal + */ +function equalArray( array1, array2 ) { + + return ( array1.length === array2.length ) && array1.every( function ( element, index ) { + + return element === array2[ index ]; + + } ); + +} + +/** + * Converts a string to an ArrayBuffer. + * @param {string} text + * @return {ArrayBuffer} + */ +function stringToArrayBuffer( text ) { + + return new TextEncoder().encode( text ).buffer; + +} + +/** + * Is identity matrix + * + * @param {Matrix4} matrix + * @returns {Boolean} Returns true, if parameter is identity matrix + */ +function isIdentityMatrix( matrix ) { + + return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ); + +} + +/** + * Get the min and max vectors from the given attribute + * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count + * @param {Integer} start + * @param {Integer} count + * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components) + */ +function getMinMax( attribute, start, count ) { + + const output = { + + min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ), + max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY ) + + }; + + for ( let i = start; i < start + count; i ++ ) { + + for ( let a = 0; a < attribute.itemSize; a ++ ) { + + let value; + + if ( attribute.itemSize > 4 ) { + + // no support for interleaved data for itemSize > 4 + + value = attribute.array[ i * attribute.itemSize + a ]; + + } else { + + if ( a === 0 ) value = attribute.getX( i ); + else if ( a === 1 ) value = attribute.getY( i ); + else if ( a === 2 ) value = attribute.getZ( i ); + else if ( a === 3 ) value = attribute.getW( i ); + + if ( attribute.normalized === true ) { + + value = MathUtils.normalize( value, attribute.array ); + + } + + } + + output.min[ a ] = Math.min( output.min[ a ], value ); + output.max[ a ] = Math.max( output.max[ a ], value ); + + } + + } + + return output; + +} + +/** + * Get the required size + padding for a buffer, rounded to the next 4-byte boundary. + * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment + * + * @param {Integer} bufferSize The size the original buffer. + * @returns {Integer} new buffer size with required padding. + * + */ +function getPaddedBufferSize( bufferSize ) { + + return Math.ceil( bufferSize / 4 ) * 4; + +} + +/** + * Returns a buffer aligned to 4-byte boundary. + * + * @param {ArrayBuffer} arrayBuffer Buffer to pad + * @param {Integer} paddingByte (Optional) + * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer + */ +function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) { + + const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength ); + + if ( paddedLength !== arrayBuffer.byteLength ) { + + const array = new Uint8Array( paddedLength ); + array.set( new Uint8Array( arrayBuffer ) ); + + if ( paddingByte !== 0 ) { + + for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) { + + array[ i ] = paddingByte; + + } + + } + + return array.buffer; + + } + + return arrayBuffer; + +} + +function getCanvas() { + + if ( typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' ) { + + return new OffscreenCanvas( 1, 1 ); + + } + + return document.createElement( 'canvas' ); + +} + +function getToBlobPromise( canvas, mimeType ) { + + if ( canvas.toBlob !== undefined ) { + + return new Promise( ( resolve ) => canvas.toBlob( resolve, mimeType ) ); + + } + + let quality; + + // Blink's implementation of convertToBlob seems to default to a quality level of 100% + // Use the Blink default quality levels of toBlob instead so that file sizes are comparable. + if ( mimeType === 'image/jpeg' ) { + + quality = 0.92; + + } else if ( mimeType === 'image/webp' ) { + + quality = 0.8; + + } + + return canvas.convertToBlob( { + + type: mimeType, + quality: quality + + } ); + +} + +/** + * Writer + */ +class GLTFWriter { + + constructor() { + + this.plugins = []; + + this.options = {}; + this.pending = []; + this.buffers = []; + + this.byteOffset = 0; + this.buffers = []; + this.nodeMap = new Map(); + this.skins = []; + this.extensionsUsed = {}; + + this.uids = new Map(); + this.uid = 0; + + this.json = { + asset: { + version: '2.0', + generator: 'THREE.GLTFExporter' + } + }; + + this.cache = { + meshes: new Map(), + attributes: new Map(), + attributesNormalized: new Map(), + materials: new Map(), + textures: new Map(), + images: new Map() + }; + + } + + setPlugins( plugins ) { + + this.plugins = plugins; + + } + + /** + * Parse scenes and generate GLTF output + * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes + * @param {Function} onDone Callback on completed + * @param {Object} options options + */ + async write( input, onDone, options = {} ) { + + this.options = Object.assign( { + // default options + binary: false, + trs: false, + onlyVisible: true, + maxTextureSize: Infinity, + animations: [], + includeCustomExtensions: false + }, options ); + + if ( this.options.animations.length > 0 ) { + + // Only TRS properties, and not matrices, may be targeted by animation. + this.options.trs = true; + + } + + this.processInput( input ); + + await Promise.all( this.pending ); + + const writer = this; + const buffers = writer.buffers; + const json = writer.json; + options = writer.options; + const extensionsUsed = writer.extensionsUsed; + + // Merge buffers. + const blob = new Blob( buffers, { type: 'application/octet-stream' } ); + + // Declare extensions. + const extensionsUsedList = Object.keys( extensionsUsed ); + + if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList; + + // Update bytelength of the single buffer. + if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size; + + if ( options.binary === true ) { + + // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification + + const reader = new FileReader(); + reader.readAsArrayBuffer( blob ); + reader.onloadend = function () { + + // Binary chunk. + const binaryChunk = getPaddedArrayBuffer( reader.result ); + const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) ); + binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true ); + binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true ); + + // JSON chunk. + const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 ); + const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) ); + jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true ); + jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true ); + + // GLB header. + const header = new ArrayBuffer( GLB_HEADER_BYTES ); + const headerView = new DataView( header ); + headerView.setUint32( 0, GLB_HEADER_MAGIC, true ); + headerView.setUint32( 4, GLB_VERSION, true ); + const totalByteLength = GLB_HEADER_BYTES + + jsonChunkPrefix.byteLength + jsonChunk.byteLength + + binaryChunkPrefix.byteLength + binaryChunk.byteLength; + headerView.setUint32( 8, totalByteLength, true ); + + const glbBlob = new Blob( [ + header, + jsonChunkPrefix, + jsonChunk, + binaryChunkPrefix, + binaryChunk + ], { type: 'application/octet-stream' } ); + + const glbReader = new FileReader(); + glbReader.readAsArrayBuffer( glbBlob ); + glbReader.onloadend = function () { + + onDone( glbReader.result ); + + }; + + }; + + } else { + + if ( json.buffers && json.buffers.length > 0 ) { + + const reader = new FileReader(); + reader.readAsDataURL( blob ); + reader.onloadend = function () { + + const base64data = reader.result; + json.buffers[ 0 ].uri = base64data; + onDone( json ); + + }; + + } else { + + onDone( json ); + + } + + } + + + } + + /** + * Serializes a userData. + * + * @param {THREE.Object3D|THREE.Material} object + * @param {Object} objectDef + */ + serializeUserData( object, objectDef ) { + + if ( Object.keys( object.userData ).length === 0 ) return; + + const options = this.options; + const extensionsUsed = this.extensionsUsed; + + try { + + const json = JSON.parse( JSON.stringify( object.userData ) ); + + if ( options.includeCustomExtensions && json.gltfExtensions ) { + + if ( objectDef.extensions === undefined ) objectDef.extensions = {}; + + for ( const extensionName in json.gltfExtensions ) { + + objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ]; + extensionsUsed[ extensionName ] = true; + + } + + delete json.gltfExtensions; + + } + + if ( Object.keys( json ).length > 0 ) objectDef.extras = json; + + } catch ( error ) { + + console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' + + 'won\'t be serialized because of JSON.stringify error - ' + error.message ); + + } + + } + + /** + * Returns ids for buffer attributes. + * @param {Object} object + * @return {Integer} + */ + getUID( attribute, isRelativeCopy = false ) { + + if ( this.uids.has( attribute ) === false ) { + + const uids = new Map(); + + uids.set( true, this.uid ++ ); + uids.set( false, this.uid ++ ); + + this.uids.set( attribute, uids ); + + } + + const uids = this.uids.get( attribute ); + + return uids.get( isRelativeCopy ); + + } + + /** + * Checks if normal attribute values are normalized. + * + * @param {BufferAttribute} normal + * @returns {Boolean} + */ + isNormalizedNormalAttribute( normal ) { + + const cache = this.cache; + + if ( cache.attributesNormalized.has( normal ) ) return false; + + const v = new Vector3(); + + for ( let i = 0, il = normal.count; i < il; i ++ ) { + + // 0.0005 is from glTF-validator + if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false; + + } + + return true; + + } + + /** + * Creates normalized normal buffer attribute. + * + * @param {BufferAttribute} normal + * @returns {BufferAttribute} + * + */ + createNormalizedNormalAttribute( normal ) { + + const cache = this.cache; + + if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal ); + + const attribute = normal.clone(); + const v = new Vector3(); + + for ( let i = 0, il = attribute.count; i < il; i ++ ) { + + v.fromBufferAttribute( attribute, i ); + + if ( v.x === 0 && v.y === 0 && v.z === 0 ) { + + // if values can't be normalized set (1, 0, 0) + v.setX( 1.0 ); + + } else { + + v.normalize(); + + } + + attribute.setXYZ( i, v.x, v.y, v.z ); + + } + + cache.attributesNormalized.set( normal, attribute ); + + return attribute; + + } + + /** + * Applies a texture transform, if present, to the map definition. Requires + * the KHR_texture_transform extension. + * + * @param {Object} mapDef + * @param {THREE.Texture} texture + */ + applyTextureTransform( mapDef, texture ) { + + let didTransform = false; + const transformDef = {}; + + if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) { + + transformDef.offset = texture.offset.toArray(); + didTransform = true; + + } + + if ( texture.rotation !== 0 ) { + + transformDef.rotation = texture.rotation; + didTransform = true; + + } + + if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) { + + transformDef.scale = texture.repeat.toArray(); + didTransform = true; + + } + + if ( didTransform ) { + + mapDef.extensions = mapDef.extensions || {}; + mapDef.extensions[ 'KHR_texture_transform' ] = transformDef; + this.extensionsUsed[ 'KHR_texture_transform' ] = true; + + } + + } + + buildMetalRoughTexture( metalnessMap, roughnessMap ) { + + if ( metalnessMap === roughnessMap ) return metalnessMap; + + function getEncodingConversion( map ) { + + if ( map.encoding === sRGBEncoding ) { + + return function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + + }; + + } + + return function LinearToLinear( c ) { + + return c; + + }; + + } + + console.warn( 'THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.' ); + + const metalness = metalnessMap ? metalnessMap.image : null; + const roughness = roughnessMap ? roughnessMap.image : null; + + const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 ); + const height = Math.max( metalness ? metalness.height : 0, roughness ? roughness.height : 0 ); + + const canvas = getCanvas(); + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.fillStyle = '#00ffff'; + context.fillRect( 0, 0, width, height ); + + const composite = context.getImageData( 0, 0, width, height ); + + if ( metalness ) { + + context.drawImage( metalness, 0, 0, width, height ); + + const convert = getEncodingConversion( metalnessMap ); + const data = context.getImageData( 0, 0, width, height ).data; + + for ( let i = 2; i < data.length; i += 4 ) { + + composite.data[ i ] = convert( data[ i ] / 256 ) * 256; + + } + + } + + if ( roughness ) { + + context.drawImage( roughness, 0, 0, width, height ); + + const convert = getEncodingConversion( roughnessMap ); + const data = context.getImageData( 0, 0, width, height ).data; + + for ( let i = 1; i < data.length; i += 4 ) { + + composite.data[ i ] = convert( data[ i ] / 256 ) * 256; + + } + + } + + context.putImageData( composite, 0, 0 ); + + // + + const reference = metalnessMap || roughnessMap; + + const texture = reference.clone(); + + texture.source = new Source( canvas ); + texture.encoding = LinearEncoding; + + return texture; + + } + + /** + * Process a buffer to append to the default one. + * @param {ArrayBuffer} buffer + * @return {Integer} + */ + processBuffer( buffer ) { + + const json = this.json; + const buffers = this.buffers; + + if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ]; + + // All buffers are merged before export. + buffers.push( buffer ); + + return 0; + + } + + /** + * Process and generate a BufferView + * @param {BufferAttribute} attribute + * @param {number} componentType + * @param {number} start + * @param {number} count + * @param {number} target (Optional) Target usage of the BufferView + * @return {Object} + */ + processBufferView( attribute, componentType, start, count, target ) { + + const json = this.json; + + if ( ! json.bufferViews ) json.bufferViews = []; + + // Create a new dataview and dump the attribute's array into it + + let componentSize; + + if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) { + + componentSize = 1; + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) { + + componentSize = 2; + + } else { + + componentSize = 4; + + } + + const byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize ); + const dataView = new DataView( new ArrayBuffer( byteLength ) ); + let offset = 0; + + for ( let i = start; i < start + count; i ++ ) { + + for ( let a = 0; a < attribute.itemSize; a ++ ) { + + let value; + + if ( attribute.itemSize > 4 ) { + + // no support for interleaved data for itemSize > 4 + + value = attribute.array[ i * attribute.itemSize + a ]; + + } else { + + if ( a === 0 ) value = attribute.getX( i ); + else if ( a === 1 ) value = attribute.getY( i ); + else if ( a === 2 ) value = attribute.getZ( i ); + else if ( a === 3 ) value = attribute.getW( i ); + + if ( attribute.normalized === true ) { + + value = MathUtils.normalize( value, attribute.array ); + + } + + } + + if ( componentType === WEBGL_CONSTANTS.FLOAT ) { + + dataView.setFloat32( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) { + + dataView.setUint32( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) { + + dataView.setUint16( offset, value, true ); + + } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) { + + dataView.setUint8( offset, value ); + + } + + offset += componentSize; + + } + + } + + const bufferViewDef = { + + buffer: this.processBuffer( dataView.buffer ), + byteOffset: this.byteOffset, + byteLength: byteLength + + }; + + if ( target !== undefined ) bufferViewDef.target = target; + + if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) { + + // Only define byteStride for vertex attributes. + bufferViewDef.byteStride = attribute.itemSize * componentSize; + + } + + this.byteOffset += byteLength; + + json.bufferViews.push( bufferViewDef ); + + // @TODO Merge bufferViews where possible. + const output = { + + id: json.bufferViews.length - 1, + byteLength: 0 + + }; + + return output; + + } + + /** + * Process and generate a BufferView from an image Blob. + * @param {Blob} blob + * @return {Promise} + */ + processBufferViewImage( blob ) { + + const writer = this; + const json = writer.json; + + if ( ! json.bufferViews ) json.bufferViews = []; + + return new Promise( function ( resolve ) { + + const reader = new FileReader(); + reader.readAsArrayBuffer( blob ); + reader.onloadend = function () { + + const buffer = getPaddedArrayBuffer( reader.result ); + + const bufferViewDef = { + buffer: writer.processBuffer( buffer ), + byteOffset: writer.byteOffset, + byteLength: buffer.byteLength + }; + + writer.byteOffset += buffer.byteLength; + resolve( json.bufferViews.push( bufferViewDef ) - 1 ); + + }; + + } ); + + } + + /** + * Process attribute to generate an accessor + * @param {BufferAttribute} attribute Attribute to process + * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range + * @param {Integer} start (Optional) + * @param {Integer} count (Optional) + * @return {Integer|null} Index of the processed accessor on the "accessors" array + */ + processAccessor( attribute, geometry, start, count ) { + + const json = this.json; + + const types = { + + 1: 'SCALAR', + 2: 'VEC2', + 3: 'VEC3', + 4: 'VEC4', + 16: 'MAT4' + + }; + + let componentType; + + // Detect the component type of the attribute array (float, uint or ushort) + if ( attribute.array.constructor === Float32Array ) { + + componentType = WEBGL_CONSTANTS.FLOAT; + + } else if ( attribute.array.constructor === Uint32Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_INT; + + } else if ( attribute.array.constructor === Uint16Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; + + } else if ( attribute.array.constructor === Uint8Array ) { + + componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; + + } else { + + throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' ); + + } + + if ( start === undefined ) start = 0; + if ( count === undefined ) count = attribute.count; + + // Skip creating an accessor if the attribute doesn't have data to export + if ( count === 0 ) return null; + + const minMax = getMinMax( attribute, start, count ); + let bufferViewTarget; + + // If geometry isn't provided, don't infer the target usage of the bufferView. For + // animation samplers, target must not be set. + if ( geometry !== undefined ) { + + bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; + + } + + const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget ); + + const accessorDef = { + + bufferView: bufferView.id, + byteOffset: bufferView.byteOffset, + componentType: componentType, + count: count, + max: minMax.max, + min: minMax.min, + type: types[ attribute.itemSize ] + + }; + + if ( attribute.normalized === true ) accessorDef.normalized = true; + if ( ! json.accessors ) json.accessors = []; + + return json.accessors.push( accessorDef ) - 1; + + } + + /** + * Process image + * @param {Image} image to process + * @param {Integer} format of the image (RGBAFormat) + * @param {Boolean} flipY before writing out the image + * @param {String} mimeType export format + * @return {Integer} Index of the processed texture in the "images" array + */ + processImage( image, format, flipY, mimeType = 'image/png' ) { + + if ( image !== null ) { + + const writer = this; + const cache = writer.cache; + const json = writer.json; + const options = writer.options; + const pending = writer.pending; + + if ( ! cache.images.has( image ) ) cache.images.set( image, {} ); + + const cachedImages = cache.images.get( image ); + + const key = mimeType + ':flipY/' + flipY.toString(); + + if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ]; + + if ( ! json.images ) json.images = []; + + const imageDef = { mimeType: mimeType }; + + const canvas = getCanvas(); + + canvas.width = Math.min( image.width, options.maxTextureSize ); + canvas.height = Math.min( image.height, options.maxTextureSize ); + + const ctx = canvas.getContext( '2d' ); + + if ( flipY === true ) { + + ctx.translate( 0, canvas.height ); + ctx.scale( 1, - 1 ); + + } + + if ( image.data !== undefined ) { // THREE.DataTexture + + if ( format !== RGBAFormat ) { + + console.error( 'GLTFExporter: Only RGBAFormat is supported.' ); + + } + + if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) { + + console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image ); + + } + + const data = new Uint8ClampedArray( image.height * image.width * 4 ); + + for ( let i = 0; i < data.length; i += 4 ) { + + data[ i + 0 ] = image.data[ i + 0 ]; + data[ i + 1 ] = image.data[ i + 1 ]; + data[ i + 2 ] = image.data[ i + 2 ]; + data[ i + 3 ] = image.data[ i + 3 ]; + + } + + ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 ); + + } else { + + ctx.drawImage( image, 0, 0, canvas.width, canvas.height ); + + } + + if ( options.binary === true ) { + + pending.push( + + getToBlobPromise( canvas, mimeType ) + .then( blob => writer.processBufferViewImage( blob ) ) + .then( bufferViewIndex => { + + imageDef.bufferView = bufferViewIndex; + + } ) + + ); + + } else { + + if ( canvas.toDataURL !== undefined ) { + + imageDef.uri = canvas.toDataURL( mimeType ); + + } else { + + pending.push( + + getToBlobPromise( canvas, mimeType ) + .then( blob => new FileReader().readAsDataURL( blob ) ) + .then( dataURL => { + + imageDef.uri = dataURL; + + } ) + + ); + + } + + } + + const index = json.images.push( imageDef ) - 1; + cachedImages[ key ] = index; + return index; + + } else { + + throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' ); + + } + + } + + /** + * Process sampler + * @param {Texture} map Texture to process + * @return {Integer} Index of the processed texture in the "samplers" array + */ + processSampler( map ) { + + const json = this.json; + + if ( ! json.samplers ) json.samplers = []; + + const samplerDef = { + magFilter: THREE_TO_WEBGL[ map.magFilter ], + minFilter: THREE_TO_WEBGL[ map.minFilter ], + wrapS: THREE_TO_WEBGL[ map.wrapS ], + wrapT: THREE_TO_WEBGL[ map.wrapT ] + }; + + return json.samplers.push( samplerDef ) - 1; + + } + + /** + * Process texture + * @param {Texture} map Map to process + * @return {Integer} Index of the processed texture in the "textures" array + */ + processTexture( map ) { + + const cache = this.cache; + const json = this.json; + + if ( cache.textures.has( map ) ) return cache.textures.get( map ); + + if ( ! json.textures ) json.textures = []; + + let mimeType = map.userData.mimeType; + + if ( mimeType === 'image/webp' ) mimeType = 'image/png'; + + const textureDef = { + sampler: this.processSampler( map ), + source: this.processImage( map.image, map.format, map.flipY, mimeType ) + }; + + if ( map.name ) textureDef.name = map.name; + + this._invokeAll( function ( ext ) { + + ext.writeTexture && ext.writeTexture( map, textureDef ); + + } ); + + const index = json.textures.push( textureDef ) - 1; + cache.textures.set( map, index ); + return index; + + } + + /** + * Process material + * @param {THREE.Material} material Material to process + * @return {Integer|null} Index of the processed material in the "materials" array + */ + processMaterial( material ) { + + const cache = this.cache; + const json = this.json; + + if ( cache.materials.has( material ) ) return cache.materials.get( material ); + + if ( material.isShaderMaterial ) { + + console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' ); + return null; + + } + + if ( ! json.materials ) json.materials = []; + + // @QUESTION Should we avoid including any attribute that has the default value? + const materialDef = { pbrMetallicRoughness: {} }; + + if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) { + + console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' ); + + } + + // pbrMetallicRoughness.baseColorFactor + const color = material.color.toArray().concat( [ material.opacity ] ); + + if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) { + + materialDef.pbrMetallicRoughness.baseColorFactor = color; + + } + + if ( material.isMeshStandardMaterial ) { + + materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; + materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; + + } else { + + materialDef.pbrMetallicRoughness.metallicFactor = 0.5; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; + + } + + // pbrMetallicRoughness.metallicRoughnessTexture + if ( material.metalnessMap || material.roughnessMap ) { + + const metalRoughTexture = this.buildMetalRoughTexture( material.metalnessMap, material.roughnessMap ); + + const metalRoughMapDef = { index: this.processTexture( metalRoughTexture ) }; + this.applyTextureTransform( metalRoughMapDef, metalRoughTexture ); + materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + + } + + // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture + if ( material.map ) { + + const baseColorMapDef = { index: this.processTexture( material.map ) }; + this.applyTextureTransform( baseColorMapDef, material.map ); + materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; + + } + + if ( material.emissive ) { + + // note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000. + const emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ); + const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b ); + + if ( maxEmissiveComponent > 1 ) { + + emissive.multiplyScalar( 1 / maxEmissiveComponent ); + + console.warn( 'THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited' ); + + } + + if ( maxEmissiveComponent > 0 ) { + + materialDef.emissiveFactor = emissive.toArray(); + + } + + // emissiveTexture + if ( material.emissiveMap ) { + + const emissiveMapDef = { index: this.processTexture( material.emissiveMap ) }; + this.applyTextureTransform( emissiveMapDef, material.emissiveMap ); + materialDef.emissiveTexture = emissiveMapDef; + + } + + } + + // normalTexture + if ( material.normalMap ) { + + const normalMapDef = { index: this.processTexture( material.normalMap ) }; + + if ( material.normalScale && material.normalScale.x !== 1 ) { + + // glTF normal scale is univariate. Ignore `y`, which may be flipped. + // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 + normalMapDef.scale = material.normalScale.x; + + } + + this.applyTextureTransform( normalMapDef, material.normalMap ); + materialDef.normalTexture = normalMapDef; + + } + + // occlusionTexture + if ( material.aoMap ) { + + const occlusionMapDef = { + index: this.processTexture( material.aoMap ), + texCoord: 1 + }; + + if ( material.aoMapIntensity !== 1.0 ) { + + occlusionMapDef.strength = material.aoMapIntensity; + + } + + this.applyTextureTransform( occlusionMapDef, material.aoMap ); + materialDef.occlusionTexture = occlusionMapDef; + + } + + // alphaMode + if ( material.transparent ) { + + materialDef.alphaMode = 'BLEND'; + + } else { + + if ( material.alphaTest > 0.0 ) { + + materialDef.alphaMode = 'MASK'; + materialDef.alphaCutoff = material.alphaTest; + + } + + } + + // doubleSided + if ( material.side === DoubleSide ) materialDef.doubleSided = true; + if ( material.name !== '' ) materialDef.name = material.name; + + this.serializeUserData( material, materialDef ); + + this._invokeAll( function ( ext ) { + + ext.writeMaterial && ext.writeMaterial( material, materialDef ); + + } ); + + const index = json.materials.push( materialDef ) - 1; + cache.materials.set( material, index ); + return index; + + } + + /** + * Process mesh + * @param {THREE.Mesh} mesh Mesh to process + * @return {Integer|null} Index of the processed mesh in the "meshes" array + */ + processMesh( mesh ) { + + const cache = this.cache; + const json = this.json; + + const meshCacheKeyParts = [ mesh.geometry.uuid ]; + + if ( Array.isArray( mesh.material ) ) { + + for ( let i = 0, l = mesh.material.length; i < l; i ++ ) { + + meshCacheKeyParts.push( mesh.material[ i ].uuid ); + + } + + } else { + + meshCacheKeyParts.push( mesh.material.uuid ); + + } + + const meshCacheKey = meshCacheKeyParts.join( ':' ); + + if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey ); + + const geometry = mesh.geometry; + + let mode; + + // Use the correct mode + if ( mesh.isLineSegments ) { + + mode = WEBGL_CONSTANTS.LINES; + + } else if ( mesh.isLineLoop ) { + + mode = WEBGL_CONSTANTS.LINE_LOOP; + + } else if ( mesh.isLine ) { + + mode = WEBGL_CONSTANTS.LINE_STRIP; + + } else if ( mesh.isPoints ) { + + mode = WEBGL_CONSTANTS.POINTS; + + } else { + + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; + + } + + const meshDef = {}; + const attributes = {}; + const primitives = []; + const targets = []; + + // Conversion between attributes names in threejs and gltf spec + const nameConversion = { + uv: 'TEXCOORD_0', + uv2: 'TEXCOORD_1', + color: 'COLOR_0', + skinWeight: 'WEIGHTS_0', + skinIndex: 'JOINTS_0' + }; + + const originalNormal = geometry.getAttribute( 'normal' ); + + if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) { + + console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' ); + + geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) ); + + } + + // @QUESTION Detect if .vertexColors = true? + // For every attribute create an accessor + let modifiedAttribute = null; + + for ( let attributeName in geometry.attributes ) { + + // Ignore morph target attributes, which are exported later. + if ( attributeName.slice( 0, 5 ) === 'morph' ) continue; + + const attribute = geometry.attributes[ attributeName ]; + attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase(); + + // Prefix all geometry attributes except the ones specifically + // listed in the spec; non-spec attributes are considered custom. + const validVertexAttributes = + /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; + + if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName; + + if ( cache.attributes.has( this.getUID( attribute ) ) ) { + + attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) ); + continue; + + } + + // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT. + modifiedAttribute = null; + const array = attribute.array; + + if ( attributeName === 'JOINTS_0' && + ! ( array instanceof Uint16Array ) && + ! ( array instanceof Uint8Array ) ) { + + console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' ); + modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized ); + + } + + const accessor = this.processAccessor( modifiedAttribute || attribute, geometry ); + + if ( accessor !== null ) { + + attributes[ attributeName ] = accessor; + cache.attributes.set( this.getUID( attribute ), accessor ); + + } + + } + + if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal ); + + // Skip if no exportable attributes found + if ( Object.keys( attributes ).length === 0 ) return null; + + // Morph targets + if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) { + + const weights = []; + const targetNames = []; + const reverseDictionary = {}; + + if ( mesh.morphTargetDictionary !== undefined ) { + + for ( const key in mesh.morphTargetDictionary ) { + + reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key; + + } + + } + + for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) { + + const target = {}; + let warned = false; + + for ( const attributeName in geometry.morphAttributes ) { + + // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT. + // Three.js doesn't support TANGENT yet. + + if ( attributeName !== 'position' && attributeName !== 'normal' ) { + + if ( ! warned ) { + + console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' ); + warned = true; + + } + + continue; + + } + + const attribute = geometry.morphAttributes[ attributeName ][ i ]; + const gltfAttributeName = attributeName.toUpperCase(); + + // Three.js morph attribute has absolute values while the one of glTF has relative values. + // + // glTF 2.0 Specification: + // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets + + const baseAttribute = geometry.attributes[ attributeName ]; + + if ( cache.attributes.has( this.getUID( attribute, true ) ) ) { + + target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) ); + continue; + + } + + // Clones attribute not to override + const relativeAttribute = attribute.clone(); + + if ( ! geometry.morphTargetsRelative ) { + + for ( let j = 0, jl = attribute.count; j < jl; j ++ ) { + + for ( let a = 0; a < attribute.itemSize; a ++ ) { + + if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) ); + if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) ); + if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) ); + if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) ); + + } + + } + + } + + target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry ); + cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] ); + + } + + targets.push( target ); + + weights.push( mesh.morphTargetInfluences[ i ] ); + + if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] ); + + } + + meshDef.weights = weights; + + if ( targetNames.length > 0 ) { + + meshDef.extras = {}; + meshDef.extras.targetNames = targetNames; + + } + + } + + const isMultiMaterial = Array.isArray( mesh.material ); + + if ( isMultiMaterial && geometry.groups.length === 0 ) return null; + + const materials = isMultiMaterial ? mesh.material : [ mesh.material ]; + const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ]; + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const primitive = { + mode: mode, + attributes: attributes, + }; + + this.serializeUserData( geometry, primitive ); + + if ( targets.length > 0 ) primitive.targets = targets; + + if ( geometry.index !== null ) { + + let cacheKey = this.getUID( geometry.index ); + + if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) { + + cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count; + + } + + if ( cache.attributes.has( cacheKey ) ) { + + primitive.indices = cache.attributes.get( cacheKey ); + + } else { + + primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count ); + cache.attributes.set( cacheKey, primitive.indices ); + + } + + if ( primitive.indices === null ) delete primitive.indices; + + } + + const material = this.processMaterial( materials[ groups[ i ].materialIndex ] ); + + if ( material !== null ) primitive.material = material; + + primitives.push( primitive ); + + } + + meshDef.primitives = primitives; + + if ( ! json.meshes ) json.meshes = []; + + this._invokeAll( function ( ext ) { + + ext.writeMesh && ext.writeMesh( mesh, meshDef ); + + } ); + + const index = json.meshes.push( meshDef ) - 1; + cache.meshes.set( meshCacheKey, index ); + return index; + + } + + /** + * Process camera + * @param {THREE.Camera} camera Camera to process + * @return {Integer} Index of the processed mesh in the "camera" array + */ + processCamera( camera ) { + + const json = this.json; + + if ( ! json.cameras ) json.cameras = []; + + const isOrtho = camera.isOrthographicCamera; + + const cameraDef = { + type: isOrtho ? 'orthographic' : 'perspective' + }; + + if ( isOrtho ) { + + cameraDef.orthographic = { + xmag: camera.right * 2, + ymag: camera.top * 2, + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + + } else { + + cameraDef.perspective = { + aspectRatio: camera.aspect, + yfov: MathUtils.degToRad( camera.fov ), + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + + } + + // Question: Is saving "type" as name intentional? + if ( camera.name !== '' ) cameraDef.name = camera.type; + + return json.cameras.push( cameraDef ) - 1; + + } + + /** + * Creates glTF animation entry from AnimationClip object. + * + * Status: + * - Only properties listed in PATH_PROPERTIES may be animated. + * + * @param {THREE.AnimationClip} clip + * @param {THREE.Object3D} root + * @return {number|null} + */ + processAnimation( clip, root ) { + + const json = this.json; + const nodeMap = this.nodeMap; + + if ( ! json.animations ) json.animations = []; + + clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root ); + + const tracks = clip.tracks; + const channels = []; + const samplers = []; + + for ( let i = 0; i < tracks.length; ++ i ) { + + const track = tracks[ i ]; + const trackBinding = PropertyBinding.parseTrackName( track.name ); + let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName ); + const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ]; + + if ( trackBinding.objectName === 'bones' ) { + + if ( trackNode.isSkinnedMesh === true ) { + + trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex ); + + } else { + + trackNode = undefined; + + } + + } + + if ( ! trackNode || ! trackProperty ) { + + console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name ); + return null; + + } + + const inputItemSize = 1; + let outputItemSize = track.values.length / track.times.length; + + if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) { + + outputItemSize /= trackNode.morphTargetInfluences.length; + + } + + let interpolation; + + // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE + + // Detecting glTF cubic spline interpolant by checking factory method's special property + // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return + // valid value from .getInterpolation(). + if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) { + + interpolation = 'CUBICSPLINE'; + + // itemSize of CUBICSPLINE keyframe is 9 + // (VEC3 * 3: inTangent, splineVertex, and outTangent) + // but needs to be stored as VEC3 so dividing by 3 here. + outputItemSize /= 3; + + } else if ( track.getInterpolation() === InterpolateDiscrete ) { + + interpolation = 'STEP'; + + } else { + + interpolation = 'LINEAR'; + + } + + samplers.push( { + input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ), + output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ), + interpolation: interpolation + } ); + + channels.push( { + sampler: samplers.length - 1, + target: { + node: nodeMap.get( trackNode ), + path: trackProperty + } + } ); + + } + + json.animations.push( { + name: clip.name || 'clip_' + json.animations.length, + samplers: samplers, + channels: channels + } ); + + return json.animations.length - 1; + + } + + /** + * @param {THREE.Object3D} object + * @return {number|null} + */ + processSkin( object ) { + + const json = this.json; + const nodeMap = this.nodeMap; + + const node = json.nodes[ nodeMap.get( object ) ]; + + const skeleton = object.skeleton; + + if ( skeleton === undefined ) return null; + + const rootJoint = object.skeleton.bones[ 0 ]; + + if ( rootJoint === undefined ) return null; + + const joints = []; + const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 ); + const temporaryBoneInverse = new Matrix4(); + + for ( let i = 0; i < skeleton.bones.length; ++ i ) { + + joints.push( nodeMap.get( skeleton.bones[ i ] ) ); + temporaryBoneInverse.copy( skeleton.boneInverses[ i ] ); + temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 ); + + } + + if ( json.skins === undefined ) json.skins = []; + + json.skins.push( { + inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ), + joints: joints, + skeleton: nodeMap.get( rootJoint ) + } ); + + const skinIndex = node.skin = json.skins.length - 1; + + return skinIndex; + + } + + /** + * Process Object3D node + * @param {THREE.Object3D} node Object3D to processNode + * @return {Integer} Index of the node in the nodes list + */ + processNode( object ) { + + const json = this.json; + const options = this.options; + const nodeMap = this.nodeMap; + + if ( ! json.nodes ) json.nodes = []; + + const nodeDef = {}; + + if ( options.trs ) { + + const rotation = object.quaternion.toArray(); + const position = object.position.toArray(); + const scale = object.scale.toArray(); + + if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) { + + nodeDef.rotation = rotation; + + } + + if ( ! equalArray( position, [ 0, 0, 0 ] ) ) { + + nodeDef.translation = position; + + } + + if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) { + + nodeDef.scale = scale; + + } + + } else { + + if ( object.matrixAutoUpdate ) { + + object.updateMatrix(); + + } + + if ( isIdentityMatrix( object.matrix ) === false ) { + + nodeDef.matrix = object.matrix.elements; + + } + + } + + // We don't export empty strings name because it represents no-name in Three.js. + if ( object.name !== '' ) nodeDef.name = String( object.name ); + + this.serializeUserData( object, nodeDef ); + + if ( object.isMesh || object.isLine || object.isPoints ) { + + const meshIndex = this.processMesh( object ); + + if ( meshIndex !== null ) nodeDef.mesh = meshIndex; + + } else if ( object.isCamera ) { + + nodeDef.camera = this.processCamera( object ); + + } + + if ( object.isSkinnedMesh ) this.skins.push( object ); + + if ( object.children.length > 0 ) { + + const children = []; + + for ( let i = 0, l = object.children.length; i < l; i ++ ) { + + const child = object.children[ i ]; + + if ( child.visible || options.onlyVisible === false ) { + + const nodeIndex = this.processNode( child ); + + if ( nodeIndex !== null ) children.push( nodeIndex ); + + } + + } + + if ( children.length > 0 ) nodeDef.children = children; + + } + + this._invokeAll( function ( ext ) { + + ext.writeNode && ext.writeNode( object, nodeDef ); + + } ); + + const nodeIndex = json.nodes.push( nodeDef ) - 1; + nodeMap.set( object, nodeIndex ); + return nodeIndex; + + } + + /** + * Process Scene + * @param {Scene} node Scene to process + */ + processScene( scene ) { + + const json = this.json; + const options = this.options; + + if ( ! json.scenes ) { + + json.scenes = []; + json.scene = 0; + + } + + const sceneDef = {}; + + if ( scene.name !== '' ) sceneDef.name = scene.name; + + json.scenes.push( sceneDef ); + + const nodes = []; + + for ( let i = 0, l = scene.children.length; i < l; i ++ ) { + + const child = scene.children[ i ]; + + if ( child.visible || options.onlyVisible === false ) { + + const nodeIndex = this.processNode( child ); + + if ( nodeIndex !== null ) nodes.push( nodeIndex ); + + } + + } + + if ( nodes.length > 0 ) sceneDef.nodes = nodes; + + this.serializeUserData( scene, sceneDef ); + + } + + /** + * Creates a Scene to hold a list of objects and parse it + * @param {Array} objects List of objects to process + */ + processObjects( objects ) { + + const scene = new Scene(); + scene.name = 'AuxScene'; + + for ( let i = 0; i < objects.length; i ++ ) { + + // We push directly to children instead of calling `add` to prevent + // modify the .parent and break its original scene and hierarchy + scene.children.push( objects[ i ] ); + + } + + this.processScene( scene ); + + } + + /** + * @param {THREE.Object3D|Array} input + */ + processInput( input ) { + + const options = this.options; + + input = input instanceof Array ? input : [ input ]; + + this._invokeAll( function ( ext ) { + + ext.beforeParse && ext.beforeParse( input ); + + } ); + + const objectsWithoutScene = []; + + for ( let i = 0; i < input.length; i ++ ) { + + if ( input[ i ] instanceof Scene ) { + + this.processScene( input[ i ] ); + + } else { + + objectsWithoutScene.push( input[ i ] ); + + } + + } + + if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene ); + + for ( let i = 0; i < this.skins.length; ++ i ) { + + this.processSkin( this.skins[ i ] ); + + } + + for ( let i = 0; i < options.animations.length; ++ i ) { + + this.processAnimation( options.animations[ i ], input[ 0 ] ); + + } + + this._invokeAll( function ( ext ) { + + ext.afterParse && ext.afterParse( input ); + + } ); + + } + + _invokeAll( func ) { + + for ( let i = 0, il = this.plugins.length; i < il; i ++ ) { + + func( this.plugins[ i ] ); + + } + + } + +} + +/** + * Punctual Lights Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual + */ +class GLTFLightExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_lights_punctual'; + + } + + writeNode( light, nodeDef ) { + + if ( ! light.isLight ) return; + + if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) { + + console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light ); + return; + + } + + const writer = this.writer; + const json = writer.json; + const extensionsUsed = writer.extensionsUsed; + + const lightDef = {}; + + if ( light.name ) lightDef.name = light.name; + + lightDef.color = light.color.toArray(); + + lightDef.intensity = light.intensity; + + if ( light.isDirectionalLight ) { + + lightDef.type = 'directional'; + + } else if ( light.isPointLight ) { + + lightDef.type = 'point'; + + if ( light.distance > 0 ) lightDef.range = light.distance; + + } else if ( light.isSpotLight ) { + + lightDef.type = 'spot'; + + if ( light.distance > 0 ) lightDef.range = light.distance; + + lightDef.spot = {}; + lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0; + lightDef.spot.outerConeAngle = light.angle; + + } + + if ( light.decay !== undefined && light.decay !== 2 ) { + + console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + + 'and expects light.decay=2.' ); + + } + + if ( light.target + && ( light.target.parent !== light + || light.target.position.x !== 0 + || light.target.position.y !== 0 + || light.target.position.z !== - 1 ) ) { + + console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, ' + + 'make light.target a child of the light with position 0,0,-1.' ); + + } + + if ( ! extensionsUsed[ this.name ] ) { + + json.extensions = json.extensions || {}; + json.extensions[ this.name ] = { lights: [] }; + extensionsUsed[ this.name ] = true; + + } + + const lights = json.extensions[ this.name ].lights; + lights.push( lightDef ); + + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[ this.name ] = { light: lights.length - 1 }; + + } + +} + +/** + * Unlit Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit + */ +class GLTFMaterialsUnlitExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_materials_unlit'; + + } + + writeMaterial( material, materialDef ) { + + if ( ! material.isMeshBasicMaterial ) return; + + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[ this.name ] = {}; + + extensionsUsed[ this.name ] = true; + + materialDef.pbrMetallicRoughness.metallicFactor = 0.0; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; + + } + +} + +/** + * Clearcoat Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat + */ +class GLTFMaterialsClearcoatExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_materials_clearcoat'; + + } + + writeMaterial( material, materialDef ) { + + if ( ! material.isMeshPhysicalMaterial ) return; + + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + + const extensionDef = {}; + + extensionDef.clearcoatFactor = material.clearcoat; + + if ( material.clearcoatMap ) { + + const clearcoatMapDef = { index: writer.processTexture( material.clearcoatMap ) }; + writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap ); + extensionDef.clearcoatTexture = clearcoatMapDef; + + } + + extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; + + if ( material.clearcoatRoughnessMap ) { + + const clearcoatRoughnessMapDef = { index: writer.processTexture( material.clearcoatRoughnessMap ) }; + writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap ); + extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; + + } + + if ( material.clearcoatNormalMap ) { + + const clearcoatNormalMapDef = { index: writer.processTexture( material.clearcoatNormalMap ) }; + writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap ); + extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; + + } + + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[ this.name ] = extensionDef; + + extensionsUsed[ this.name ] = true; + + + } + +} + +/** + * Iridescence Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence + */ +class GLTFMaterialsIridescenceExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_materials_iridescence'; + + } + + writeMaterial( material, materialDef ) { + + if ( ! material.isMeshPhysicalMaterial ) return; + + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + + const extensionDef = {}; + + extensionDef.iridescenceFactor = material.iridescence; + + if ( material.iridescenceMap ) { + + const iridescenceMapDef = { index: writer.processTexture( material.iridescenceMap ) }; + writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap ); + extensionDef.iridescenceTexture = iridescenceMapDef; + + } + + extensionDef.iridescenceIor = material.iridescenceIOR; + extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ]; + extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceThicknessMap ) { + + const iridescenceThicknessMapDef = { index: writer.processTexture( material.iridescenceThicknessMap ) }; + writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap ); + extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef; + + } + + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[ this.name ] = extensionDef; + + extensionsUsed[ this.name ] = true; + + } + +} + +/** + * Transmission Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission + */ +class GLTFMaterialsTransmissionExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_materials_transmission'; + + } + + writeMaterial( material, materialDef ) { + + if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return; + + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + + const extensionDef = {}; + + extensionDef.transmissionFactor = material.transmission; + + if ( material.transmissionMap ) { + + const transmissionMapDef = { index: writer.processTexture( material.transmissionMap ) }; + writer.applyTextureTransform( transmissionMapDef, material.transmissionMap ); + extensionDef.transmissionTexture = transmissionMapDef; + + } + + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[ this.name ] = extensionDef; + + extensionsUsed[ this.name ] = true; + + } + +} + +/** + * Materials Volume Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume + */ +class GLTFMaterialsVolumeExtension { + + constructor( writer ) { + + this.writer = writer; + this.name = 'KHR_materials_volume'; + + } + + writeMaterial( material, materialDef ) { + + if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return; + + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + + const extensionDef = {}; + + extensionDef.thicknessFactor = material.thickness; + + if ( material.thicknessMap ) { + + const thicknessMapDef = { index: writer.processTexture( material.thicknessMap ) }; + writer.applyTextureTransform( thicknessMapDef, material.thicknessMap ); + extensionDef.thicknessTexture = thicknessMapDef; + + } + + extensionDef.attenuationDistance = material.attenuationDistance; + extensionDef.attenuationColor = material.attenuationColor.toArray(); + + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[ this.name ] = extensionDef; + + extensionsUsed[ this.name ] = true; + + } + +} + +/** + * Static utility functions + */ +GLTFExporter.Utils = { + + insertKeyframe: function ( track, time ) { + + const tolerance = 0.001; // 1ms + const valueSize = track.getValueSize(); + + const times = new track.TimeBufferType( track.times.length + 1 ); + const values = new track.ValueBufferType( track.values.length + valueSize ); + const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) ); + + let index; + + if ( track.times.length === 0 ) { + + times[ 0 ] = time; + + for ( let i = 0; i < valueSize; i ++ ) { + + values[ i ] = 0; + + } + + index = 0; + + } else if ( time < track.times[ 0 ] ) { + + if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0; + + times[ 0 ] = time; + times.set( track.times, 1 ); + + values.set( interpolant.evaluate( time ), 0 ); + values.set( track.values, valueSize ); + + index = 0; + + } else if ( time > track.times[ track.times.length - 1 ] ) { + + if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) { + + return track.times.length - 1; + + } + + times[ times.length - 1 ] = time; + times.set( track.times, 0 ); + + values.set( track.values, 0 ); + values.set( interpolant.evaluate( time ), track.values.length ); + + index = times.length - 1; + + } else { + + for ( let i = 0; i < track.times.length; i ++ ) { + + if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i; + + if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) { + + times.set( track.times.slice( 0, i + 1 ), 0 ); + times[ i + 1 ] = time; + times.set( track.times.slice( i + 1 ), i + 2 ); + + values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 ); + values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize ); + values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize ); + + index = i + 1; + + break; + + } + + } + + } + + track.times = times; + track.values = values; + + return index; + + }, + + mergeMorphTargetTracks: function ( clip, root ) { + + const tracks = []; + const mergedTracks = {}; + const sourceTracks = clip.tracks; + + for ( let i = 0; i < sourceTracks.length; ++ i ) { + + let sourceTrack = sourceTracks[ i ]; + const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name ); + const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName ); + + if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) { + + // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is. + tracks.push( sourceTrack ); + continue; + + } + + if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete + && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) { + + if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + // This should never happen, because glTF morph target animations + // affect all targets already. + throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' ); + + } + + console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' ); + + sourceTrack = sourceTrack.clone(); + sourceTrack.setInterpolation( InterpolateLinear ); + + } + + const targetCount = sourceTrackNode.morphTargetInfluences.length; + const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ]; + + if ( targetIndex === undefined ) { + + throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex ); + + } + + let mergedTrack; + + // If this is the first time we've seen this object, create a new + // track to store merged keyframe data for each morph target. + if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) { + + mergedTrack = sourceTrack.clone(); + + const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length ); + + for ( let j = 0; j < mergedTrack.times.length; j ++ ) { + + values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ]; + + } + + // We need to take into consideration the intended target node + // of our original un-merged morphTarget animation. + mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences'; + mergedTrack.values = values; + + mergedTracks[ sourceTrackNode.uuid ] = mergedTrack; + tracks.push( mergedTrack ); + + continue; + + } + + const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) ); + + mergedTrack = mergedTracks[ sourceTrackNode.uuid ]; + + // For every existing keyframe of the merged track, write a (possibly + // interpolated) value from the source track. + for ( let j = 0; j < mergedTrack.times.length; j ++ ) { + + mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] ); + + } + + // For every existing keyframe of the source track, write a (possibly + // new) keyframe to the merged track. Values from the previous loop may + // be written again, but keyframes are de-duplicated. + for ( let j = 0; j < sourceTrack.times.length; j ++ ) { + + const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] ); + mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ]; + + } + + } + + clip.tracks = tracks; + + return clip; + + } + +}; + +export { GLTFExporter }; diff --git a/renderer/jsm/exporters/KTX2Exporter.js b/renderer/jsm/exporters/KTX2Exporter.js new file mode 100644 index 0000000..f7aeabb --- /dev/null +++ b/renderer/jsm/exporters/KTX2Exporter.js @@ -0,0 +1,281 @@ +import { + FloatType, + HalfFloatType, + UnsignedByteType, + RGBAFormat, + RGFormat, + RGIntegerFormat, + RedFormat, + RedIntegerFormat, + LinearEncoding, + sRGBEncoding, + DataTexture, + REVISION, +} from 'three'; + +import { + write, + KTX2Container, + KHR_DF_CHANNEL_RGBSDA_ALPHA, + KHR_DF_CHANNEL_RGBSDA_BLUE, + KHR_DF_CHANNEL_RGBSDA_GREEN, + KHR_DF_CHANNEL_RGBSDA_RED, + KHR_DF_MODEL_RGBSDA, + KHR_DF_PRIMARIES_BT709, + KHR_DF_SAMPLE_DATATYPE_FLOAT, + KHR_DF_SAMPLE_DATATYPE_LINEAR, + KHR_DF_SAMPLE_DATATYPE_SIGNED, + KHR_DF_TRANSFER_LINEAR, + KHR_DF_TRANSFER_SRGB, + VK_FORMAT_R16_SFLOAT, + VK_FORMAT_R16G16_SFLOAT, + VK_FORMAT_R16G16B16A16_SFLOAT, + VK_FORMAT_R32_SFLOAT, + VK_FORMAT_R32G32_SFLOAT, + VK_FORMAT_R32G32B32A32_SFLOAT, + VK_FORMAT_R8_SRGB, + VK_FORMAT_R8_UNORM, + VK_FORMAT_R8G8_SRGB, + VK_FORMAT_R8G8_UNORM, + VK_FORMAT_R8G8B8A8_SRGB, + VK_FORMAT_R8G8B8A8_UNORM, +} from '../libs/ktx-parse.module.js'; + +const VK_FORMAT_MAP = { + + [ RGBAFormat ]: { + [ FloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R32G32B32A32_SFLOAT, + }, + [ HalfFloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R16G16B16A16_SFLOAT, + }, + [ UnsignedByteType ]: { + [ LinearEncoding ]: VK_FORMAT_R8G8B8A8_UNORM, + [ sRGBEncoding ]: VK_FORMAT_R8G8B8A8_SRGB, + }, + }, + + [ RGFormat ]: { + [ FloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R32G32_SFLOAT, + }, + [ HalfFloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R16G16_SFLOAT, + }, + [ UnsignedByteType ]: { + [ LinearEncoding ]: VK_FORMAT_R8G8_UNORM, + [ sRGBEncoding ]: VK_FORMAT_R8G8_SRGB, + }, + }, + + [ RedFormat ]: { + [ FloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R32_SFLOAT, + }, + [ HalfFloatType ]: { + [ LinearEncoding ]: VK_FORMAT_R16_SFLOAT, + }, + [ UnsignedByteType ]: { + [ LinearEncoding ]: VK_FORMAT_R8_SRGB, + [ sRGBEncoding ]: VK_FORMAT_R8_UNORM, + }, + }, + +}; + +const KHR_DF_CHANNEL_MAP = { + + 0: KHR_DF_CHANNEL_RGBSDA_RED, + 1: KHR_DF_CHANNEL_RGBSDA_GREEN, + 2: KHR_DF_CHANNEL_RGBSDA_BLUE, + 3: KHR_DF_CHANNEL_RGBSDA_ALPHA, + +}; + +const ERROR_INPUT = 'THREE.KTX2Exporter: Supported inputs are DataTexture, Data3DTexture, or WebGLRenderer and WebGLRenderTarget.'; +const ERROR_FORMAT = 'THREE.KTX2Exporter: Supported formats are RGBAFormat, RGFormat, or RedFormat.'; +const ERROR_TYPE = 'THREE.KTX2Exporter: Supported types are FloatType, HalfFloatType, or UnsignedByteType."'; +const ERROR_ENCODING = 'THREE.KTX2Exporter: Supported encodings are sRGB (UnsignedByteType only) or Linear.'; + +export class KTX2Exporter { + + parse( arg1, arg2 ) { + + let texture; + + if ( arg1.isDataTexture || arg1.isData3DTexture ) { + + texture = arg1; + + } else if ( arg1.isWebGLRenderer && arg2.isWebGLRenderTarget ) { + + texture = toDataTexture( arg1, arg2 ); + + } else { + + throw new Error( ERROR_INPUT ); + + } + + if ( VK_FORMAT_MAP[ texture.format ] === undefined ) { + + throw new Error( ERROR_FORMAT ); + + } + + if ( VK_FORMAT_MAP[ texture.format ][ texture.type ] === undefined ) { + + throw new Error( ERROR_TYPE ); + + } + + if ( VK_FORMAT_MAP[ texture.format ][ texture.type ][ texture.encoding ] === undefined ) { + + throw new Error( ERROR_ENCODING ); + + } + + // + + const array = texture.image.data; + const channelCount = getChannelCount( texture ); + const container = new KTX2Container(); + + container.vkFormat = VK_FORMAT_MAP[ texture.format ][ texture.type ][ texture.encoding ]; + container.typeSize = array.BYTES_PER_ELEMENT; + container.pixelWidth = texture.image.width; + container.pixelHeight = texture.image.height; + + if ( texture.isData3DTexture ) { + + container.pixelDepth = texture.image.depth; + + } + + // + + const basicDesc = container.dataFormatDescriptor[ 0 ]; + + // TODO: After `texture.encoding` is replaced, distinguish between + // non-color data (unspecified model and primaries) and sRGB or Linear-sRGB colors. + basicDesc.colorModel = KHR_DF_MODEL_RGBSDA; + basicDesc.colorPrimaries = KHR_DF_PRIMARIES_BT709; + basicDesc.transferFunction = texture.encoding === sRGBEncoding + ? KHR_DF_TRANSFER_SRGB + : KHR_DF_TRANSFER_LINEAR; + + basicDesc.texelBlockDimension = [ 0, 0, 0, 0 ]; + + basicDesc.bytesPlane = [ + + container.typeSize * channelCount, 0, 0, 0, 0, 0, 0, 0, + + ]; + + for ( let i = 0; i < channelCount; ++ i ) { + + let channelType = KHR_DF_CHANNEL_MAP[ i ]; + + if ( texture.encoding === LinearEncoding ) { + + channelType |= KHR_DF_SAMPLE_DATATYPE_LINEAR; + + } + + if ( texture.type === FloatType || texture.type === HalfFloatType ) { + + channelType |= KHR_DF_SAMPLE_DATATYPE_FLOAT; + channelType |= KHR_DF_SAMPLE_DATATYPE_SIGNED; + + } + + basicDesc.samples.push( { + + channelType: channelType, + bitOffset: i * array.BYTES_PER_ELEMENT, + bitLength: array.BYTES_PER_ELEMENT * 8 - 1, + samplePosition: [ 0, 0, 0, 0 ], + sampleLower: texture.type === UnsignedByteType ? 0 : - 1, + sampleUpper: texture.type === UnsignedByteType ? 255 : 1, + + } ); + + } + + // + + container.levels = [ { + + levelData: new Uint8Array( array.buffer, array.byteOffset, array.byteLength ), + uncompressedByteLength: array.byteLength, + + } ]; + + // + + container.keyValue[ 'KTXwriter' ] = `three.js ${ REVISION }`; + + // + + return write( container, { keepWriter: true } ); + + } + +} + +function toDataTexture( renderer, rtt ) { + + const channelCount = getChannelCount( rtt.texture ); + + let view; + + if ( rtt.texture.type === FloatType ) { + + view = new Float32Array( rtt.width * rtt.height * channelCount ); + + } else if ( rtt.texture.type === HalfFloatType ) { + + view = new Uint16Array( rtt.width * rtt.height * channelCount ); + + } else if ( rtt.texture.type === UnsignedByteType ) { + + view = new Uint8Array( rtt.width * rtt.height * channelCount ); + + } else { + + throw new Error( ERROR_TYPE ); + + } + + renderer.readRenderTargetPixels( rtt, 0, 0, rtt.width, rtt.height, view ); + + return new DataTexture( view, rtt.width, rtt.height, rtt.texture.format, rtt.texture.type ); + +} + +function getChannelCount( texture ) { + + switch ( texture.format ) { + + case RGBAFormat: + + return 4; + + case RGFormat: + case RGIntegerFormat: + + return 2; + + case RedFormat: + case RedIntegerFormat: + + return 1; + + default: + + throw new Error( ERROR_FORMAT ); + + } + +} diff --git a/renderer/jsm/exporters/MMDExporter.js b/renderer/jsm/exporters/MMDExporter.js new file mode 100644 index 0000000..bcef712 --- /dev/null +++ b/renderer/jsm/exporters/MMDExporter.js @@ -0,0 +1,217 @@ +import { + Matrix4, + Quaternion, + Vector3 +} from 'three'; +import { MMDParser } from '../libs/mmdparser.module.js'; + +/** + * Dependencies + * - mmd-parser https://github.com/takahirox/mmd-parser + */ + +class MMDExporter { + + /* TODO: implement + // mesh -> pmd + this.parsePmd = function ( object ) { + + }; + */ + + /* TODO: implement + // mesh -> pmx + this.parsePmx = function ( object ) { + + }; + */ + + /* TODO: implement + // animation + skeleton -> vmd + this.parseVmd = function ( object ) { + + }; + */ + + /* + * skeleton -> vpd + * Returns Shift_JIS encoded Uint8Array. Otherwise return strings. + */ + parseVpd( skin, outputShiftJis, useOriginalBones ) { + + if ( skin.isSkinnedMesh !== true ) { + + console.warn( 'THREE.MMDExporter: parseVpd() requires SkinnedMesh instance.' ); + return null; + + } + + function toStringsFromNumber( num ) { + + if ( Math.abs( num ) < 1e-6 ) num = 0; + + let a = num.toString(); + + if ( a.indexOf( '.' ) === - 1 ) { + + a += '.'; + + } + + a += '000000'; + + const index = a.indexOf( '.' ); + + const d = a.slice( 0, index ); + const p = a.slice( index + 1, index + 7 ); + + return d + '.' + p; + + } + + function toStringsFromArray( array ) { + + const a = []; + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + a.push( toStringsFromNumber( array[ i ] ) ); + + } + + return a.join( ',' ); + + } + + skin.updateMatrixWorld( true ); + + const bones = skin.skeleton.bones; + const bones2 = getBindBones( skin ); + + const position = new Vector3(); + const quaternion = new Quaternion(); + const quaternion2 = new Quaternion(); + const matrix = new Matrix4(); + + const array = []; + array.push( 'Vocaloid Pose Data file' ); + array.push( '' ); + array.push( ( skin.name !== '' ? skin.name.replace( /\s/g, '_' ) : 'skin' ) + '.osm;' ); + array.push( bones.length + ';' ); + array.push( '' ); + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + const bone = bones[ i ]; + const bone2 = bones2[ i ]; + + /* + * use the bone matrix saved before solving IK. + * see CCDIKSolver for the detail. + */ + if ( useOriginalBones === true && + bone.userData.ik !== undefined && + bone.userData.ik.originalMatrix !== undefined ) { + + matrix.fromArray( bone.userData.ik.originalMatrix ); + + } else { + + matrix.copy( bone.matrix ); + + } + + position.setFromMatrixPosition( matrix ); + quaternion.setFromRotationMatrix( matrix ); + + const pArray = position.sub( bone2.position ).toArray(); + const qArray = quaternion2.copy( bone2.quaternion ).conjugate().multiply( quaternion ).toArray(); + + // right to left + pArray[ 2 ] = - pArray[ 2 ]; + qArray[ 0 ] = - qArray[ 0 ]; + qArray[ 1 ] = - qArray[ 1 ]; + + array.push( 'Bone' + i + '{' + bone.name ); + array.push( ' ' + toStringsFromArray( pArray ) + ';' ); + array.push( ' ' + toStringsFromArray( qArray ) + ';' ); + array.push( '}' ); + array.push( '' ); + + } + + array.push( '' ); + + const lines = array.join( '\n' ); + + return ( outputShiftJis === true ) ? unicodeToShiftjis( lines ) : lines; + + } + +} + +// Unicode to Shift_JIS table +let u2sTable; + +function unicodeToShiftjis( str ) { + + if ( u2sTable === undefined ) { + + const encoder = new MMDParser.CharsetEncoder(); + const table = encoder.s2uTable; + u2sTable = {}; + + const keys = Object.keys( table ); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + let key = keys[ i ]; + + const value = table[ key ]; + key = parseInt( key ); + + u2sTable[ value ] = key; + + } + + } + + const array = []; + + for ( let i = 0, il = str.length; i < il; i ++ ) { + + const code = str.charCodeAt( i ); + + const value = u2sTable[ code ]; + + if ( value === undefined ) { + + throw new Error( 'cannot convert charcode 0x' + code.toString( 16 ) ); + + } else if ( value > 0xff ) { + + array.push( ( value >> 8 ) & 0xff ); + array.push( value & 0xff ); + + } else { + + array.push( value & 0xff ); + + } + + } + + return new Uint8Array( array ); + +} + +function getBindBones( skin ) { + + // any more efficient ways? + const poseSkin = skin.clone(); + poseSkin.pose(); + return poseSkin.skeleton.bones; + +} + +export { MMDExporter }; diff --git a/renderer/jsm/exporters/OBJExporter.js b/renderer/jsm/exporters/OBJExporter.js new file mode 100644 index 0000000..63a483e --- /dev/null +++ b/renderer/jsm/exporters/OBJExporter.js @@ -0,0 +1,284 @@ +import { + Color, + Matrix3, + Vector2, + Vector3 +} from 'three'; + +class OBJExporter { + + parse( object ) { + + let output = ''; + + let indexVertex = 0; + let indexVertexUvs = 0; + let indexNormals = 0; + + const vertex = new Vector3(); + const color = new Color(); + const normal = new Vector3(); + const uv = new Vector2(); + + const face = []; + + function parseMesh( mesh ) { + + let nbVertex = 0; + let nbNormals = 0; + let nbVertexUvs = 0; + + const geometry = mesh.geometry; + + const normalMatrixWorld = new Matrix3(); + + // shortcuts + const vertices = geometry.getAttribute( 'position' ); + const normals = geometry.getAttribute( 'normal' ); + const uvs = geometry.getAttribute( 'uv' ); + const indices = geometry.getIndex(); + + // name of the mesh object + output += 'o ' + mesh.name + '\n'; + + // name of the mesh material + if ( mesh.material && mesh.material.name ) { + + output += 'usemtl ' + mesh.material.name + '\n'; + + } + + // vertices + + if ( vertices !== undefined ) { + + for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) { + + vertex.fromBufferAttribute( vertices, i ); + + // transform the vertex to world space + vertex.applyMatrix4( mesh.matrixWorld ); + + // transform the vertex to export format + output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n'; + + } + + } + + // uvs + + if ( uvs !== undefined ) { + + for ( let i = 0, l = uvs.count; i < l; i ++, nbVertexUvs ++ ) { + + uv.fromBufferAttribute( uvs, i ); + + // transform the uv to export format + output += 'vt ' + uv.x + ' ' + uv.y + '\n'; + + } + + } + + // normals + + if ( normals !== undefined ) { + + normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); + + for ( let i = 0, l = normals.count; i < l; i ++, nbNormals ++ ) { + + normal.fromBufferAttribute( normals, i ); + + // transform the normal to world space + normal.applyMatrix3( normalMatrixWorld ).normalize(); + + // transform the normal to export format + output += 'vn ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n'; + + } + + } + + // faces + + if ( indices !== null ) { + + for ( let i = 0, l = indices.count; i < l; i += 3 ) { + + for ( let m = 0; m < 3; m ++ ) { + + const j = indices.getX( i + m ) + 1; + + face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' ); + + } + + // transform the face to export format + output += 'f ' + face.join( ' ' ) + '\n'; + + } + + } else { + + for ( let i = 0, l = vertices.count; i < l; i += 3 ) { + + for ( let m = 0; m < 3; m ++ ) { + + const j = i + m + 1; + + face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' ); + + } + + // transform the face to export format + output += 'f ' + face.join( ' ' ) + '\n'; + + } + + } + + // update index + indexVertex += nbVertex; + indexVertexUvs += nbVertexUvs; + indexNormals += nbNormals; + + } + + function parseLine( line ) { + + let nbVertex = 0; + + const geometry = line.geometry; + const type = line.type; + + // shortcuts + const vertices = geometry.getAttribute( 'position' ); + + // name of the line object + output += 'o ' + line.name + '\n'; + + if ( vertices !== undefined ) { + + for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) { + + vertex.fromBufferAttribute( vertices, i ); + + // transform the vertex to world space + vertex.applyMatrix4( line.matrixWorld ); + + // transform the vertex to export format + output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n'; + + } + + } + + if ( type === 'Line' ) { + + output += 'l '; + + for ( let j = 1, l = vertices.count; j <= l; j ++ ) { + + output += ( indexVertex + j ) + ' '; + + } + + output += '\n'; + + } + + if ( type === 'LineSegments' ) { + + for ( let j = 1, k = j + 1, l = vertices.count; j < l; j += 2, k = j + 1 ) { + + output += 'l ' + ( indexVertex + j ) + ' ' + ( indexVertex + k ) + '\n'; + + } + + } + + // update index + indexVertex += nbVertex; + + } + + function parsePoints( points ) { + + let nbVertex = 0; + + const geometry = points.geometry; + + const vertices = geometry.getAttribute( 'position' ); + const colors = geometry.getAttribute( 'color' ); + + output += 'o ' + points.name + '\n'; + + if ( vertices !== undefined ) { + + for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) { + + vertex.fromBufferAttribute( vertices, i ); + vertex.applyMatrix4( points.matrixWorld ); + + output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z; + + if ( colors !== undefined ) { + + color.fromBufferAttribute( colors, i ).convertLinearToSRGB(); + + output += ' ' + color.r + ' ' + color.g + ' ' + color.b; + + } + + output += '\n'; + + } + + output += 'p '; + + for ( let j = 1, l = vertices.count; j <= l; j ++ ) { + + output += ( indexVertex + j ) + ' '; + + } + + output += '\n'; + + } + + // update index + indexVertex += nbVertex; + + } + + object.traverse( function ( child ) { + + if ( child.isMesh === true ) { + + parseMesh( child ); + + } + + if ( child.isLine === true ) { + + parseLine( child ); + + } + + if ( child.isPoints === true ) { + + parsePoints( child ); + + } + + } ); + + return output; + + } + +} + +export { OBJExporter }; diff --git a/renderer/jsm/exporters/PLYExporter.js b/renderer/jsm/exporters/PLYExporter.js new file mode 100644 index 0000000..2e46a8c --- /dev/null +++ b/renderer/jsm/exporters/PLYExporter.js @@ -0,0 +1,528 @@ +import { + Matrix3, + Vector3, + Color +} from 'three'; + +/** + * https://github.com/gkjohnson/ply-exporter-js + * + * Usage: + * const exporter = new PLYExporter(); + * + * // second argument is a list of options + * exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ], littleEndian: true }); + * + * Format Definition: + * http://paulbourke.net/dataformats/ply/ + */ + +class PLYExporter { + + parse( object, onDone, options = {} ) { + + // Iterate over the valid meshes in the object + function traverseMeshes( cb ) { + + object.traverse( function ( child ) { + + if ( child.isMesh === true || child.isPoints ) { + + const mesh = child; + const geometry = mesh.geometry; + + if ( geometry.hasAttribute( 'position' ) === true ) { + + cb( mesh, geometry ); + + } + + } + + } ); + + } + + // Default options + const defaultOptions = { + binary: false, + excludeAttributes: [], // normal, uv, color, index + littleEndian: false + }; + + options = Object.assign( defaultOptions, options ); + + const excludeAttributes = options.excludeAttributes; + let includeIndices = true; + let includeNormals = false; + let includeColors = false; + let includeUVs = false; + + // count the vertices, check which properties are used, + // and cache the BufferGeometry + let vertexCount = 0; + let faceCount = 0; + + object.traverse( function ( child ) { + + if ( child.isMesh === true ) { + + const mesh = child; + const geometry = mesh.geometry; + + const vertices = geometry.getAttribute( 'position' ); + const normals = geometry.getAttribute( 'normal' ); + const uvs = geometry.getAttribute( 'uv' ); + const colors = geometry.getAttribute( 'color' ); + const indices = geometry.getIndex(); + + if ( vertices === undefined ) { + + return; + + } + + vertexCount += vertices.count; + faceCount += indices ? indices.count / 3 : vertices.count / 3; + + if ( normals !== undefined ) includeNormals = true; + + if ( uvs !== undefined ) includeUVs = true; + + if ( colors !== undefined ) includeColors = true; + + } else if ( child.isPoints ) { + + const mesh = child; + const geometry = mesh.geometry; + + const vertices = geometry.getAttribute( 'position' ); + const normals = geometry.getAttribute( 'normal' ); + const colors = geometry.getAttribute( 'color' ); + + vertexCount += vertices.count; + + if ( normals !== undefined ) includeNormals = true; + + if ( colors !== undefined ) includeColors = true; + + includeIndices = false; + + } + + } ); + + const tempColor = new Color(); + includeIndices = includeIndices && excludeAttributes.indexOf( 'index' ) === - 1; + includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1; + includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1; + includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1; + + + if ( includeIndices && faceCount !== Math.floor( faceCount ) ) { + + // point cloud meshes will not have an index array and may not have a + // number of vertices that is divisble by 3 (and therefore representable + // as triangles) + console.error( + + 'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' + + 'number of indices is not divisible by 3.' + + ); + + return null; + + } + + const indexByteCount = 4; + + let header = + 'ply\n' + + `format ${ options.binary ? ( options.littleEndian ? 'binary_little_endian' : 'binary_big_endian' ) : 'ascii' } 1.0\n` + + `element vertex ${vertexCount}\n` + + + // position + 'property float x\n' + + 'property float y\n' + + 'property float z\n'; + + if ( includeNormals === true ) { + + // normal + header += + 'property float nx\n' + + 'property float ny\n' + + 'property float nz\n'; + + } + + if ( includeUVs === true ) { + + // uvs + header += + 'property float s\n' + + 'property float t\n'; + + } + + if ( includeColors === true ) { + + // colors + header += + 'property uchar red\n' + + 'property uchar green\n' + + 'property uchar blue\n'; + + } + + if ( includeIndices === true ) { + + // faces + header += + `element face ${faceCount}\n` + + 'property list uchar int vertex_index\n'; + + } + + header += 'end_header\n'; + + + // Generate attribute data + const vertex = new Vector3(); + const normalMatrixWorld = new Matrix3(); + let result = null; + + if ( options.binary === true ) { + + // Binary File Generation + const headerBin = new TextEncoder().encode( header ); + + // 3 position values at 4 bytes + // 3 normal values at 4 bytes + // 3 color channels with 1 byte + // 2 uv values at 4 bytes + const vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) ); + + // 1 byte shape desciptor + // 3 vertex indices at ${indexByteCount} bytes + const faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0; + const output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) ); + new Uint8Array( output.buffer ).set( headerBin, 0 ); + + + let vOffset = headerBin.length; + let fOffset = headerBin.length + vertexListLength; + let writtenVertices = 0; + traverseMeshes( function ( mesh, geometry ) { + + const vertices = geometry.getAttribute( 'position' ); + const normals = geometry.getAttribute( 'normal' ); + const uvs = geometry.getAttribute( 'uv' ); + const colors = geometry.getAttribute( 'color' ); + const indices = geometry.getIndex(); + + normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); + + for ( let i = 0, l = vertices.count; i < l; i ++ ) { + + vertex.fromBufferAttribute( vertices, i ); + + vertex.applyMatrix4( mesh.matrixWorld ); + + + // Position information + output.setFloat32( vOffset, vertex.x, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, vertex.y, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, vertex.z, options.littleEndian ); + vOffset += 4; + + // Normal information + if ( includeNormals === true ) { + + if ( normals != null ) { + + vertex.fromBufferAttribute( normals, i ); + + vertex.applyMatrix3( normalMatrixWorld ).normalize(); + + output.setFloat32( vOffset, vertex.x, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, vertex.y, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, vertex.z, options.littleEndian ); + vOffset += 4; + + } else { + + output.setFloat32( vOffset, 0, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, 0, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, 0, options.littleEndian ); + vOffset += 4; + + } + + } + + // UV information + if ( includeUVs === true ) { + + if ( uvs != null ) { + + output.setFloat32( vOffset, uvs.getX( i ), options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, uvs.getY( i ), options.littleEndian ); + vOffset += 4; + + } else { + + output.setFloat32( vOffset, 0, options.littleEndian ); + vOffset += 4; + + output.setFloat32( vOffset, 0, options.littleEndian ); + vOffset += 4; + + } + + } + + // Color information + if ( includeColors === true ) { + + if ( colors != null ) { + + tempColor + .fromBufferAttribute( colors, i ) + .convertLinearToSRGB(); + + output.setUint8( vOffset, Math.floor( tempColor.r * 255 ) ); + vOffset += 1; + + output.setUint8( vOffset, Math.floor( tempColor.g * 255 ) ); + vOffset += 1; + + output.setUint8( vOffset, Math.floor( tempColor.b * 255 ) ); + vOffset += 1; + + } else { + + output.setUint8( vOffset, 255 ); + vOffset += 1; + + output.setUint8( vOffset, 255 ); + vOffset += 1; + + output.setUint8( vOffset, 255 ); + vOffset += 1; + + } + + } + + } + + if ( includeIndices === true ) { + + // Create the face list + + if ( indices !== null ) { + + for ( let i = 0, l = indices.count; i < l; i += 3 ) { + + output.setUint8( fOffset, 3 ); + fOffset += 1; + + output.setUint32( fOffset, indices.getX( i + 0 ) + writtenVertices, options.littleEndian ); + fOffset += indexByteCount; + + output.setUint32( fOffset, indices.getX( i + 1 ) + writtenVertices, options.littleEndian ); + fOffset += indexByteCount; + + output.setUint32( fOffset, indices.getX( i + 2 ) + writtenVertices, options.littleEndian ); + fOffset += indexByteCount; + + } + + } else { + + for ( let i = 0, l = vertices.count; i < l; i += 3 ) { + + output.setUint8( fOffset, 3 ); + fOffset += 1; + + output.setUint32( fOffset, writtenVertices + i, options.littleEndian ); + fOffset += indexByteCount; + + output.setUint32( fOffset, writtenVertices + i + 1, options.littleEndian ); + fOffset += indexByteCount; + + output.setUint32( fOffset, writtenVertices + i + 2, options.littleEndian ); + fOffset += indexByteCount; + + } + + } + + } + + + // Save the amount of verts we've already written so we can offset + // the face index on the next mesh + writtenVertices += vertices.count; + + } ); + + result = output.buffer; + + } else { + + // Ascii File Generation + // count the number of vertices + let writtenVertices = 0; + let vertexList = ''; + let faceList = ''; + + traverseMeshes( function ( mesh, geometry ) { + + const vertices = geometry.getAttribute( 'position' ); + const normals = geometry.getAttribute( 'normal' ); + const uvs = geometry.getAttribute( 'uv' ); + const colors = geometry.getAttribute( 'color' ); + const indices = geometry.getIndex(); + + normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); + + // form each line + for ( let i = 0, l = vertices.count; i < l; i ++ ) { + + vertex.fromBufferAttribute( vertices, i ); + + vertex.applyMatrix4( mesh.matrixWorld ); + + + // Position information + let line = + vertex.x + ' ' + + vertex.y + ' ' + + vertex.z; + + // Normal information + if ( includeNormals === true ) { + + if ( normals != null ) { + + vertex.fromBufferAttribute( normals, i ); + + vertex.applyMatrix3( normalMatrixWorld ).normalize(); + + line += ' ' + + vertex.x + ' ' + + vertex.y + ' ' + + vertex.z; + + } else { + + line += ' 0 0 0'; + + } + + } + + // UV information + if ( includeUVs === true ) { + + if ( uvs != null ) { + + line += ' ' + + uvs.getX( i ) + ' ' + + uvs.getY( i ); + + } else { + + line += ' 0 0'; + + } + + } + + // Color information + if ( includeColors === true ) { + + if ( colors != null ) { + + tempColor + .fromBufferAttribute( colors, i ) + .convertLinearToSRGB(); + + line += ' ' + + Math.floor( tempColor.r * 255 ) + ' ' + + Math.floor( tempColor.g * 255 ) + ' ' + + Math.floor( tempColor.b * 255 ); + + } else { + + line += ' 255 255 255'; + + } + + } + + vertexList += line + '\n'; + + } + + // Create the face list + if ( includeIndices === true ) { + + if ( indices !== null ) { + + for ( let i = 0, l = indices.count; i < l; i += 3 ) { + + faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`; + faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`; + faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`; + + } + + } else { + + for ( let i = 0, l = vertices.count; i < l; i += 3 ) { + + faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`; + + } + + } + + faceCount += indices ? indices.count / 3 : vertices.count / 3; + + } + + writtenVertices += vertices.count; + + } ); + + result = `${ header }${vertexList}${ includeIndices ? `${faceList}\n` : '\n' }`; + + } + + if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) ); + + return result; + + } + +} + +export { PLYExporter }; diff --git a/renderer/jsm/exporters/STLExporter.js b/renderer/jsm/exporters/STLExporter.js new file mode 100644 index 0000000..4270486 --- /dev/null +++ b/renderer/jsm/exporters/STLExporter.js @@ -0,0 +1,199 @@ +import { Vector3 } from 'three'; + +/** + * Usage: + * const exporter = new STLExporter(); + * + * // second argument is a list of options + * const data = exporter.parse( mesh, { binary: true } ); + * + */ + +class STLExporter { + + parse( scene, options = {} ) { + + options = Object.assign( { + binary: false + }, options ); + + const binary = options.binary; + + // + + const objects = []; + let triangles = 0; + + scene.traverse( function ( object ) { + + if ( object.isMesh ) { + + const geometry = object.geometry; + + const index = geometry.index; + const positionAttribute = geometry.getAttribute( 'position' ); + + triangles += ( index !== null ) ? ( index.count / 3 ) : ( positionAttribute.count / 3 ); + + objects.push( { + object3d: object, + geometry: geometry + } ); + + } + + } ); + + let output; + let offset = 80; // skip header + + if ( binary === true ) { + + const bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4; + const arrayBuffer = new ArrayBuffer( bufferLength ); + output = new DataView( arrayBuffer ); + output.setUint32( offset, triangles, true ); offset += 4; + + } else { + + output = ''; + output += 'solid exported\n'; + + } + + const vA = new Vector3(); + const vB = new Vector3(); + const vC = new Vector3(); + const cb = new Vector3(); + const ab = new Vector3(); + const normal = new Vector3(); + + for ( let i = 0, il = objects.length; i < il; i ++ ) { + + const object = objects[ i ].object3d; + const geometry = objects[ i ].geometry; + + const index = geometry.index; + const positionAttribute = geometry.getAttribute( 'position' ); + + if ( index !== null ) { + + // indexed geometry + + for ( let j = 0; j < index.count; j += 3 ) { + + const a = index.getX( j + 0 ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + writeFace( a, b, c, positionAttribute, object ); + + } + + } else { + + // non-indexed geometry + + for ( let j = 0; j < positionAttribute.count; j += 3 ) { + + const a = j + 0; + const b = j + 1; + const c = j + 2; + + writeFace( a, b, c, positionAttribute, object ); + + } + + } + + } + + if ( binary === false ) { + + output += 'endsolid exported\n'; + + } + + return output; + + function writeFace( a, b, c, positionAttribute, object ) { + + vA.fromBufferAttribute( positionAttribute, a ); + vB.fromBufferAttribute( positionAttribute, b ); + vC.fromBufferAttribute( positionAttribute, c ); + + if ( object.isSkinnedMesh === true ) { + + object.boneTransform( a, vA ); + object.boneTransform( b, vB ); + object.boneTransform( c, vC ); + + } + + vA.applyMatrix4( object.matrixWorld ); + vB.applyMatrix4( object.matrixWorld ); + vC.applyMatrix4( object.matrixWorld ); + + writeNormal( vA, vB, vC ); + + writeVertex( vA ); + writeVertex( vB ); + writeVertex( vC ); + + if ( binary === true ) { + + output.setUint16( offset, 0, true ); offset += 2; + + } else { + + output += '\t\tendloop\n'; + output += '\tendfacet\n'; + + } + + } + + function writeNormal( vA, vB, vC ) { + + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ).normalize(); + + normal.copy( cb ).normalize(); + + if ( binary === true ) { + + output.setFloat32( offset, normal.x, true ); offset += 4; + output.setFloat32( offset, normal.y, true ); offset += 4; + output.setFloat32( offset, normal.z, true ); offset += 4; + + } else { + + output += '\tfacet normal ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n'; + output += '\t\touter loop\n'; + + } + + } + + function writeVertex( vertex ) { + + if ( binary === true ) { + + output.setFloat32( offset, vertex.x, true ); offset += 4; + output.setFloat32( offset, vertex.y, true ); offset += 4; + output.setFloat32( offset, vertex.z, true ); offset += 4; + + } else { + + output += '\t\t\tvertex ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n'; + + } + + } + + } + +} + +export { STLExporter }; diff --git a/renderer/jsm/exporters/USDZExporter.js b/renderer/jsm/exporters/USDZExporter.js new file mode 100644 index 0000000..a8fe3d8 --- /dev/null +++ b/renderer/jsm/exporters/USDZExporter.js @@ -0,0 +1,661 @@ +import { + DoubleSide +} from 'three'; + +import * as fflate from '../libs/fflate.module.js'; + +class USDZExporter { + + async parse( scene, options = {} ) { + + options = Object.assign( { + ar: { + anchoring: { type: 'plane' }, + planeAnchoring: { alignment: 'horizontal' } + } + }, options ); + + const files = {}; + const modelFileName = 'model.usda'; + + // model file should be first in USDZ archive so we init it here + files[ modelFileName ] = null; + + let output = buildHeader(); + + output += buildSceneStart( options ); + + const materials = {}; + const textures = {}; + + scene.traverseVisible( ( object ) => { + + if ( object.isMesh ) { + + const geometry = object.geometry; + const material = object.material; + + if ( material.isMeshStandardMaterial ) { + + const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usd'; + + if ( ! ( geometryFileName in files ) ) { + + const meshObject = buildMeshObject( geometry ); + files[ geometryFileName ] = buildUSDFileAsString( meshObject ); + + } + + if ( ! ( material.uuid in materials ) ) { + + materials[ material.uuid ] = material; + + } + + output += buildXform( object, geometry, material ); + + } else { + + console.warn( 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)', object ); + + } + + } else if ( object.isCamera ) { + + output += buildCamera( object ); + + } + + } ); + + + output += buildSceneEnd(); + + output += buildMaterials( materials, textures ); + + files[ modelFileName ] = fflate.strToU8( output ); + output = null; + + for ( const id in textures ) { + + const texture = textures[ id ]; + const color = id.split( '_' )[ 1 ]; + const isRGBA = texture.format === 1023; + + const canvas = imageToCanvas( texture.image, color ); + const blob = await new Promise( resolve => canvas.toBlob( resolve, isRGBA ? 'image/png' : 'image/jpeg', 1 ) ); + + files[ `textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }` ] = new Uint8Array( await blob.arrayBuffer() ); + + } + + // 64 byte alignment + // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109 + + let offset = 0; + + for ( const filename in files ) { + + const file = files[ filename ]; + const headerSize = 34 + filename.length; + + offset += headerSize; + + const offsetMod64 = offset & 63; + + if ( offsetMod64 !== 4 ) { + + const padLength = 64 - offsetMod64; + const padding = new Uint8Array( padLength ); + + files[ filename ] = [ file, { extra: { 12345: padding } } ]; + + } + + offset = file.length; + + } + + return fflate.zipSync( files, { level: 0 } ); + + } + +} + +function imageToCanvas( image, color ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const scale = 1024 / Math.max( image.width, image.height ); + + const canvas = document.createElement( 'canvas' ); + canvas.width = image.width * Math.min( 1, scale ); + canvas.height = image.height * Math.min( 1, scale ); + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, canvas.width, canvas.height ); + + if ( color !== undefined ) { + + const hex = parseInt( color, 16 ); + + const r = ( hex >> 16 & 255 ) / 255; + const g = ( hex >> 8 & 255 ) / 255; + const b = ( hex & 255 ) / 255; + + const imagedata = context.getImageData( 0, 0, canvas.width, canvas.height ); + const data = imagedata.data; + + for ( let i = 0; i < data.length; i += 4 ) { + + data[ i + 0 ] = data[ i + 0 ] * r; + data[ i + 1 ] = data[ i + 1 ] * g; + data[ i + 2 ] = data[ i + 2 ] * b; + + } + + context.putImageData( imagedata, 0, 0 ); + + } + + return canvas; + + } else { + + throw new Error( 'THREE.USDZExporter: No valid image data found. Unable to process texture.' ); + + } + +} + +// + +const PRECISION = 7; + +function buildHeader() { + + return `#usda 1.0 +( + customLayerData = { + string creator = "Three.js USDZExporter" + } + metersPerUnit = 1 + upAxis = "Y" +) + +`; + +} + +function buildSceneStart( options ) { + + return `def Xform "Root" +{ + def Scope "Scenes" ( + kind = "sceneLibrary" + ) + { + def Xform "Scene" ( + customData = { + bool preliminary_collidesWithEnvironment = 0 + string sceneName = "Scene" + } + sceneName = "Scene" + ) + { + token preliminary:anchoring:type = "${options.ar.anchoring.type}" + token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}" + +`; + +} + +function buildSceneEnd() { + + return ` + } + } +} + +`; + +} + +function buildUSDFileAsString( dataToInsert ) { + + let output = buildHeader(); + output += dataToInsert; + return fflate.strToU8( output ); + +} + +// Xform + +function buildXform( object, geometry, material ) { + + const name = 'Object_' + object.id; + const transform = buildMatrix( object.matrixWorld ); + + if ( object.matrixWorld.determinant() < 0 ) { + + console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object ); + + } + + return `def Xform "${ name }" ( + prepend references = @./geometries/Geometry_${ geometry.id }.usd@ +) +{ + matrix4d xformOp:transform = ${ transform } + uniform token[] xformOpOrder = ["xformOp:transform"] + + rel material:binding = +} + +`; + +} + +function buildMatrix( matrix ) { + + const array = matrix.elements; + + return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`; + +} + +function buildMatrixRow( array, offset ) { + + return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`; + +} + +// Mesh + +function buildMeshObject( geometry ) { + + const mesh = buildMesh( geometry ); + return ` +def "Geometry" +{ + ${mesh} +} +`; + +} + +function buildMesh( geometry ) { + + const name = 'Geometry'; + const attributes = geometry.attributes; + const count = attributes.position.count; + + return ` + def Mesh "${ name }" + { + int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }] + int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }] + normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] ( + interpolation = "vertex" + ) + point3f[] points = [${ buildVector3Array( attributes.position, count )}] + float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] ( + interpolation = "vertex" + ) + uniform token subdivisionScheme = "none" + } +`; + +} + +function buildMeshVertexCount( geometry ) { + + const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count; + + return Array( count / 3 ).fill( 3 ).join( ', ' ); + +} + +function buildMeshVertexIndices( geometry ) { + + const index = geometry.index; + const array = []; + + if ( index !== null ) { + + for ( let i = 0; i < index.count; i ++ ) { + + array.push( index.getX( i ) ); + + } + + } else { + + const length = geometry.attributes.position.count; + + for ( let i = 0; i < length; i ++ ) { + + array.push( i ); + + } + + } + + return array.join( ', ' ); + +} + +function buildVector3Array( attribute, count ) { + + if ( attribute === undefined ) { + + console.warn( 'USDZExporter: Normals missing.' ); + return Array( count ).fill( '(0, 0, 0)' ).join( ', ' ); + + } + + const array = []; + + for ( let i = 0; i < attribute.count; i ++ ) { + + const x = attribute.getX( i ); + const y = attribute.getY( i ); + const z = attribute.getZ( i ); + + array.push( `(${ x.toPrecision( PRECISION ) }, ${ y.toPrecision( PRECISION ) }, ${ z.toPrecision( PRECISION ) })` ); + + } + + return array.join( ', ' ); + +} + +function buildVector2Array( attribute, count ) { + + if ( attribute === undefined ) { + + console.warn( 'USDZExporter: UVs missing.' ); + return Array( count ).fill( '(0, 0)' ).join( ', ' ); + + } + + const array = []; + + for ( let i = 0; i < attribute.count; i ++ ) { + + const x = attribute.getX( i ); + const y = attribute.getY( i ); + + array.push( `(${ x.toPrecision( PRECISION ) }, ${ 1 - y.toPrecision( PRECISION ) })` ); + + } + + return array.join( ', ' ); + +} + +// Materials + +function buildMaterials( materials, textures ) { + + const array = []; + + for ( const uuid in materials ) { + + const material = materials[ uuid ]; + + array.push( buildMaterial( material, textures ) ); + + } + + return `def "Materials" +{ +${ array.join( '' ) } +} + +`; + +} + +function buildMaterial( material, textures ) { + + // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html + + const pad = ' '; + const inputs = []; + const samplers = []; + + function buildTexture( texture, mapType, color ) { + + const id = texture.id + ( color ? '_' + color.getHexString() : '' ); + const isRGBA = texture.format === 1023; + + textures[ id ] = texture; + + return ` + def Shader "Transform2d_${ mapType }" ( + sdrMetadata = { + string role = "math" + } + ) + { + uniform token info:id = "UsdTransform2d" + float2 inputs:in.connect = + float2 inputs:scale = ${ buildVector2( texture.repeat ) } + float2 inputs:translation = ${ buildVector2( texture.offset ) } + float2 outputs:result + } + + def Shader "Texture_${ texture.id }_${ mapType }" + { + uniform token info:id = "UsdUVTexture" + asset inputs:file = @textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }@ + float2 inputs:st.connect = + token inputs:wrapS = "repeat" + token inputs:wrapT = "repeat" + float outputs:r + float outputs:g + float outputs:b + float3 outputs:rgb + ${ material.transparent || material.alphaTest > 0.0 ? 'float outputs:a' : '' } + }`; + + } + + + if ( material.side === DoubleSide ) { + + console.warn( 'THREE.USDZExporter: USDZ does not support double sided materials', material ); + + } + + if ( material.map !== null ) { + + inputs.push( `${ pad }color3f inputs:diffuseColor.connect = ` ); + + if ( material.transparent ) { + + inputs.push( `${ pad }float inputs:opacity.connect = ` ); + + } else if ( material.alphaTest > 0.0 ) { + + inputs.push( `${ pad }float inputs:opacity.connect = ` ); + inputs.push( `${ pad }float inputs:opacityThreshold = ${material.alphaTest}` ); + + } + + samplers.push( buildTexture( material.map, 'diffuse', material.color ) ); + + } else { + + inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` ); + + } + + if ( material.emissiveMap !== null ) { + + inputs.push( `${ pad }color3f inputs:emissiveColor.connect = ` ); + + samplers.push( buildTexture( material.emissiveMap, 'emissive' ) ); + + } else if ( material.emissive.getHex() > 0 ) { + + inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` ); + + } + + if ( material.normalMap !== null ) { + + inputs.push( `${ pad }normal3f inputs:normal.connect = ` ); + + samplers.push( buildTexture( material.normalMap, 'normal' ) ); + + } + + if ( material.aoMap !== null ) { + + inputs.push( `${ pad }float inputs:occlusion.connect = ` ); + + samplers.push( buildTexture( material.aoMap, 'occlusion' ) ); + + } + + if ( material.roughnessMap !== null && material.roughness === 1 ) { + + inputs.push( `${ pad }float inputs:roughness.connect = ` ); + + samplers.push( buildTexture( material.roughnessMap, 'roughness' ) ); + + } else { + + inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` ); + + } + + if ( material.metalnessMap !== null && material.metalness === 1 ) { + + inputs.push( `${ pad }float inputs:metallic.connect = ` ); + + samplers.push( buildTexture( material.metalnessMap, 'metallic' ) ); + + } else { + + inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` ); + + } + + if ( material.alphaMap !== null ) { + + inputs.push( `${pad}float inputs:opacity.connect = ` ); + inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` ); + + samplers.push( buildTexture( material.alphaMap, 'opacity' ) ); + + } else { + + inputs.push( `${pad}float inputs:opacity = ${material.opacity}` ); + + } + + if ( material.isMeshPhysicalMaterial ) { + + inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` ); + inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` ); + inputs.push( `${ pad }float inputs:ior = ${ material.ior }` ); + + } + + return ` + def Material "Material_${ material.id }" + { + def Shader "PreviewSurface" + { + uniform token info:id = "UsdPreviewSurface" +${ inputs.join( '\n' ) } + int inputs:useSpecularWorkflow = 0 + token outputs:surface + } + + token outputs:surface.connect = + token inputs:frame:stPrimvarName = "st" + + def Shader "uvReader_st" + { + uniform token info:id = "UsdPrimvarReader_float2" + token inputs:varname.connect = + float2 inputs:fallback = (0.0, 0.0) + float2 outputs:result + } + +${ samplers.join( '\n' ) } + + } +`; + +} + +function buildColor( color ) { + + return `(${ color.r }, ${ color.g }, ${ color.b })`; + +} + +function buildVector2( vector ) { + + return `(${ vector.x }, ${ vector.y })`; + +} + + +function buildCamera( camera ) { + + const name = camera.name ? camera.name : 'Camera_' + camera.id; + + const transform = buildMatrix( camera.matrixWorld ); + + if ( camera.matrixWorld.determinant() < 0 ) { + + console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', camera ); + + } + + if ( camera.isOrthographicCamera ) { + + return `def Camera "${name}" + { + matrix4d xformOp:transform = ${ transform } + uniform token[] xformOpOrder = ["xformOp:transform"] + + float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) }) + float horizontalAperture = ${ ( ( Math.abs( camera.left ) + Math.abs( camera.right ) ) * 10 ).toPrecision( PRECISION ) } + float verticalAperture = ${ ( ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) * 10 ).toPrecision( PRECISION ) } + token projection = "orthographic" + } + + `; + + } else { + + return `def Camera "${name}" + { + matrix4d xformOp:transform = ${ transform } + uniform token[] xformOpOrder = ["xformOp:transform"] + + float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) }) + float focalLength = ${ camera.getFocalLength().toPrecision( PRECISION ) } + float focusDistance = ${ camera.focus.toPrecision( PRECISION ) } + float horizontalAperture = ${ camera.getFilmWidth().toPrecision( PRECISION ) } + token projection = "perspective" + float verticalAperture = ${ camera.getFilmHeight().toPrecision( PRECISION ) } + } + + `; + + } + +} + +export { USDZExporter }; diff --git a/renderer/jsm/geometries/BoxLineGeometry.js b/renderer/jsm/geometries/BoxLineGeometry.js new file mode 100644 index 0000000..8f05833 --- /dev/null +++ b/renderer/jsm/geometries/BoxLineGeometry.js @@ -0,0 +1,69 @@ +import { + BufferGeometry, + Float32BufferAttribute +} from 'three'; + +class BoxLineGeometry extends BufferGeometry { + + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const segmentWidth = width / widthSegments; + const segmentHeight = height / heightSegments; + const segmentDepth = depth / depthSegments; + + const vertices = []; + + let x = - widthHalf; + let y = - heightHalf; + let z = - depthHalf; + + for ( let i = 0; i <= widthSegments; i ++ ) { + + vertices.push( x, - heightHalf, - depthHalf, x, heightHalf, - depthHalf ); + vertices.push( x, heightHalf, - depthHalf, x, heightHalf, depthHalf ); + vertices.push( x, heightHalf, depthHalf, x, - heightHalf, depthHalf ); + vertices.push( x, - heightHalf, depthHalf, x, - heightHalf, - depthHalf ); + + x += segmentWidth; + + } + + for ( let i = 0; i <= heightSegments; i ++ ) { + + vertices.push( - widthHalf, y, - depthHalf, widthHalf, y, - depthHalf ); + vertices.push( widthHalf, y, - depthHalf, widthHalf, y, depthHalf ); + vertices.push( widthHalf, y, depthHalf, - widthHalf, y, depthHalf ); + vertices.push( - widthHalf, y, depthHalf, - widthHalf, y, - depthHalf ); + + y += segmentHeight; + + } + + for ( let i = 0; i <= depthSegments; i ++ ) { + + vertices.push( - widthHalf, - heightHalf, z, - widthHalf, heightHalf, z ); + vertices.push( - widthHalf, heightHalf, z, widthHalf, heightHalf, z ); + vertices.push( widthHalf, heightHalf, z, widthHalf, - heightHalf, z ); + vertices.push( widthHalf, - heightHalf, z, - widthHalf, - heightHalf, z ); + + z += segmentDepth; + + } + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + +} + +export { BoxLineGeometry }; diff --git a/renderer/jsm/geometries/ConvexGeometry.js b/renderer/jsm/geometries/ConvexGeometry.js new file mode 100644 index 0000000..3aa65c5 --- /dev/null +++ b/renderer/jsm/geometries/ConvexGeometry.js @@ -0,0 +1,53 @@ +import { + BufferGeometry, + Float32BufferAttribute +} from 'three'; +import { ConvexHull } from '../math/ConvexHull.js'; + +class ConvexGeometry extends BufferGeometry { + + constructor( points = [] ) { + + super(); + + // buffers + + const vertices = []; + const normals = []; + + const convexHull = new ConvexHull().setFromPoints( points ); + + // generate vertices and normals + + const faces = convexHull.faces; + + for ( let i = 0; i < faces.length; i ++ ) { + + const face = faces[ i ]; + let edge = face.edge; + + // we move along a doubly-connected edge list to access all face points (see HalfEdge docs) + + do { + + const point = edge.head().point; + + vertices.push( point.x, point.y, point.z ); + normals.push( face.normal.x, face.normal.y, face.normal.z ); + + edge = edge.next; + + } while ( edge !== face.edge ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + + } + +} + +export { ConvexGeometry }; diff --git a/renderer/jsm/geometries/DecalGeometry.js b/renderer/jsm/geometries/DecalGeometry.js new file mode 100644 index 0000000..5e712f2 --- /dev/null +++ b/renderer/jsm/geometries/DecalGeometry.js @@ -0,0 +1,356 @@ +import { + BufferGeometry, + Float32BufferAttribute, + Matrix4, + Vector3 +} from 'three'; + +/** + * You can use this geometry to create a decal mesh, that serves different kinds of purposes. + * e.g. adding unique details to models, performing dynamic visual environmental changes or covering seams. + * + * Constructor parameter: + * + * mesh — Any mesh object + * position — Position of the decal projector + * orientation — Orientation of the decal projector + * size — Size of the decal projector + * + * reference: http://blog.wolfire.com/2009/06/how-to-project-decals/ + * + */ + +class DecalGeometry extends BufferGeometry { + + constructor( mesh, position, orientation, size ) { + + super(); + + // buffers + + const vertices = []; + const normals = []; + const uvs = []; + + // helpers + + const plane = new Vector3(); + + // this matrix represents the transformation of the decal projector + + const projectorMatrix = new Matrix4(); + projectorMatrix.makeRotationFromEuler( orientation ); + projectorMatrix.setPosition( position ); + + const projectorMatrixInverse = new Matrix4(); + projectorMatrixInverse.copy( projectorMatrix ).invert(); + + // generate buffers + + generate(); + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generate() { + + let decalVertices = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // handle different geometry types + + const geometry = mesh.geometry; + + const positionAttribute = geometry.attributes.position; + const normalAttribute = geometry.attributes.normal; + + // first, create an array of 'DecalVertex' objects + // three consecutive 'DecalVertex' objects represent a single face + // + // this data structure will be later used to perform the clipping + + if ( geometry.index !== null ) { + + // indexed BufferGeometry + + const index = geometry.index; + + for ( let i = 0; i < index.count; i ++ ) { + + vertex.fromBufferAttribute( positionAttribute, index.getX( i ) ); + normal.fromBufferAttribute( normalAttribute, index.getX( i ) ); + + pushDecalVertex( decalVertices, vertex, normal ); + + } + + } else { + + // non-indexed BufferGeometry + + for ( let i = 0; i < positionAttribute.count; i ++ ) { + + vertex.fromBufferAttribute( positionAttribute, i ); + normal.fromBufferAttribute( normalAttribute, i ); + + pushDecalVertex( decalVertices, vertex, normal ); + + } + + } + + // second, clip the geometry so that it doesn't extend out from the projector + + decalVertices = clipGeometry( decalVertices, plane.set( 1, 0, 0 ) ); + decalVertices = clipGeometry( decalVertices, plane.set( - 1, 0, 0 ) ); + decalVertices = clipGeometry( decalVertices, plane.set( 0, 1, 0 ) ); + decalVertices = clipGeometry( decalVertices, plane.set( 0, - 1, 0 ) ); + decalVertices = clipGeometry( decalVertices, plane.set( 0, 0, 1 ) ); + decalVertices = clipGeometry( decalVertices, plane.set( 0, 0, - 1 ) ); + + // third, generate final vertices, normals and uvs + + for ( let i = 0; i < decalVertices.length; i ++ ) { + + const decalVertex = decalVertices[ i ]; + + // create texture coordinates (we are still in projector space) + + uvs.push( + 0.5 + ( decalVertex.position.x / size.x ), + 0.5 + ( decalVertex.position.y / size.y ) + ); + + // transform the vertex back to world space + + decalVertex.position.applyMatrix4( projectorMatrix ); + + // now create vertex and normal buffer data + + vertices.push( decalVertex.position.x, decalVertex.position.y, decalVertex.position.z ); + normals.push( decalVertex.normal.x, decalVertex.normal.y, decalVertex.normal.z ); + + } + + } + + function pushDecalVertex( decalVertices, vertex, normal ) { + + // transform the vertex to world space, then to projector space + + vertex.applyMatrix4( mesh.matrixWorld ); + vertex.applyMatrix4( projectorMatrixInverse ); + + normal.transformDirection( mesh.matrixWorld ); + + decalVertices.push( new DecalVertex( vertex.clone(), normal.clone() ) ); + + } + + function clipGeometry( inVertices, plane ) { + + const outVertices = []; + + const s = 0.5 * Math.abs( size.dot( plane ) ); + + // a single iteration clips one face, + // which consists of three consecutive 'DecalVertex' objects + + for ( let i = 0; i < inVertices.length; i += 3 ) { + + let total = 0; + let nV1; + let nV2; + let nV3; + let nV4; + + const d1 = inVertices[ i + 0 ].position.dot( plane ) - s; + const d2 = inVertices[ i + 1 ].position.dot( plane ) - s; + const d3 = inVertices[ i + 2 ].position.dot( plane ) - s; + + const v1Out = d1 > 0; + const v2Out = d2 > 0; + const v3Out = d3 > 0; + + // calculate, how many vertices of the face lie outside of the clipping plane + + total = ( v1Out ? 1 : 0 ) + ( v2Out ? 1 : 0 ) + ( v3Out ? 1 : 0 ); + + switch ( total ) { + + case 0: { + + // the entire face lies inside of the plane, no clipping needed + + outVertices.push( inVertices[ i ] ); + outVertices.push( inVertices[ i + 1 ] ); + outVertices.push( inVertices[ i + 2 ] ); + break; + + } + + case 1: { + + // one vertex lies outside of the plane, perform clipping + + if ( v1Out ) { + + nV1 = inVertices[ i + 1 ]; + nV2 = inVertices[ i + 2 ]; + nV3 = clip( inVertices[ i ], nV1, plane, s ); + nV4 = clip( inVertices[ i ], nV2, plane, s ); + + } + + if ( v2Out ) { + + nV1 = inVertices[ i ]; + nV2 = inVertices[ i + 2 ]; + nV3 = clip( inVertices[ i + 1 ], nV1, plane, s ); + nV4 = clip( inVertices[ i + 1 ], nV2, plane, s ); + + outVertices.push( nV3 ); + outVertices.push( nV2.clone() ); + outVertices.push( nV1.clone() ); + + outVertices.push( nV2.clone() ); + outVertices.push( nV3.clone() ); + outVertices.push( nV4 ); + break; + + } + + if ( v3Out ) { + + nV1 = inVertices[ i ]; + nV2 = inVertices[ i + 1 ]; + nV3 = clip( inVertices[ i + 2 ], nV1, plane, s ); + nV4 = clip( inVertices[ i + 2 ], nV2, plane, s ); + + } + + outVertices.push( nV1.clone() ); + outVertices.push( nV2.clone() ); + outVertices.push( nV3 ); + + outVertices.push( nV4 ); + outVertices.push( nV3.clone() ); + outVertices.push( nV2.clone() ); + + break; + + } + + case 2: { + + // two vertices lies outside of the plane, perform clipping + + if ( ! v1Out ) { + + nV1 = inVertices[ i ].clone(); + nV2 = clip( nV1, inVertices[ i + 1 ], plane, s ); + nV3 = clip( nV1, inVertices[ i + 2 ], plane, s ); + outVertices.push( nV1 ); + outVertices.push( nV2 ); + outVertices.push( nV3 ); + + } + + if ( ! v2Out ) { + + nV1 = inVertices[ i + 1 ].clone(); + nV2 = clip( nV1, inVertices[ i + 2 ], plane, s ); + nV3 = clip( nV1, inVertices[ i ], plane, s ); + outVertices.push( nV1 ); + outVertices.push( nV2 ); + outVertices.push( nV3 ); + + } + + if ( ! v3Out ) { + + nV1 = inVertices[ i + 2 ].clone(); + nV2 = clip( nV1, inVertices[ i ], plane, s ); + nV3 = clip( nV1, inVertices[ i + 1 ], plane, s ); + outVertices.push( nV1 ); + outVertices.push( nV2 ); + outVertices.push( nV3 ); + + } + + break; + + } + + case 3: { + + // the entire face lies outside of the plane, so let's discard the corresponding vertices + + break; + + } + + } + + } + + return outVertices; + + } + + function clip( v0, v1, p, s ) { + + const d0 = v0.position.dot( p ) - s; + const d1 = v1.position.dot( p ) - s; + + const s0 = d0 / ( d0 - d1 ); + + const v = new DecalVertex( + new Vector3( + v0.position.x + s0 * ( v1.position.x - v0.position.x ), + v0.position.y + s0 * ( v1.position.y - v0.position.y ), + v0.position.z + s0 * ( v1.position.z - v0.position.z ) + ), + new Vector3( + v0.normal.x + s0 * ( v1.normal.x - v0.normal.x ), + v0.normal.y + s0 * ( v1.normal.y - v0.normal.y ), + v0.normal.z + s0 * ( v1.normal.z - v0.normal.z ) + ) + ); + + // need to clip more values (texture coordinates)? do it this way: + // intersectpoint.value = a.value + s * ( b.value - a.value ); + + return v; + + } + + } + +} + +// helper + +class DecalVertex { + + constructor( position, normal ) { + + this.position = position; + this.normal = normal; + + } + + clone() { + + return new this.constructor( this.position.clone(), this.normal.clone() ); + + } + +} + +export { DecalGeometry, DecalVertex }; diff --git a/renderer/jsm/geometries/LightningStrike.js b/renderer/jsm/geometries/LightningStrike.js new file mode 100644 index 0000000..0d29a41 --- /dev/null +++ b/renderer/jsm/geometries/LightningStrike.js @@ -0,0 +1,1017 @@ +import { + BufferGeometry, + DynamicDrawUsage, + Float32BufferAttribute, + MathUtils, + Uint32BufferAttribute, + Vector3 +} from 'three'; +import { SimplexNoise } from '../math/SimplexNoise.js'; + +/** + * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs. + * + * + * Usage + * + * var myRay = new LightningStrike( paramsObject ); + * var myRayMesh = new THREE.Mesh( myRay, myMaterial ); + * scene.add( myRayMesh ); + * ... + * myRay.update( currentTime ); + * + * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative. + * + * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters. + * + * + * LightningStrike parameters + * + * The paramsObject can contain any of the following parameters. + * + * Legend: + * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters. + * 'Subray': A ramification of the ray. It is not a LightningStrike object. + * 'Segment': A linear segment piece of a subray. + * 'Leaf segment': A ray segment which cannot be smaller. + * + * + * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly: + * + * @param {Vector3} sourceOffset The point where the ray starts. + * + * @param {Vector3} destOffset The point where the ray ends. + * + * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1 + * + * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9 + * + * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7 + * + * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much. + * + * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized. + * + * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1 + * + * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1 + * + * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5 + * + * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2 + * + * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1 + * + * + * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: + * + * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined. + * + * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None. + * + * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None. + * + * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1 + * + * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9 + * + * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4 + * + * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6 + * + * + * These parameters cannot change after lightning creation: + * + * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9 + * + * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays. + * + * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5 + * + * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3 + * + * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6 + * + * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false. + * + * @param {Object} randomGenerator Set here your random number generator which will seed the SimplexNoise and other decisions during ray tree creation. + * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time. + * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable. + * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number. + * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied) + * + * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator) + * + * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info. + * + * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane. + * + * +*/ + +class LightningStrike extends BufferGeometry { + + constructor( rayParameters = {} ) { + + super(); + + this.isLightningStrike = true; + + this.type = 'LightningStrike'; + + // Set parameters, and set undefined parameters to default values + this.init( LightningStrike.copyParameters( rayParameters, rayParameters ) ); + + // Creates and populates the mesh + this.createMesh(); + + } + + static createRandomGenerator() { + + const numSeeds = 2053; + const seeds = []; + + for ( let i = 0; i < numSeeds; i ++ ) { + + seeds.push( Math.random() ); + + } + + const generator = { + + currentSeed: 0, + + random: function () { + + const value = seeds[ generator.currentSeed ]; + + generator.currentSeed = ( generator.currentSeed + 1 ) % numSeeds; + + return value; + + }, + + getSeed: function () { + + return generator.currentSeed / numSeeds; + + }, + + setSeed: function ( seed ) { + + generator.currentSeed = Math.floor( seed * numSeeds ) % numSeeds; + + } + + }; + + return generator; + + } + + static copyParameters( dest = {}, source = {} ) { + + const vecCopy = function ( v ) { + + if ( source === dest ) { + + return v; + + } else { + + return v.clone(); + + } + + }; + + dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy( source.sourceOffset ) : new Vector3( 0, 100, 0 ), + dest.destOffset = source.destOffset !== undefined ? vecCopy( source.destOffset ) : new Vector3( 0, 0, 0 ), + + dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1, + dest.roughness = source.roughness !== undefined ? source.roughness : 0.9, + dest.straightness = source.straightness !== undefined ? source.straightness : 0.7, + + dest.up0 = source.up0 !== undefined ? vecCopy( source.up0 ) : new Vector3( 0, 0, 1 ); + dest.up1 = source.up1 !== undefined ? vecCopy( source.up1 ) : new Vector3( 0, 0, 1 ), + dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1, + dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1, + dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5, + dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2, + dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2, + + // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: + + dest.isEternal = source.isEternal !== undefined ? source.isEternal : ( source.birthTime === undefined || source.deathTime === undefined ), + dest.birthTime = source.birthTime, + dest.deathTime = source.deathTime, + dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1, + dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9, + dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4, + dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6; + + // These parameters cannot change after lightning creation: + + dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9; + dest.isStatic = source.isStatic !== undefined ? source.isStatic : false; + dest.ramification = source.ramification !== undefined ? source.ramification : 5; + dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3; + dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6; + dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false; + dest.randomGenerator = source.randomGenerator, + dest.noiseSeed = source.noiseSeed, + dest.onDecideSubrayCreation = source.onDecideSubrayCreation, + dest.onSubrayCreation = source.onSubrayCreation; + + return dest; + + } + + update( time ) { + + if ( this.isStatic ) return; + + if ( this.rayParameters.isEternal || ( this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime ) ) { + + this.updateMesh( time ); + + if ( time < this.subrays[ 0 ].endPropagationTime ) { + + this.state = LightningStrike.RAY_PROPAGATING; + + } else if ( time > this.subrays[ 0 ].beginVanishingTime ) { + + this.state = LightningStrike.RAY_VANISHING; + + } else { + + this.state = LightningStrike.RAY_STEADY; + + } + + this.visible = true; + + } else { + + this.visible = false; + + if ( time < this.rayParameters.birthTime ) { + + this.state = LightningStrike.RAY_UNBORN; + + } else { + + this.state = LightningStrike.RAY_EXTINGUISHED; + + } + + } + + } + + init( rayParameters ) { + + // Init all the state from the parameters + + this.rayParameters = rayParameters; + + // These parameters cannot change after lightning creation: + + this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor( rayParameters.maxIterations ) : 9; + rayParameters.maxIterations = this.maxIterations; + this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false; + rayParameters.isStatic = this.isStatic; + this.ramification = rayParameters.ramification !== undefined ? Math.floor( rayParameters.ramification ) : 5; + rayParameters.ramification = this.ramification; + this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor( rayParameters.maxSubrayRecursion ) : 3; + rayParameters.maxSubrayRecursion = this.maxSubrayRecursion; + this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6; + rayParameters.recursionProbability = this.recursionProbability; + this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false; + rayParameters.generateUVs = this.generateUVs; + + // Random generator + if ( rayParameters.randomGenerator !== undefined ) { + + this.randomGenerator = rayParameters.randomGenerator; + this.seedGenerator = rayParameters.randomGenerator; + + if ( rayParameters.noiseSeed !== undefined ) { + + this.seedGenerator.setSeed( rayParameters.noiseSeed ); + + } + + } else { + + this.randomGenerator = LightningStrike.createRandomGenerator(); + this.seedGenerator = Math; + + } + + // Ray creation callbacks + if ( rayParameters.onDecideSubrayCreation !== undefined ) { + + this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation; + + } else { + + this.createDefaultSubrayCreationCallbacks(); + + if ( rayParameters.onSubrayCreation !== undefined ) { + + this.onSubrayCreation = rayParameters.onSubrayCreation; + + } + + } + + // Internal state + + this.state = LightningStrike.RAY_INITIALIZED; + + this.maxSubrays = Math.ceil( 1 + Math.pow( this.ramification, Math.max( 0, this.maxSubrayRecursion - 1 ) ) ); + rayParameters.maxSubrays = this.maxSubrays; + + this.maxRaySegments = 2 * ( 1 << this.maxIterations ); + + this.subrays = []; + + for ( let i = 0; i < this.maxSubrays; i ++ ) { + + this.subrays.push( this.createSubray() ); + + } + + this.raySegments = []; + + for ( let i = 0; i < this.maxRaySegments; i ++ ) { + + this.raySegments.push( this.createSegment() ); + + } + + this.time = 0; + this.timeFraction = 0; + this.currentSegmentCallback = null; + this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs; + this.numSubrays = 0; + this.currentSubray = null; + this.currentSegmentIndex = 0; + this.isInitialSegment = false; + this.subrayProbability = 0; + + this.currentVertex = 0; + this.currentIndex = 0; + this.currentCoordinate = 0; + this.currentUVCoordinate = 0; + this.vertices = null; + this.uvs = null; + this.indices = null; + this.positionAttribute = null; + this.uvsAttribute = null; + + this.simplexX = new SimplexNoise( this.seedGenerator ); + this.simplexY = new SimplexNoise( this.seedGenerator ); + this.simplexZ = new SimplexNoise( this.seedGenerator ); + + // Temp vectors + this.forwards = new Vector3(); + this.forwardsFill = new Vector3(); + this.side = new Vector3(); + this.down = new Vector3(); + this.middlePos = new Vector3(); + this.middleLinPos = new Vector3(); + this.newPos = new Vector3(); + this.vPos = new Vector3(); + this.cross1 = new Vector3(); + + } + + createMesh() { + + const maxDrawableSegmentsPerSubRay = 1 << this.maxIterations; + + const maxVerts = 3 * ( maxDrawableSegmentsPerSubRay + 1 ) * this.maxSubrays; + const maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays; + + this.vertices = new Float32Array( maxVerts * 3 ); + this.indices = new Uint32Array( maxIndices ); + + if ( this.generateUVs ) { + + this.uvs = new Float32Array( maxVerts * 2 ); + + } + + // Populate the mesh + this.fillMesh( 0 ); + + this.setIndex( new Uint32BufferAttribute( this.indices, 1 ) ); + + this.positionAttribute = new Float32BufferAttribute( this.vertices, 3 ); + this.setAttribute( 'position', this.positionAttribute ); + + if ( this.generateUVs ) { + + this.uvsAttribute = new Float32BufferAttribute( new Float32Array( this.uvs ), 2 ); + this.setAttribute( 'uv', this.uvsAttribute ); + + } + + if ( ! this.isStatic ) { + + this.index.usage = DynamicDrawUsage; + this.positionAttribute.usage = DynamicDrawUsage; + + if ( this.generateUVs ) { + + this.uvsAttribute.usage = DynamicDrawUsage; + + } + + } + + // Store buffers for later modification + this.vertices = this.positionAttribute.array; + this.indices = this.index.array; + + if ( this.generateUVs ) { + + this.uvs = this.uvsAttribute.array; + + } + + } + + updateMesh( time ) { + + this.fillMesh( time ); + + this.drawRange.count = this.currentIndex; + + this.index.needsUpdate = true; + + this.positionAttribute.needsUpdate = true; + + if ( this.generateUVs ) { + + this.uvsAttribute.needsUpdate = true; + + } + + } + + fillMesh( time ) { + + const scope = this; + + this.currentVertex = 0; + this.currentIndex = 0; + this.currentCoordinate = 0; + this.currentUVCoordinate = 0; + + this.fractalRay( time, function fillVertices( segment ) { + + const subray = scope.currentSubray; + + if ( time < subray.birthTime ) { //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) { + + return; + + } else if ( this.rayParameters.isEternal && scope.currentSubray.recursion == 0 ) { + + // Eternal rays don't propagate nor vanish, but its subrays do + + scope.createPrism( segment ); + + scope.onDecideSubrayCreation( segment, scope ); + + } else if ( time < subray.endPropagationTime ) { + + if ( scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor ) { + + // Ray propagation has arrived to this segment + + scope.createPrism( segment ); + + scope.onDecideSubrayCreation( segment, scope ); + + } + + } else if ( time < subray.beginVanishingTime ) { + + // Ray is steady (nor propagating nor vanishing) + + scope.createPrism( segment ); + + scope.onDecideSubrayCreation( segment, scope ); + + } else { + + if ( scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * ( 1 - subray.vanishingTimeFactor ) ) { + + // Segment has not yet vanished + + scope.createPrism( segment ); + + } + + scope.onDecideSubrayCreation( segment, scope ); + + } + + } ); + + } + + addNewSubray( /*rayParameters*/ ) { + + return this.subrays[ this.numSubrays ++ ]; + + } + + initSubray( subray, rayParameters ) { + + subray.pos0.copy( rayParameters.sourceOffset ); + subray.pos1.copy( rayParameters.destOffset ); + subray.up0.copy( rayParameters.up0 ); + subray.up1.copy( rayParameters.up1 ); + subray.radius0 = rayParameters.radius0; + subray.radius1 = rayParameters.radius1; + subray.birthTime = rayParameters.birthTime; + subray.deathTime = rayParameters.deathTime; + subray.timeScale = rayParameters.timeScale; + subray.roughness = rayParameters.roughness; + subray.straightness = rayParameters.straightness; + subray.propagationTimeFactor = rayParameters.propagationTimeFactor; + subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor; + + subray.maxIterations = this.maxIterations; + subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0; + subray.recursion = 0; + + } + + fractalRay( time, segmentCallback ) { + + this.time = time; + this.currentSegmentCallback = segmentCallback; + this.numSubrays = 0; + + // Add the top level subray + this.initSubray( this.addNewSubray(), this.rayParameters ); + + // Process all subrays that are being generated until consuming all of them + for ( let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex ++ ) { + + const subray = this.subrays[ subrayIndex ]; + this.currentSubray = subray; + + this.randomGenerator.setSeed( subray.seed ); + + subray.endPropagationTime = MathUtils.lerp( subray.birthTime, subray.deathTime, subray.propagationTimeFactor ); + subray.beginVanishingTime = MathUtils.lerp( subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor ); + + const random1 = this.randomGenerator.random; + subray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); + subray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); + + this.timeFraction = ( time - subray.birthTime ) / ( subray.deathTime - subray.birthTime ); + + this.currentSegmentIndex = 0; + this.isInitialSegment = true; + + const segment = this.getNewSegment(); + segment.iteration = 0; + segment.pos0.copy( subray.pos0 ); + segment.pos1.copy( subray.pos1 ); + segment.linPos0.copy( subray.linPos0 ); + segment.linPos1.copy( subray.linPos1 ); + segment.up0.copy( subray.up0 ); + segment.up1.copy( subray.up1 ); + segment.radius0 = subray.radius0; + segment.radius1 = subray.radius1; + segment.fraction0 = 0; + segment.fraction1 = 1; + segment.positionVariationFactor = 1 - subray.straightness; + + this.subrayProbability = this.ramification * Math.pow( this.recursionProbability, subray.recursion ) / ( 1 << subray.maxIterations ); + + this.fractalRayRecursive( segment ); + + } + + this.currentSegmentCallback = null; + this.currentSubray = null; + + } + + fractalRayRecursive( segment ) { + + // Leave recursion condition + if ( segment.iteration >= this.currentSubray.maxIterations ) { + + this.currentSegmentCallback( segment ); + + return; + + } + + // Interpolation + this.forwards.subVectors( segment.pos1, segment.pos0 ); + let lForwards = this.forwards.length(); + + if ( lForwards < 0.000001 ) { + + this.forwards.set( 0, 0, 0.01 ); + lForwards = this.forwards.length(); + + } + + const middleRadius = ( segment.radius0 + segment.radius1 ) * 0.5; + const middleFraction = ( segment.fraction0 + segment.fraction1 ) * 0.5; + + const timeDimension = this.time * this.currentSubray.timeScale * Math.pow( 2, segment.iteration ); + + this.middlePos.lerpVectors( segment.pos0, segment.pos1, 0.5 ); + this.middleLinPos.lerpVectors( segment.linPos0, segment.linPos1, 0.5 ); + const p = this.middleLinPos; + + // Noise + this.newPos.set( this.simplexX.noise4d( p.x, p.y, p.z, timeDimension ), + this.simplexY.noise4d( p.x, p.y, p.z, timeDimension ), + this.simplexZ.noise4d( p.x, p.y, p.z, timeDimension ) ); + + this.newPos.multiplyScalar( segment.positionVariationFactor * lForwards ); + this.newPos.add( this.middlePos ); + + // Recursion + + const newSegment1 = this.getNewSegment(); + newSegment1.pos0.copy( segment.pos0 ); + newSegment1.pos1.copy( this.newPos ); + newSegment1.linPos0.copy( segment.linPos0 ); + newSegment1.linPos1.copy( this.middleLinPos ); + newSegment1.up0.copy( segment.up0 ); + newSegment1.up1.copy( segment.up1 ); + newSegment1.radius0 = segment.radius0; + newSegment1.radius1 = middleRadius; + newSegment1.fraction0 = segment.fraction0; + newSegment1.fraction1 = middleFraction; + newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; + newSegment1.iteration = segment.iteration + 1; + + const newSegment2 = this.getNewSegment(); + newSegment2.pos0.copy( this.newPos ); + newSegment2.pos1.copy( segment.pos1 ); + newSegment2.linPos0.copy( this.middleLinPos ); + newSegment2.linPos1.copy( segment.linPos1 ); + this.cross1.crossVectors( segment.up0, this.forwards.normalize() ); + newSegment2.up0.crossVectors( this.forwards, this.cross1 ).normalize(); + newSegment2.up1.copy( segment.up1 ); + newSegment2.radius0 = middleRadius; + newSegment2.radius1 = segment.radius1; + newSegment2.fraction0 = middleFraction; + newSegment2.fraction1 = segment.fraction1; + newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; + newSegment2.iteration = segment.iteration + 1; + + this.fractalRayRecursive( newSegment1 ); + + this.fractalRayRecursive( newSegment2 ); + + } + + createPrism( segment ) { + + // Creates one triangular prism and its vertices at the segment + + this.forwardsFill.subVectors( segment.pos1, segment.pos0 ).normalize(); + + if ( this.isInitialSegment ) { + + this.currentCreateTriangleVertices( segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0 ); + + this.isInitialSegment = false; + + } + + this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 ); + + this.createPrismFaces(); + + } + + createTriangleVerticesWithoutUVs( pos, up, forwards, radius ) { + + // Create an equilateral triangle (only vertices) + + this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG ); + this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG ); + + const p = this.vPos; + const v = this.vertices; + + p.copy( pos ).sub( this.side ).add( this.down ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + p.copy( pos ).add( this.side ).add( this.down ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + p.copy( up ).multiplyScalar( radius ).add( pos ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + this.currentVertex += 3; + + } + + createTriangleVerticesWithUVs( pos, up, forwards, radius, u ) { + + // Create an equilateral triangle (only vertices) + + this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG ); + this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG ); + + const p = this.vPos; + const v = this.vertices; + const uv = this.uvs; + + p.copy( pos ).sub( this.side ).add( this.down ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + uv[ this.currentUVCoordinate ++ ] = u; + uv[ this.currentUVCoordinate ++ ] = 0; + + p.copy( pos ).add( this.side ).add( this.down ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + uv[ this.currentUVCoordinate ++ ] = u; + uv[ this.currentUVCoordinate ++ ] = 0.5; + + p.copy( up ).multiplyScalar( radius ).add( pos ); + + v[ this.currentCoordinate ++ ] = p.x; + v[ this.currentCoordinate ++ ] = p.y; + v[ this.currentCoordinate ++ ] = p.z; + + uv[ this.currentUVCoordinate ++ ] = u; + uv[ this.currentUVCoordinate ++ ] = 1; + + this.currentVertex += 3; + + } + + createPrismFaces( vertex/*, index*/ ) { + + const indices = this.indices; + vertex = this.currentVertex - 6; + + indices[ this.currentIndex ++ ] = vertex + 1; + indices[ this.currentIndex ++ ] = vertex + 2; + indices[ this.currentIndex ++ ] = vertex + 5; + indices[ this.currentIndex ++ ] = vertex + 1; + indices[ this.currentIndex ++ ] = vertex + 5; + indices[ this.currentIndex ++ ] = vertex + 4; + indices[ this.currentIndex ++ ] = vertex + 0; + indices[ this.currentIndex ++ ] = vertex + 1; + indices[ this.currentIndex ++ ] = vertex + 4; + indices[ this.currentIndex ++ ] = vertex + 0; + indices[ this.currentIndex ++ ] = vertex + 4; + indices[ this.currentIndex ++ ] = vertex + 3; + indices[ this.currentIndex ++ ] = vertex + 2; + indices[ this.currentIndex ++ ] = vertex + 0; + indices[ this.currentIndex ++ ] = vertex + 3; + indices[ this.currentIndex ++ ] = vertex + 2; + indices[ this.currentIndex ++ ] = vertex + 3; + indices[ this.currentIndex ++ ] = vertex + 5; + + } + + createDefaultSubrayCreationCallbacks() { + + const random1 = this.randomGenerator.random; + + this.onDecideSubrayCreation = function ( segment, lightningStrike ) { + + // Decide subrays creation at parent (sub)ray segment + + const subray = lightningStrike.currentSubray; + + const period = lightningStrike.rayParameters.subrayPeriod; + const dutyCycle = lightningStrike.rayParameters.subrayDutyCycle; + + const phase0 = ( lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) ? - random1() * period : MathUtils.lerp( subray.birthTime, subray.endPropagationTime, segment.fraction0 ) - random1() * period; + + const phase = lightningStrike.time - phase0; + const currentCycle = Math.floor( phase / period ); + + const childSubraySeed = random1() * ( currentCycle + 1 ); + + const isActive = phase % period <= dutyCycle * period; + + let probability = 0; + + if ( isActive ) { + + probability = lightningStrike.subrayProbability; + // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0; + + } + + if ( subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability ) { + + const childSubray = lightningStrike.addNewSubray(); + + const parentSeed = lightningStrike.randomGenerator.getSeed(); + childSubray.seed = childSubraySeed; + lightningStrike.randomGenerator.setSeed( childSubraySeed ); + + childSubray.recursion = subray.recursion + 1; + childSubray.maxIterations = Math.max( 1, subray.maxIterations - 1 ); + + childSubray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); + childSubray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 ); + childSubray.up0.copy( subray.up0 ); + childSubray.up1.copy( subray.up1 ); + childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor; + childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor ); + + childSubray.birthTime = phase0 + ( currentCycle ) * period; + childSubray.deathTime = childSubray.birthTime + period * dutyCycle; + + if ( ! lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) { + + childSubray.birthTime = Math.max( childSubray.birthTime, subray.birthTime ); + childSubray.deathTime = Math.min( childSubray.deathTime, subray.deathTime ); + + } + + childSubray.timeScale = subray.timeScale * 2; + childSubray.roughness = subray.roughness; + childSubray.straightness = subray.straightness; + childSubray.propagationTimeFactor = subray.propagationTimeFactor; + childSubray.vanishingTimeFactor = subray.vanishingTimeFactor; + + lightningStrike.onSubrayCreation( segment, subray, childSubray, lightningStrike ); + + lightningStrike.randomGenerator.setSeed( parentSeed ); + + } + + }; + + const vec1Pos = new Vector3(); + const vec2Forward = new Vector3(); + const vec3Side = new Vector3(); + const vec4Up = new Vector3(); + + this.onSubrayCreation = function ( segment, parentSubray, childSubray, lightningStrike ) { + + // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray + + // Just use the default cone position generator + lightningStrike.subrayCylinderPosition( segment, parentSubray, childSubray, 0.5, 0.6, 0.2 ); + + }; + + this.subrayConePosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) { + + // Sets childSubray pos0 and pos1 in a cone + + childSubray.pos0.copy( segment.pos0 ); + + vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 ); + vec2Forward.copy( vec1Pos ).normalize(); + vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( random1() * heightFactor ) ); + const length = vec1Pos.length(); + vec3Side.crossVectors( parentSubray.up0, vec2Forward ); + const angle = 2 * Math.PI * random1(); + vec3Side.multiplyScalar( Math.cos( angle ) ); + vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) ); + + childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 ); + + }; + + this.subrayCylinderPosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) { + + // Sets childSubray pos0 and pos1 in a cylinder + + childSubray.pos0.copy( segment.pos0 ); + + vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 ); + vec2Forward.copy( vec1Pos ).normalize(); + vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( ( 2 * random1() - 1 ) * heightFactor ) ); + const length = vec1Pos.length(); + vec3Side.crossVectors( parentSubray.up0, vec2Forward ); + const angle = 2 * Math.PI * random1(); + vec3Side.multiplyScalar( Math.cos( angle ) ); + vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) ); + + childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 ); + + }; + + } + + createSubray() { + + return { + + seed: 0, + maxIterations: 0, + recursion: 0, + pos0: new Vector3(), + pos1: new Vector3(), + linPos0: new Vector3(), + linPos1: new Vector3(), + up0: new Vector3(), + up1: new Vector3(), + radius0: 0, + radius1: 0, + birthTime: 0, + deathTime: 0, + timeScale: 0, + roughness: 0, + straightness: 0, + propagationTimeFactor: 0, + vanishingTimeFactor: 0, + endPropagationTime: 0, + beginVanishingTime: 0 + + }; + + } + + createSegment() { + + return { + iteration: 0, + pos0: new Vector3(), + pos1: new Vector3(), + linPos0: new Vector3(), + linPos1: new Vector3(), + up0: new Vector3(), + up1: new Vector3(), + radius0: 0, + radius1: 0, + fraction0: 0, + fraction1: 0, + positionVariationFactor: 0 + }; + + } + + getNewSegment() { + + return this.raySegments[ this.currentSegmentIndex ++ ]; + + } + + copy( source ) { + + super.copy( source ); + + this.init( LightningStrike.copyParameters( {}, source.rayParameters ) ); + + return this; + + } + + clone() { + + return new this.constructor( LightningStrike.copyParameters( {}, this.rayParameters ) ); + + } + +} + +// Ray states +LightningStrike.RAY_INITIALIZED = 0; +LightningStrike.RAY_UNBORN = 1; +LightningStrike.RAY_PROPAGATING = 2; +LightningStrike.RAY_STEADY = 3; +LightningStrike.RAY_VANISHING = 4; +LightningStrike.RAY_EXTINGUISHED = 5; + +LightningStrike.COS30DEG = Math.cos( 30 * Math.PI / 180 ); +LightningStrike.SIN30DEG = Math.sin( 30 * Math.PI / 180 ); + +export { LightningStrike }; diff --git a/renderer/jsm/geometries/ParametricGeometries.js b/renderer/jsm/geometries/ParametricGeometries.js new file mode 100644 index 0000000..6716735 --- /dev/null +++ b/renderer/jsm/geometries/ParametricGeometries.js @@ -0,0 +1,254 @@ +import { + Curve, + Vector3 +} from 'three'; + +import { ParametricGeometry } from './ParametricGeometry.js'; + +/** + * Experimenting of primitive geometry creation using Surface Parametric equations + */ + +const ParametricGeometries = { + + klein: function ( v, u, target ) { + + u *= Math.PI; + v *= 2 * Math.PI; + + u = u * 2; + let x, z; + if ( u < Math.PI ) { + + x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( u ) * Math.cos( v ); + z = - 8 * Math.sin( u ) - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( u ) * Math.cos( v ); + + } else { + + x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( v + Math.PI ); + z = - 8 * Math.sin( u ); + + } + + const y = - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( v ); + + target.set( x, y, z ); + + }, + + plane: function ( width, height ) { + + return function ( u, v, target ) { + + const x = u * width; + const y = 0; + const z = v * height; + + target.set( x, y, z ); + + }; + + }, + + mobius: function ( u, t, target ) { + + // flat mobius strip + // http://www.wolframalpha.com/input/?i=M%C3%B6bius+strip+parametric+equations&lk=1&a=ClashPrefs_*Surface.MoebiusStrip.SurfaceProperty.ParametricEquations- + u = u - 0.5; + const v = 2 * Math.PI * t; + + const a = 2; + + const x = Math.cos( v ) * ( a + u * Math.cos( v / 2 ) ); + const y = Math.sin( v ) * ( a + u * Math.cos( v / 2 ) ); + const z = u * Math.sin( v / 2 ); + + target.set( x, y, z ); + + }, + + mobius3d: function ( u, t, target ) { + + // volumetric mobius strip + + u *= Math.PI; + t *= 2 * Math.PI; + + u = u * 2; + const phi = u / 2; + const major = 2.25, a = 0.125, b = 0.65; + + let x = a * Math.cos( t ) * Math.cos( phi ) - b * Math.sin( t ) * Math.sin( phi ); + const z = a * Math.cos( t ) * Math.sin( phi ) + b * Math.sin( t ) * Math.cos( phi ); + const y = ( major + x ) * Math.sin( u ); + x = ( major + x ) * Math.cos( u ); + + target.set( x, y, z ); + + } + +}; + + +/********************************************* + * + * Parametric Replacement for TubeGeometry + * + *********************************************/ + +ParametricGeometries.TubeGeometry = class TubeGeometry extends ParametricGeometry { + + constructor( path, segments = 64, radius = 1, segmentsRadius = 8, closed = false ) { + + const numpoints = segments + 1; + + const frames = path.computeFrenetFrames( segments, closed ), + tangents = frames.tangents, + normals = frames.normals, + binormals = frames.binormals; + + const position = new Vector3(); + + function ParametricTube( u, v, target ) { + + v *= 2 * Math.PI; + + const i = Math.floor( u * ( numpoints - 1 ) ); + + path.getPointAt( u, position ); + + const normal = normals[ i ]; + const binormal = binormals[ i ]; + + const cx = - radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside. + const cy = radius * Math.sin( v ); + + position.x += cx * normal.x + cy * binormal.x; + position.y += cx * normal.y + cy * binormal.y; + position.z += cx * normal.z + cy * binormal.z; + + target.copy( position ); + + } + + super( ParametricTube, segments, segmentsRadius ); + + // proxy internals + + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; + + this.path = path; + this.segments = segments; + this.radius = radius; + this.segmentsRadius = segmentsRadius; + this.closed = closed; + + } + +}; + + +/********************************************* + * + * Parametric Replacement for TorusKnotGeometry + * + *********************************************/ +ParametricGeometries.TorusKnotGeometry = class TorusKnotGeometry extends ParametricGeometries.TubeGeometry { + + constructor( radius = 200, tube = 40, segmentsT = 64, segmentsR = 8, p = 2, q = 3 ) { + + class TorusKnotCurve extends Curve { + + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + t *= Math.PI * 2; + + const r = 0.5; + + const x = ( 1 + r * Math.cos( q * t ) ) * Math.cos( p * t ); + const y = ( 1 + r * Math.cos( q * t ) ) * Math.sin( p * t ); + const z = r * Math.sin( q * t ); + + return point.set( x, y, z ).multiplyScalar( radius ); + + } + + } + + const segments = segmentsT; + const radiusSegments = segmentsR; + const extrudePath = new TorusKnotCurve(); + + super( extrudePath, segments, tube, radiusSegments, true, false ); + + this.radius = radius; + this.tube = tube; + this.segmentsT = segmentsT; + this.segmentsR = segmentsR; + this.p = p; + this.q = q; + + } + +}; + +/********************************************* + * + * Parametric Replacement for SphereGeometry + * + *********************************************/ +ParametricGeometries.SphereGeometry = class SphereGeometry extends ParametricGeometry { + + constructor( size, u, v ) { + + function sphere( u, v, target ) { + + u *= Math.PI; + v *= 2 * Math.PI; + + const x = size * Math.sin( u ) * Math.cos( v ); + const y = size * Math.sin( u ) * Math.sin( v ); + const z = size * Math.cos( u ); + + target.set( x, y, z ); + + } + + super( sphere, u, v ); + + } + +}; + + +/********************************************* + * + * Parametric Replacement for PlaneGeometry + * + *********************************************/ + +ParametricGeometries.PlaneGeometry = class PlaneGeometry extends ParametricGeometry { + + constructor( width, depth, segmentsWidth, segmentsDepth ) { + + function plane( u, v, target ) { + + const x = u * width; + const y = 0; + const z = v * depth; + + target.set( x, y, z ); + + } + + super( plane, segmentsWidth, segmentsDepth ); + + } + +}; + +export { ParametricGeometries }; diff --git a/renderer/jsm/geometries/ParametricGeometry.js b/renderer/jsm/geometries/ParametricGeometry.js new file mode 100644 index 0000000..33ec014 --- /dev/null +++ b/renderer/jsm/geometries/ParametricGeometry.js @@ -0,0 +1,129 @@ +/** + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html + */ + +import { + BufferGeometry, + Float32BufferAttribute, + Vector3 +} from 'three'; + +class ParametricGeometry extends BufferGeometry { + + constructor( func = ( u, v, target ) => target.set( u, v, Math.cos( u ) * Math.sin( v ) ), slices = 8, stacks = 8 ) { + + super(); + + this.type = 'ParametricGeometry'; + + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + const EPS = 0.00001; + + const normal = new Vector3(); + + const p0 = new Vector3(), p1 = new Vector3(); + const pu = new Vector3(), pv = new Vector3(); + + // generate vertices, normals and uvs + + const sliceCount = slices + 1; + + for ( let i = 0; i <= stacks; i ++ ) { + + const v = i / stacks; + + for ( let j = 0; j <= slices; j ++ ) { + + const u = j / slices; + + // vertex + + func( u, v, p0 ); + vertices.push( p0.x, p0.y, p0.z ); + + // normal + + // approximate tangent vectors via finite differences + + if ( u - EPS >= 0 ) { + + func( u - EPS, v, p1 ); + pu.subVectors( p0, p1 ); + + } else { + + func( u + EPS, v, p1 ); + pu.subVectors( p1, p0 ); + + } + + if ( v - EPS >= 0 ) { + + func( u, v - EPS, p1 ); + pv.subVectors( p0, p1 ); + + } else { + + func( u, v + EPS, p1 ); + pv.subVectors( p1, p0 ); + + } + + // cross product of tangent vectors returns surface normal + + normal.crossVectors( pu, pv ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, v ); + + } + + } + + // generate indices + + for ( let i = 0; i < stacks; i ++ ) { + + for ( let j = 0; j < slices; j ++ ) { + + const a = i * sliceCount + j; + const b = i * sliceCount + j + 1; + const c = ( i + 1 ) * sliceCount + j + 1; + const d = ( i + 1 ) * sliceCount + j; + + // faces one and two + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + +} + +export { ParametricGeometry }; diff --git a/renderer/jsm/geometries/RoundedBoxGeometry.js b/renderer/jsm/geometries/RoundedBoxGeometry.js new file mode 100644 index 0000000..8baa168 --- /dev/null +++ b/renderer/jsm/geometries/RoundedBoxGeometry.js @@ -0,0 +1,155 @@ +import { + BoxGeometry, + Vector3 +} from 'three'; + +const _tempNormal = new Vector3(); + +function getUv( faceDirVector, normal, uvAxis, projectionAxis, radius, sideLength ) { + + const totArcLength = 2 * Math.PI * radius / 4; + + // length of the planes between the arcs on each axis + const centerLength = Math.max( sideLength - 2 * radius, 0 ); + const halfArc = Math.PI / 4; + + // Get the vector projected onto the Y plane + _tempNormal.copy( normal ); + _tempNormal[ projectionAxis ] = 0; + _tempNormal.normalize(); + + // total amount of UV space alloted to a single arc + const arcUvRatio = 0.5 * totArcLength / ( totArcLength + centerLength ); + + // the distance along one arc the point is at + const arcAngleRatio = 1.0 - ( _tempNormal.angleTo( faceDirVector ) / halfArc ); + + if ( Math.sign( _tempNormal[ uvAxis ] ) === 1 ) { + + return arcAngleRatio * arcUvRatio; + + } else { + + // total amount of UV space alloted to the plane between the arcs + const lenUv = centerLength / ( totArcLength + centerLength ); + return lenUv + arcUvRatio + arcUvRatio * ( 1.0 - arcAngleRatio ); + + } + +} + +class RoundedBoxGeometry extends BoxGeometry { + + constructor( width = 1, height = 1, depth = 1, segments = 2, radius = 0.1 ) { + + // ensure segments is odd so we have a plane connecting the rounded corners + segments = segments * 2 + 1; + + // ensure radius isn't bigger than shortest side + radius = Math.min( width / 2, height / 2, depth / 2, radius ); + + super( 1, 1, 1, segments, segments, segments ); + + // if we just have one segment we're the same as a regular box + if ( segments === 1 ) return; + + const geometry2 = this.toNonIndexed(); + + this.index = null; + this.attributes.position = geometry2.attributes.position; + this.attributes.normal = geometry2.attributes.normal; + this.attributes.uv = geometry2.attributes.uv; + + // + + const position = new Vector3(); + const normal = new Vector3(); + + const box = new Vector3( width, height, depth ).divideScalar( 2 ).subScalar( radius ); + + const positions = this.attributes.position.array; + const normals = this.attributes.normal.array; + const uvs = this.attributes.uv.array; + + const faceTris = positions.length / 6; + const faceDirVector = new Vector3(); + const halfSegmentSize = 0.5 / segments; + + for ( let i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + + position.fromArray( positions, i ); + normal.copy( position ); + normal.x -= Math.sign( normal.x ) * halfSegmentSize; + normal.y -= Math.sign( normal.y ) * halfSegmentSize; + normal.z -= Math.sign( normal.z ) * halfSegmentSize; + normal.normalize(); + + positions[ i + 0 ] = box.x * Math.sign( position.x ) + normal.x * radius; + positions[ i + 1 ] = box.y * Math.sign( position.y ) + normal.y * radius; + positions[ i + 2 ] = box.z * Math.sign( position.z ) + normal.z * radius; + + normals[ i + 0 ] = normal.x; + normals[ i + 1 ] = normal.y; + normals[ i + 2 ] = normal.z; + + const side = Math.floor( i / faceTris ); + + switch ( side ) { + + case 0: // right + + // generate UVs along Z then Y + faceDirVector.set( 1, 0, 0 ); + uvs[ j + 0 ] = getUv( faceDirVector, normal, 'z', 'y', radius, depth ); + uvs[ j + 1 ] = 1.0 - getUv( faceDirVector, normal, 'y', 'z', radius, height ); + break; + + case 1: // left + + // generate UVs along Z then Y + faceDirVector.set( - 1, 0, 0 ); + uvs[ j + 0 ] = 1.0 - getUv( faceDirVector, normal, 'z', 'y', radius, depth ); + uvs[ j + 1 ] = 1.0 - getUv( faceDirVector, normal, 'y', 'z', radius, height ); + break; + + case 2: // top + + // generate UVs along X then Z + faceDirVector.set( 0, 1, 0 ); + uvs[ j + 0 ] = 1.0 - getUv( faceDirVector, normal, 'x', 'z', radius, width ); + uvs[ j + 1 ] = getUv( faceDirVector, normal, 'z', 'x', radius, depth ); + break; + + case 3: // bottom + + // generate UVs along X then Z + faceDirVector.set( 0, - 1, 0 ); + uvs[ j + 0 ] = 1.0 - getUv( faceDirVector, normal, 'x', 'z', radius, width ); + uvs[ j + 1 ] = 1.0 - getUv( faceDirVector, normal, 'z', 'x', radius, depth ); + break; + + case 4: // front + + // generate UVs along X then Y + faceDirVector.set( 0, 0, 1 ); + uvs[ j + 0 ] = 1.0 - getUv( faceDirVector, normal, 'x', 'y', radius, width ); + uvs[ j + 1 ] = 1.0 - getUv( faceDirVector, normal, 'y', 'x', radius, height ); + break; + + case 5: // back + + // generate UVs along X then Y + faceDirVector.set( 0, 0, - 1 ); + uvs[ j + 0 ] = getUv( faceDirVector, normal, 'x', 'y', radius, width ); + uvs[ j + 1 ] = 1.0 - getUv( faceDirVector, normal, 'y', 'x', radius, height ); + break; + + } + + } + + } + +} + +export { RoundedBoxGeometry }; diff --git a/renderer/jsm/geometries/TeapotGeometry.js b/renderer/jsm/geometries/TeapotGeometry.js new file mode 100644 index 0000000..b6b5ff1 --- /dev/null +++ b/renderer/jsm/geometries/TeapotGeometry.js @@ -0,0 +1,704 @@ +import { + BufferAttribute, + BufferGeometry, + Matrix4, + Vector3, + Vector4 +} from 'three'; + +/** + * Tessellates the famous Utah teapot database by Martin Newell into triangles. + * + * Parameters: size = 50, segments = 10, bottom = true, lid = true, body = true, + * fitLid = false, blinn = true + * + * size is a relative scale: I've scaled the teapot to fit vertically between -1 and 1. + * Think of it as a "radius". + * segments - number of line segments to subdivide each patch edge; + * 1 is possible but gives degenerates, so two is the real minimum. + * bottom - boolean, if true (default) then the bottom patches are added. Some consider + * adding the bottom heresy, so set this to "false" to adhere to the One True Way. + * lid - to remove the lid and look inside, set to true. + * body - to remove the body and leave the lid, set this and "bottom" to false. + * fitLid - the lid is a tad small in the original. This stretches it a bit so you can't + * see the teapot's insides through the gap. + * blinn - Jim Blinn scaled the original data vertically by dividing by about 1.3 to look + * nicer. If you want to see the original teapot, similar to the real-world model, set + * this to false. True by default. + * See http://en.wikipedia.org/wiki/File:Original_Utah_Teapot.jpg for the original + * real-world teapot (from http://en.wikipedia.org/wiki/Utah_teapot). + * + * Note that the bottom (the last four patches) is not flat - blame Frank Crow, not me. + * + * The teapot should normally be rendered as a double sided object, since for some + * patches both sides can be seen, e.g., the gap around the lid and inside the spout. + * + * Segments 'n' determines the number of triangles output. + * Total triangles = 32*2*n*n - 8*n [degenerates at the top and bottom cusps are deleted] + * + * size_factor # triangles + * 1 56 + * 2 240 + * 3 552 + * 4 992 + * + * 10 6320 + * 20 25440 + * 30 57360 + * + * Code converted from my ancient SPD software, http://tog.acm.org/resources/SPD/ + * Created for the Udacity course "Interactive Rendering", http://bit.ly/ericity + * YouTube video on teapot history: https://www.youtube.com/watch?v=DxMfblPzFNc + * + * See https://en.wikipedia.org/wiki/Utah_teapot for the history of the teapot + * + */ + +class TeapotGeometry extends BufferGeometry { + + constructor( size = 50, segments = 10, bottom = true, lid = true, body = true, fitLid = true, blinn = true ) { + + // 32 * 4 * 4 Bezier spline patches + const teapotPatches = [ + /*rim*/ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 3, 16, 17, 18, 7, 19, 20, 21, 11, 22, 23, 24, 15, 25, 26, 27, + 18, 28, 29, 30, 21, 31, 32, 33, 24, 34, 35, 36, 27, 37, 38, 39, + 30, 40, 41, 0, 33, 42, 43, 4, 36, 44, 45, 8, 39, 46, 47, 12, + /*body*/ + 12, 13, 14, 15, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 15, 25, 26, 27, 51, 60, 61, 62, 55, 63, 64, 65, 59, 66, 67, 68, + 27, 37, 38, 39, 62, 69, 70, 71, 65, 72, 73, 74, 68, 75, 76, 77, + 39, 46, 47, 12, 71, 78, 79, 48, 74, 80, 81, 52, 77, 82, 83, 56, + 56, 57, 58, 59, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 59, 66, 67, 68, 87, 96, 97, 98, 91, 99, 100, 101, 95, 102, 103, 104, + 68, 75, 76, 77, 98, 105, 106, 107, 101, 108, 109, 110, 104, 111, 112, 113, + 77, 82, 83, 56, 107, 114, 115, 84, 110, 116, 117, 88, 113, 118, 119, 92, + /*handle*/ + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, + 123, 136, 137, 120, 127, 138, 139, 124, 131, 140, 141, 128, 135, 142, 143, 132, + 132, 133, 134, 135, 144, 145, 146, 147, 148, 149, 150, 151, 68, 152, 153, 154, + 135, 142, 143, 132, 147, 155, 156, 144, 151, 157, 158, 148, 154, 159, 160, 68, + /*spout*/ + 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 164, 177, 178, 161, 168, 179, 180, 165, 172, 181, 182, 169, 176, 183, 184, 173, + 173, 174, 175, 176, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, + 176, 183, 184, 173, 188, 197, 198, 185, 192, 199, 200, 189, 196, 201, 202, 193, + /*lid*/ + 203, 203, 203, 203, 204, 205, 206, 207, 208, 208, 208, 208, 209, 210, 211, 212, + 203, 203, 203, 203, 207, 213, 214, 215, 208, 208, 208, 208, 212, 216, 217, 218, + 203, 203, 203, 203, 215, 219, 220, 221, 208, 208, 208, 208, 218, 222, 223, 224, + 203, 203, 203, 203, 221, 225, 226, 204, 208, 208, 208, 208, 224, 227, 228, 209, + 209, 210, 211, 212, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, + 212, 216, 217, 218, 232, 241, 242, 243, 236, 244, 245, 246, 240, 247, 248, 249, + 218, 222, 223, 224, 243, 250, 251, 252, 246, 253, 254, 255, 249, 256, 257, 258, + 224, 227, 228, 209, 252, 259, 260, 229, 255, 261, 262, 233, 258, 263, 264, 237, + /*bottom*/ + 265, 265, 265, 265, 266, 267, 268, 269, 270, 271, 272, 273, 92, 119, 118, 113, + 265, 265, 265, 265, 269, 274, 275, 276, 273, 277, 278, 279, 113, 112, 111, 104, + 265, 265, 265, 265, 276, 280, 281, 282, 279, 283, 284, 285, 104, 103, 102, 95, + 265, 265, 265, 265, 282, 286, 287, 266, 285, 288, 289, 270, 95, 94, 93, 92 + ]; + + const teapotVertices = [ + 1.4, 0, 2.4, + 1.4, - 0.784, 2.4, + 0.784, - 1.4, 2.4, + 0, - 1.4, 2.4, + 1.3375, 0, 2.53125, + 1.3375, - 0.749, 2.53125, + 0.749, - 1.3375, 2.53125, + 0, - 1.3375, 2.53125, + 1.4375, 0, 2.53125, + 1.4375, - 0.805, 2.53125, + 0.805, - 1.4375, 2.53125, + 0, - 1.4375, 2.53125, + 1.5, 0, 2.4, + 1.5, - 0.84, 2.4, + 0.84, - 1.5, 2.4, + 0, - 1.5, 2.4, + - 0.784, - 1.4, 2.4, + - 1.4, - 0.784, 2.4, + - 1.4, 0, 2.4, + - 0.749, - 1.3375, 2.53125, + - 1.3375, - 0.749, 2.53125, + - 1.3375, 0, 2.53125, + - 0.805, - 1.4375, 2.53125, + - 1.4375, - 0.805, 2.53125, + - 1.4375, 0, 2.53125, + - 0.84, - 1.5, 2.4, + - 1.5, - 0.84, 2.4, + - 1.5, 0, 2.4, + - 1.4, 0.784, 2.4, + - 0.784, 1.4, 2.4, + 0, 1.4, 2.4, + - 1.3375, 0.749, 2.53125, + - 0.749, 1.3375, 2.53125, + 0, 1.3375, 2.53125, + - 1.4375, 0.805, 2.53125, + - 0.805, 1.4375, 2.53125, + 0, 1.4375, 2.53125, + - 1.5, 0.84, 2.4, + - 0.84, 1.5, 2.4, + 0, 1.5, 2.4, + 0.784, 1.4, 2.4, + 1.4, 0.784, 2.4, + 0.749, 1.3375, 2.53125, + 1.3375, 0.749, 2.53125, + 0.805, 1.4375, 2.53125, + 1.4375, 0.805, 2.53125, + 0.84, 1.5, 2.4, + 1.5, 0.84, 2.4, + 1.75, 0, 1.875, + 1.75, - 0.98, 1.875, + 0.98, - 1.75, 1.875, + 0, - 1.75, 1.875, + 2, 0, 1.35, + 2, - 1.12, 1.35, + 1.12, - 2, 1.35, + 0, - 2, 1.35, + 2, 0, 0.9, + 2, - 1.12, 0.9, + 1.12, - 2, 0.9, + 0, - 2, 0.9, + - 0.98, - 1.75, 1.875, + - 1.75, - 0.98, 1.875, + - 1.75, 0, 1.875, + - 1.12, - 2, 1.35, + - 2, - 1.12, 1.35, + - 2, 0, 1.35, + - 1.12, - 2, 0.9, + - 2, - 1.12, 0.9, + - 2, 0, 0.9, + - 1.75, 0.98, 1.875, + - 0.98, 1.75, 1.875, + 0, 1.75, 1.875, + - 2, 1.12, 1.35, + - 1.12, 2, 1.35, + 0, 2, 1.35, + - 2, 1.12, 0.9, + - 1.12, 2, 0.9, + 0, 2, 0.9, + 0.98, 1.75, 1.875, + 1.75, 0.98, 1.875, + 1.12, 2, 1.35, + 2, 1.12, 1.35, + 1.12, 2, 0.9, + 2, 1.12, 0.9, + 2, 0, 0.45, + 2, - 1.12, 0.45, + 1.12, - 2, 0.45, + 0, - 2, 0.45, + 1.5, 0, 0.225, + 1.5, - 0.84, 0.225, + 0.84, - 1.5, 0.225, + 0, - 1.5, 0.225, + 1.5, 0, 0.15, + 1.5, - 0.84, 0.15, + 0.84, - 1.5, 0.15, + 0, - 1.5, 0.15, + - 1.12, - 2, 0.45, + - 2, - 1.12, 0.45, + - 2, 0, 0.45, + - 0.84, - 1.5, 0.225, + - 1.5, - 0.84, 0.225, + - 1.5, 0, 0.225, + - 0.84, - 1.5, 0.15, + - 1.5, - 0.84, 0.15, + - 1.5, 0, 0.15, + - 2, 1.12, 0.45, + - 1.12, 2, 0.45, + 0, 2, 0.45, + - 1.5, 0.84, 0.225, + - 0.84, 1.5, 0.225, + 0, 1.5, 0.225, + - 1.5, 0.84, 0.15, + - 0.84, 1.5, 0.15, + 0, 1.5, 0.15, + 1.12, 2, 0.45, + 2, 1.12, 0.45, + 0.84, 1.5, 0.225, + 1.5, 0.84, 0.225, + 0.84, 1.5, 0.15, + 1.5, 0.84, 0.15, + - 1.6, 0, 2.025, + - 1.6, - 0.3, 2.025, + - 1.5, - 0.3, 2.25, + - 1.5, 0, 2.25, + - 2.3, 0, 2.025, + - 2.3, - 0.3, 2.025, + - 2.5, - 0.3, 2.25, + - 2.5, 0, 2.25, + - 2.7, 0, 2.025, + - 2.7, - 0.3, 2.025, + - 3, - 0.3, 2.25, + - 3, 0, 2.25, + - 2.7, 0, 1.8, + - 2.7, - 0.3, 1.8, + - 3, - 0.3, 1.8, + - 3, 0, 1.8, + - 1.5, 0.3, 2.25, + - 1.6, 0.3, 2.025, + - 2.5, 0.3, 2.25, + - 2.3, 0.3, 2.025, + - 3, 0.3, 2.25, + - 2.7, 0.3, 2.025, + - 3, 0.3, 1.8, + - 2.7, 0.3, 1.8, + - 2.7, 0, 1.575, + - 2.7, - 0.3, 1.575, + - 3, - 0.3, 1.35, + - 3, 0, 1.35, + - 2.5, 0, 1.125, + - 2.5, - 0.3, 1.125, + - 2.65, - 0.3, 0.9375, + - 2.65, 0, 0.9375, + - 2, - 0.3, 0.9, + - 1.9, - 0.3, 0.6, + - 1.9, 0, 0.6, + - 3, 0.3, 1.35, + - 2.7, 0.3, 1.575, + - 2.65, 0.3, 0.9375, + - 2.5, 0.3, 1.125, + - 1.9, 0.3, 0.6, + - 2, 0.3, 0.9, + 1.7, 0, 1.425, + 1.7, - 0.66, 1.425, + 1.7, - 0.66, 0.6, + 1.7, 0, 0.6, + 2.6, 0, 1.425, + 2.6, - 0.66, 1.425, + 3.1, - 0.66, 0.825, + 3.1, 0, 0.825, + 2.3, 0, 2.1, + 2.3, - 0.25, 2.1, + 2.4, - 0.25, 2.025, + 2.4, 0, 2.025, + 2.7, 0, 2.4, + 2.7, - 0.25, 2.4, + 3.3, - 0.25, 2.4, + 3.3, 0, 2.4, + 1.7, 0.66, 0.6, + 1.7, 0.66, 1.425, + 3.1, 0.66, 0.825, + 2.6, 0.66, 1.425, + 2.4, 0.25, 2.025, + 2.3, 0.25, 2.1, + 3.3, 0.25, 2.4, + 2.7, 0.25, 2.4, + 2.8, 0, 2.475, + 2.8, - 0.25, 2.475, + 3.525, - 0.25, 2.49375, + 3.525, 0, 2.49375, + 2.9, 0, 2.475, + 2.9, - 0.15, 2.475, + 3.45, - 0.15, 2.5125, + 3.45, 0, 2.5125, + 2.8, 0, 2.4, + 2.8, - 0.15, 2.4, + 3.2, - 0.15, 2.4, + 3.2, 0, 2.4, + 3.525, 0.25, 2.49375, + 2.8, 0.25, 2.475, + 3.45, 0.15, 2.5125, + 2.9, 0.15, 2.475, + 3.2, 0.15, 2.4, + 2.8, 0.15, 2.4, + 0, 0, 3.15, + 0.8, 0, 3.15, + 0.8, - 0.45, 3.15, + 0.45, - 0.8, 3.15, + 0, - 0.8, 3.15, + 0, 0, 2.85, + 0.2, 0, 2.7, + 0.2, - 0.112, 2.7, + 0.112, - 0.2, 2.7, + 0, - 0.2, 2.7, + - 0.45, - 0.8, 3.15, + - 0.8, - 0.45, 3.15, + - 0.8, 0, 3.15, + - 0.112, - 0.2, 2.7, + - 0.2, - 0.112, 2.7, + - 0.2, 0, 2.7, + - 0.8, 0.45, 3.15, + - 0.45, 0.8, 3.15, + 0, 0.8, 3.15, + - 0.2, 0.112, 2.7, + - 0.112, 0.2, 2.7, + 0, 0.2, 2.7, + 0.45, 0.8, 3.15, + 0.8, 0.45, 3.15, + 0.112, 0.2, 2.7, + 0.2, 0.112, 2.7, + 0.4, 0, 2.55, + 0.4, - 0.224, 2.55, + 0.224, - 0.4, 2.55, + 0, - 0.4, 2.55, + 1.3, 0, 2.55, + 1.3, - 0.728, 2.55, + 0.728, - 1.3, 2.55, + 0, - 1.3, 2.55, + 1.3, 0, 2.4, + 1.3, - 0.728, 2.4, + 0.728, - 1.3, 2.4, + 0, - 1.3, 2.4, + - 0.224, - 0.4, 2.55, + - 0.4, - 0.224, 2.55, + - 0.4, 0, 2.55, + - 0.728, - 1.3, 2.55, + - 1.3, - 0.728, 2.55, + - 1.3, 0, 2.55, + - 0.728, - 1.3, 2.4, + - 1.3, - 0.728, 2.4, + - 1.3, 0, 2.4, + - 0.4, 0.224, 2.55, + - 0.224, 0.4, 2.55, + 0, 0.4, 2.55, + - 1.3, 0.728, 2.55, + - 0.728, 1.3, 2.55, + 0, 1.3, 2.55, + - 1.3, 0.728, 2.4, + - 0.728, 1.3, 2.4, + 0, 1.3, 2.4, + 0.224, 0.4, 2.55, + 0.4, 0.224, 2.55, + 0.728, 1.3, 2.55, + 1.3, 0.728, 2.55, + 0.728, 1.3, 2.4, + 1.3, 0.728, 2.4, + 0, 0, 0, + 1.425, 0, 0, + 1.425, 0.798, 0, + 0.798, 1.425, 0, + 0, 1.425, 0, + 1.5, 0, 0.075, + 1.5, 0.84, 0.075, + 0.84, 1.5, 0.075, + 0, 1.5, 0.075, + - 0.798, 1.425, 0, + - 1.425, 0.798, 0, + - 1.425, 0, 0, + - 0.84, 1.5, 0.075, + - 1.5, 0.84, 0.075, + - 1.5, 0, 0.075, + - 1.425, - 0.798, 0, + - 0.798, - 1.425, 0, + 0, - 1.425, 0, + - 1.5, - 0.84, 0.075, + - 0.84, - 1.5, 0.075, + 0, - 1.5, 0.075, + 0.798, - 1.425, 0, + 1.425, - 0.798, 0, + 0.84, - 1.5, 0.075, + 1.5, - 0.84, 0.075 + ]; + + super(); + + // number of segments per patch + segments = Math.max( 2, Math.floor( segments ) ); + + // Jim Blinn scaled the teapot down in size by about 1.3 for + // some rendering tests. He liked the new proportions that he kept + // the data in this form. The model was distributed with these new + // proportions and became the norm. Trivia: comparing images of the + // real teapot and the computer model, the ratio for the bowl of the + // real teapot is more like 1.25, but since 1.3 is the traditional + // value given, we use it here. + const blinnScale = 1.3; + + // scale the size to be the real scaling factor + const maxHeight = 3.15 * ( blinn ? 1 : blinnScale ); + + const maxHeight2 = maxHeight / 2; + const trueSize = size / maxHeight2; + + // Number of elements depends on what is needed. Subtract degenerate + // triangles at tip of bottom and lid out in advance. + let numTriangles = bottom ? ( 8 * segments - 4 ) * segments : 0; + numTriangles += lid ? ( 16 * segments - 4 ) * segments : 0; + numTriangles += body ? 40 * segments * segments : 0; + + const indices = new Uint32Array( numTriangles * 3 ); + + let numVertices = bottom ? 4 : 0; + numVertices += lid ? 8 : 0; + numVertices += body ? 20 : 0; + numVertices *= ( segments + 1 ) * ( segments + 1 ); + + const vertices = new Float32Array( numVertices * 3 ); + const normals = new Float32Array( numVertices * 3 ); + const uvs = new Float32Array( numVertices * 2 ); + + // Bezier form + const ms = new Matrix4(); + ms.set( + - 1.0, 3.0, - 3.0, 1.0, + 3.0, - 6.0, 3.0, 0.0, + - 3.0, 3.0, 0.0, 0.0, + 1.0, 0.0, 0.0, 0.0 ); + + const g = []; + + const sp = []; + const tp = []; + const dsp = []; + const dtp = []; + + // M * G * M matrix, sort of see + // http://www.cs.helsinki.fi/group/goa/mallinnus/curves/surfaces.html + const mgm = []; + + const vert = []; + const sdir = []; + const tdir = []; + + const norm = new Vector3(); + + let tcoord; + + let sval; + let tval; + let p; + let dsval = 0; + let dtval = 0; + + const normOut = new Vector3(); + + const gmx = new Matrix4(); + const tmtx = new Matrix4(); + + const vsp = new Vector4(); + const vtp = new Vector4(); + const vdsp = new Vector4(); + const vdtp = new Vector4(); + + const vsdir = new Vector3(); + const vtdir = new Vector3(); + + const mst = ms.clone(); + mst.transpose(); + + // internal function: test if triangle has any matching vertices; + // if so, don't save triangle, since it won't display anything. + const notDegenerate = ( vtx1, vtx2, vtx3 ) => // if any vertex matches, return false + ! ( ( ( vertices[ vtx1 * 3 ] === vertices[ vtx2 * 3 ] ) && + ( vertices[ vtx1 * 3 + 1 ] === vertices[ vtx2 * 3 + 1 ] ) && + ( vertices[ vtx1 * 3 + 2 ] === vertices[ vtx2 * 3 + 2 ] ) ) || + ( ( vertices[ vtx1 * 3 ] === vertices[ vtx3 * 3 ] ) && + ( vertices[ vtx1 * 3 + 1 ] === vertices[ vtx3 * 3 + 1 ] ) && + ( vertices[ vtx1 * 3 + 2 ] === vertices[ vtx3 * 3 + 2 ] ) ) || ( vertices[ vtx2 * 3 ] === vertices[ vtx3 * 3 ] ) && + ( vertices[ vtx2 * 3 + 1 ] === vertices[ vtx3 * 3 + 1 ] ) && + ( vertices[ vtx2 * 3 + 2 ] === vertices[ vtx3 * 3 + 2 ] ) ); + + + for ( let i = 0; i < 3; i ++ ) { + + mgm[ i ] = new Matrix4(); + + } + + const minPatches = body ? 0 : 20; + const maxPatches = bottom ? 32 : 28; + + const vertPerRow = segments + 1; + + let surfCount = 0; + + let vertCount = 0; + let normCount = 0; + let uvCount = 0; + + let indexCount = 0; + + for ( let surf = minPatches; surf < maxPatches; surf ++ ) { + + // lid is in the middle of the data, patches 20-27, + // so ignore it for this part of the loop if the lid is not desired + if ( lid || ( surf < 20 || surf >= 28 ) ) { + + // get M * G * M matrix for x,y,z + for ( let i = 0; i < 3; i ++ ) { + + // get control patches + for ( let r = 0; r < 4; r ++ ) { + + for ( let c = 0; c < 4; c ++ ) { + + // transposed + g[ c * 4 + r ] = teapotVertices[ teapotPatches[ surf * 16 + r * 4 + c ] * 3 + i ]; + + // is the lid to be made larger, and is this a point on the lid + // that is X or Y? + if ( fitLid && ( surf >= 20 && surf < 28 ) && ( i !== 2 ) ) { + + // increase XY size by 7.7%, found empirically. I don't + // increase Z so that the teapot will continue to fit in the + // space -1 to 1 for Y (Y is up for the final model). + g[ c * 4 + r ] *= 1.077; + + } + + // Blinn "fixed" the teapot by dividing Z by blinnScale, and that's the + // data we now use. The original teapot is taller. Fix it: + if ( ! blinn && ( i === 2 ) ) { + + g[ c * 4 + r ] *= blinnScale; + + } + + } + + } + + gmx.set( g[ 0 ], g[ 1 ], g[ 2 ], g[ 3 ], g[ 4 ], g[ 5 ], g[ 6 ], g[ 7 ], g[ 8 ], g[ 9 ], g[ 10 ], g[ 11 ], g[ 12 ], g[ 13 ], g[ 14 ], g[ 15 ] ); + + tmtx.multiplyMatrices( gmx, ms ); + mgm[ i ].multiplyMatrices( mst, tmtx ); + + } + + // step along, get points, and output + for ( let sstep = 0; sstep <= segments; sstep ++ ) { + + const s = sstep / segments; + + for ( let tstep = 0; tstep <= segments; tstep ++ ) { + + const t = tstep / segments; + + // point from basis + // get power vectors and their derivatives + for ( p = 4, sval = tval = 1.0; p --; ) { + + sp[ p ] = sval; + tp[ p ] = tval; + sval *= s; + tval *= t; + + if ( p === 3 ) { + + dsp[ p ] = dtp[ p ] = 0.0; + dsval = dtval = 1.0; + + } else { + + dsp[ p ] = dsval * ( 3 - p ); + dtp[ p ] = dtval * ( 3 - p ); + dsval *= s; + dtval *= t; + + } + + } + + vsp.fromArray( sp ); + vtp.fromArray( tp ); + vdsp.fromArray( dsp ); + vdtp.fromArray( dtp ); + + // do for x,y,z + for ( let i = 0; i < 3; i ++ ) { + + // multiply power vectors times matrix to get value + tcoord = vsp.clone(); + tcoord.applyMatrix4( mgm[ i ] ); + vert[ i ] = tcoord.dot( vtp ); + + // get s and t tangent vectors + tcoord = vdsp.clone(); + tcoord.applyMatrix4( mgm[ i ] ); + sdir[ i ] = tcoord.dot( vtp ); + + tcoord = vsp.clone(); + tcoord.applyMatrix4( mgm[ i ] ); + tdir[ i ] = tcoord.dot( vdtp ); + + } + + // find normal + vsdir.fromArray( sdir ); + vtdir.fromArray( tdir ); + norm.crossVectors( vtdir, vsdir ); + norm.normalize(); + + // if X and Z length is 0, at the cusp, so point the normal up or down, depending on patch number + if ( vert[ 0 ] === 0 && vert[ 1 ] === 0 ) { + + // if above the middle of the teapot, normal points up, else down + normOut.set( 0, vert[ 2 ] > maxHeight2 ? 1 : - 1, 0 ); + + } else { + + // standard output: rotate on X axis + normOut.set( norm.x, norm.z, - norm.y ); + + } + + // store it all + vertices[ vertCount ++ ] = trueSize * vert[ 0 ]; + vertices[ vertCount ++ ] = trueSize * ( vert[ 2 ] - maxHeight2 ); + vertices[ vertCount ++ ] = - trueSize * vert[ 1 ]; + + normals[ normCount ++ ] = normOut.x; + normals[ normCount ++ ] = normOut.y; + normals[ normCount ++ ] = normOut.z; + + uvs[ uvCount ++ ] = 1 - t; + uvs[ uvCount ++ ] = 1 - s; + + } + + } + + // save the faces + for ( let sstep = 0; sstep < segments; sstep ++ ) { + + for ( let tstep = 0; tstep < segments; tstep ++ ) { + + const v1 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep; + const v2 = v1 + 1; + const v3 = v2 + vertPerRow; + const v4 = v1 + vertPerRow; + + // Normals and UVs cannot be shared. Without clone(), you can see the consequences + // of sharing if you call geometry.applyMatrix4( matrix ). + if ( notDegenerate( v1, v2, v3 ) ) { + + indices[ indexCount ++ ] = v1; + indices[ indexCount ++ ] = v2; + indices[ indexCount ++ ] = v3; + + } + + if ( notDegenerate( v1, v3, v4 ) ) { + + indices[ indexCount ++ ] = v1; + indices[ indexCount ++ ] = v3; + indices[ indexCount ++ ] = v4; + + } + + } + + } + + // increment only if a surface was used + surfCount ++; + + } + + } + + this.setIndex( new BufferAttribute( indices, 1 ) ); + this.setAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ) ); + + this.computeBoundingSphere(); + + } + +} + +export { TeapotGeometry }; diff --git a/renderer/jsm/geometries/TextGeometry.js b/renderer/jsm/geometries/TextGeometry.js new file mode 100644 index 0000000..5275c03 --- /dev/null +++ b/renderer/jsm/geometries/TextGeometry.js @@ -0,0 +1,57 @@ +/** + * 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 (including bevelOffset) is bevel + * bevelOffset: // how far from text outline does bevel start + * } + */ + +import { + ExtrudeGeometry +} from 'three'; + +class TextGeometry extends ExtrudeGeometry { + + constructor( text, parameters = {} ) { + + const font = parameters.font; + + if ( font === undefined ) { + + super(); // generate default extrude geometry + + } else { + + const shapes = font.generateShapes( text, parameters.size ); + + // translate parameters to ExtrudeGeometry API + + parameters.depth = parameters.height !== undefined ? parameters.height : 50; + + // defaults + + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + + super( shapes, parameters ); + + } + + this.type = 'TextGeometry'; + + } + +} + + +export { TextGeometry }; diff --git a/renderer/jsm/helpers/LightProbeHelper.js b/renderer/jsm/helpers/LightProbeHelper.js new file mode 100644 index 0000000..8120488 --- /dev/null +++ b/renderer/jsm/helpers/LightProbeHelper.js @@ -0,0 +1,130 @@ +import { + Mesh, + ShaderMaterial, + SphereGeometry +} from 'three'; + +class LightProbeHelper extends Mesh { + + constructor( lightProbe, size ) { + + const material = new ShaderMaterial( { + + type: 'LightProbeHelperMaterial', + + uniforms: { + + sh: { value: lightProbe.sh.coefficients }, // by reference + + intensity: { value: lightProbe.intensity } + + }, + + vertexShader: [ + + 'varying vec3 vNormal;', + + 'void main() {', + + ' vNormal = normalize( normalMatrix * normal );', + + ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', + + '}', + + ].join( '\n' ), + + fragmentShader: [ + + '#define RECIPROCAL_PI 0.318309886', + + 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', + + ' // matrix is assumed to be orthogonal', + + ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', + + '}', + + '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf', + 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', + + ' // normal is assumed to have unit length', + + ' float x = normal.x, y = normal.y, z = normal.z;', + + ' // band 0', + ' vec3 result = shCoefficients[ 0 ] * 0.886227;', + + ' // band 1', + ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', + ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', + ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', + + ' // band 2', + ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', + ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', + ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', + ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', + ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', + + ' return result;', + + '}', + + 'uniform vec3 sh[ 9 ]; // sh coefficients', + + 'uniform float intensity; // light probe intensity', + + 'varying vec3 vNormal;', + + 'void main() {', + + ' vec3 normal = normalize( vNormal );', + + ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', + + ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );', + + ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', + + ' gl_FragColor = linearToOutputTexel( vec4( outgoingLight, 1.0 ) );', + + '}' + + ].join( '\n' ) + + } ); + + const geometry = new SphereGeometry( 1, 32, 16 ); + + super( geometry, material ); + + this.lightProbe = lightProbe; + this.size = size; + this.type = 'LightProbeHelper'; + + this.onBeforeRender(); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + + onBeforeRender() { + + this.position.copy( this.lightProbe.position ); + + this.scale.set( 1, 1, 1 ).multiplyScalar( this.size ); + + this.material.uniforms.intensity.value = this.lightProbe.intensity; + + } + +} + +export { LightProbeHelper }; diff --git a/renderer/jsm/helpers/OctreeHelper.js b/renderer/jsm/helpers/OctreeHelper.js new file mode 100644 index 0000000..972942c --- /dev/null +++ b/renderer/jsm/helpers/OctreeHelper.js @@ -0,0 +1,73 @@ +import { + LineSegments, + BufferGeometry, + Float32BufferAttribute, + LineBasicMaterial +} from 'three'; + +class OctreeHelper extends LineSegments { + + constructor( octree, color = 0xffff00 ) { + + super( new BufferGeometry(), new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.octree = octree; + this.color = color; + + this.type = 'OctreeHelper'; + + this.update(); + + } + + update() { + + const vertices = []; + + function traverse( tree ) { + + for ( let i = 0; i < tree.length; i ++ ) { + + const min = tree[ i ].box.min; + const max = tree[ i ].box.max; + + vertices.push( max.x, max.y, max.z ); vertices.push( min.x, max.y, max.z ); // 0, 1 + vertices.push( min.x, max.y, max.z ); vertices.push( min.x, min.y, max.z ); // 1, 2 + vertices.push( min.x, min.y, max.z ); vertices.push( max.x, min.y, max.z ); // 2, 3 + vertices.push( max.x, min.y, max.z ); vertices.push( max.x, max.y, max.z ); // 3, 0 + + vertices.push( max.x, max.y, min.z ); vertices.push( min.x, max.y, min.z ); // 4, 5 + vertices.push( min.x, max.y, min.z ); vertices.push( min.x, min.y, min.z ); // 5, 6 + vertices.push( min.x, min.y, min.z ); vertices.push( max.x, min.y, min.z ); // 6, 7 + vertices.push( max.x, min.y, min.z ); vertices.push( max.x, max.y, min.z ); // 7, 4 + + vertices.push( max.x, max.y, max.z ); vertices.push( max.x, max.y, min.z ); // 0, 4 + vertices.push( min.x, max.y, max.z ); vertices.push( min.x, max.y, min.z ); // 1, 5 + vertices.push( min.x, min.y, max.z ); vertices.push( min.x, min.y, min.z ); // 2, 6 + vertices.push( max.x, min.y, max.z ); vertices.push( max.x, min.y, min.z ); // 3, 7 + + traverse( tree[ i ].subTrees ); + + } + + } + + traverse( this.octree.subTrees ); + + this.geometry.dispose(); + + this.geometry = new BufferGeometry(); + this.geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +export { OctreeHelper }; diff --git a/renderer/jsm/helpers/PositionalAudioHelper.js b/renderer/jsm/helpers/PositionalAudioHelper.js new file mode 100644 index 0000000..0a20ea5 --- /dev/null +++ b/renderer/jsm/helpers/PositionalAudioHelper.js @@ -0,0 +1,109 @@ +import { + BufferGeometry, + BufferAttribute, + LineBasicMaterial, + Line, + MathUtils +} from 'three'; + +class PositionalAudioHelper extends Line { + + constructor( audio, range = 1, divisionsInnerAngle = 16, divisionsOuterAngle = 2 ) { + + const geometry = new BufferGeometry(); + const divisions = divisionsInnerAngle + divisionsOuterAngle * 2; + const positions = new Float32Array( ( divisions * 3 + 3 ) * 3 ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + + const materialInnerAngle = new LineBasicMaterial( { color: 0x00ff00 } ); + const materialOuterAngle = new LineBasicMaterial( { color: 0xffff00 } ); + + super( geometry, [ materialOuterAngle, materialInnerAngle ] ); + + this.audio = audio; + this.range = range; + this.divisionsInnerAngle = divisionsInnerAngle; + this.divisionsOuterAngle = divisionsOuterAngle; + this.type = 'PositionalAudioHelper'; + + this.update(); + + } + + update() { + + const audio = this.audio; + const range = this.range; + const divisionsInnerAngle = this.divisionsInnerAngle; + const divisionsOuterAngle = this.divisionsOuterAngle; + + const coneInnerAngle = MathUtils.degToRad( audio.panner.coneInnerAngle ); + const coneOuterAngle = MathUtils.degToRad( audio.panner.coneOuterAngle ); + + const halfConeInnerAngle = coneInnerAngle / 2; + const halfConeOuterAngle = coneOuterAngle / 2; + + let start = 0; + let count = 0; + let i; + let stride; + + const geometry = this.geometry; + const positionAttribute = geometry.attributes.position; + + geometry.clearGroups(); + + // + + function generateSegment( from, to, divisions, materialIndex ) { + + const step = ( to - from ) / divisions; + + positionAttribute.setXYZ( start, 0, 0, 0 ); + count ++; + + for ( i = from; i < to; i += step ) { + + stride = start + count; + + positionAttribute.setXYZ( stride, Math.sin( i ) * range, 0, Math.cos( i ) * range ); + positionAttribute.setXYZ( stride + 1, Math.sin( Math.min( i + step, to ) ) * range, 0, Math.cos( Math.min( i + step, to ) ) * range ); + positionAttribute.setXYZ( stride + 2, 0, 0, 0 ); + + count += 3; + + } + + geometry.addGroup( start, count, materialIndex ); + + start += count; + count = 0; + + } + + // + + generateSegment( - halfConeOuterAngle, - halfConeInnerAngle, divisionsOuterAngle, 0 ); + generateSegment( - halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1 ); + generateSegment( halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0 ); + + // + + positionAttribute.needsUpdate = true; + + if ( coneInnerAngle === coneOuterAngle ) this.material[ 0 ].visible = false; + + } + + dispose() { + + this.geometry.dispose(); + this.material[ 0 ].dispose(); + this.material[ 1 ].dispose(); + + } + +} + + +export { PositionalAudioHelper }; diff --git a/renderer/jsm/helpers/RectAreaLightHelper.js b/renderer/jsm/helpers/RectAreaLightHelper.js new file mode 100644 index 0000000..416fe1b --- /dev/null +++ b/renderer/jsm/helpers/RectAreaLightHelper.js @@ -0,0 +1,85 @@ +import { + BackSide, + BufferGeometry, + Float32BufferAttribute, + Line, + LineBasicMaterial, + Mesh, + MeshBasicMaterial +} from 'three'; + +/** + * This helper must be added as a child of the light + */ + +class RectAreaLightHelper extends Line { + + constructor( light, color ) { + + const positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + const material = new LineBasicMaterial( { fog: false } ); + + super( geometry, material ); + + this.light = light; + this.color = color; // optional hardwired color for the helper + this.type = 'RectAreaLightHelper'; + + // + + const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; + + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { side: BackSide, fog: false } ) ) ); + + } + + updateMatrixWorld() { + + this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 ); + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + this.children[ 0 ].material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + + // prevent hue shift + const c = this.material.color; + const max = Math.max( c.r, c.g, c.b ); + if ( max > 1 ) c.multiplyScalar( 1 / max ); + + this.children[ 0 ].material.color.copy( this.material.color ); + + } + + // ignore world scale on light + this.matrixWorld.extractRotation( this.light.matrixWorld ).scale( this.scale ).copyPosition( this.light.matrixWorld ); + + this.children[ 0 ].matrixWorld.copy( this.matrixWorld ); + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + +} + +export { RectAreaLightHelper }; diff --git a/renderer/jsm/helpers/VertexNormalsHelper.js b/renderer/jsm/helpers/VertexNormalsHelper.js new file mode 100644 index 0000000..bfe41ab --- /dev/null +++ b/renderer/jsm/helpers/VertexNormalsHelper.js @@ -0,0 +1,96 @@ +import { + BufferGeometry, + Float32BufferAttribute, + LineSegments, + LineBasicMaterial, + Matrix3, + Vector3 +} from 'three'; + +const _v1 = new Vector3(); +const _v2 = new Vector3(); +const _normalMatrix = new Matrix3(); + +class VertexNormalsHelper extends LineSegments { + + constructor( object, size = 1, color = 0xff0000 ) { + + const geometry = new BufferGeometry(); + + const nNormals = object.geometry.attributes.normal.count; + const positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 ); + + geometry.setAttribute( 'position', positions ); + + super( geometry, new LineBasicMaterial( { color, toneMapped: false } ) ); + + this.object = object; + this.size = size; + this.type = 'VertexNormalsHelper'; + + // + + this.matrixAutoUpdate = false; + + this.update(); + + } + + update() { + + this.object.updateMatrixWorld( true ); + + _normalMatrix.getNormalMatrix( this.object.matrixWorld ); + + const matrixWorld = this.object.matrixWorld; + + const position = this.geometry.attributes.position; + + // + + const objGeometry = this.object.geometry; + + if ( objGeometry ) { + + const objPos = objGeometry.attributes.position; + + const objNorm = objGeometry.attributes.normal; + + let idx = 0; + + // for simplicity, ignore index and drawcalls, and render every normal + + for ( let j = 0, jl = objPos.count; j < jl; j ++ ) { + + _v1.fromBufferAttribute( objPos, j ).applyMatrix4( matrixWorld ); + + _v2.fromBufferAttribute( objNorm, j ); + + _v2.applyMatrix3( _normalMatrix ).normalize().multiplyScalar( this.size ).add( _v1 ); + + position.setXYZ( idx, _v1.x, _v1.y, _v1.z ); + + idx = idx + 1; + + position.setXYZ( idx, _v2.x, _v2.y, _v2.z ); + + idx = idx + 1; + + } + + } + + position.needsUpdate = true; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +export { VertexNormalsHelper }; diff --git a/renderer/jsm/helpers/VertexTangentsHelper.js b/renderer/jsm/helpers/VertexTangentsHelper.js new file mode 100644 index 0000000..1ad413f --- /dev/null +++ b/renderer/jsm/helpers/VertexTangentsHelper.js @@ -0,0 +1,88 @@ +import { + BufferGeometry, + Float32BufferAttribute, + LineSegments, + LineBasicMaterial, + Vector3 +} from 'three'; + +const _v1 = new Vector3(); +const _v2 = new Vector3(); + +class VertexTangentsHelper extends LineSegments { + + constructor( object, size = 1, color = 0x00ffff ) { + + const geometry = new BufferGeometry(); + + const nTangents = object.geometry.attributes.tangent.count; + const positions = new Float32BufferAttribute( nTangents * 2 * 3, 3 ); + + geometry.setAttribute( 'position', positions ); + + super( geometry, new LineBasicMaterial( { color, toneMapped: false } ) ); + + this.object = object; + this.size = size; + this.type = 'VertexTangentsHelper'; + + // + + this.matrixAutoUpdate = false; + + this.update(); + + } + + update() { + + this.object.updateMatrixWorld( true ); + + const matrixWorld = this.object.matrixWorld; + + const position = this.geometry.attributes.position; + + // + + const objGeometry = this.object.geometry; + + const objPos = objGeometry.attributes.position; + + const objTan = objGeometry.attributes.tangent; + + let idx = 0; + + // for simplicity, ignore index and drawcalls, and render every tangent + + for ( let j = 0, jl = objPos.count; j < jl; j ++ ) { + + _v1.fromBufferAttribute( objPos, j ).applyMatrix4( matrixWorld ); + + _v2.fromBufferAttribute( objTan, j ); + + _v2.transformDirection( matrixWorld ).multiplyScalar( this.size ).add( _v1 ); + + position.setXYZ( idx, _v1.x, _v1.y, _v1.z ); + + idx = idx + 1; + + position.setXYZ( idx, _v2.x, _v2.y, _v2.z ); + + idx = idx + 1; + + } + + position.needsUpdate = true; + + } + + dispose() { + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +export { VertexTangentsHelper }; diff --git a/renderer/jsm/helpers/ViewHelper.js b/renderer/jsm/helpers/ViewHelper.js new file mode 100644 index 0000000..ef41881 --- /dev/null +++ b/renderer/jsm/helpers/ViewHelper.js @@ -0,0 +1,333 @@ +import { + BoxGeometry, + CanvasTexture, + Color, + Euler, + Mesh, + MeshBasicMaterial, + Object3D, + OrthographicCamera, + Quaternion, + Raycaster, + Sprite, + SpriteMaterial, + Vector2, + Vector3, + Vector4 +} from 'three'; + +class ViewHelper extends Object3D { + + constructor( camera, domElement ) { + + super(); + + this.isViewHelper = true; + + this.animating = false; + this.center = new Vector3(); + + const color1 = new Color( '#ff3653' ); + const color2 = new Color( '#8adb00' ); + const color3 = new Color( '#2c8fff' ); + + const interactiveObjects = []; + const raycaster = new Raycaster(); + const mouse = new Vector2(); + const dummy = new Object3D(); + + const orthoCamera = new OrthographicCamera( - 2, 2, 2, - 2, 0, 4 ); + orthoCamera.position.set( 0, 0, 2 ); + + const geometry = new BoxGeometry( 0.8, 0.05, 0.05 ).translate( 0.4, 0, 0 ); + + const xAxis = new Mesh( geometry, getAxisMaterial( color1 ) ); + const yAxis = new Mesh( geometry, getAxisMaterial( color2 ) ); + const zAxis = new Mesh( geometry, getAxisMaterial( color3 ) ); + + yAxis.rotation.z = Math.PI / 2; + zAxis.rotation.y = - Math.PI / 2; + + this.add( xAxis ); + this.add( zAxis ); + this.add( yAxis ); + + const posXAxisHelper = new Sprite( getSpriteMaterial( color1, 'X' ) ); + posXAxisHelper.userData.type = 'posX'; + const posYAxisHelper = new Sprite( getSpriteMaterial( color2, 'Y' ) ); + posYAxisHelper.userData.type = 'posY'; + const posZAxisHelper = new Sprite( getSpriteMaterial( color3, 'Z' ) ); + posZAxisHelper.userData.type = 'posZ'; + const negXAxisHelper = new Sprite( getSpriteMaterial( color1 ) ); + negXAxisHelper.userData.type = 'negX'; + const negYAxisHelper = new Sprite( getSpriteMaterial( color2 ) ); + negYAxisHelper.userData.type = 'negY'; + const negZAxisHelper = new Sprite( getSpriteMaterial( color3 ) ); + negZAxisHelper.userData.type = 'negZ'; + + posXAxisHelper.position.x = 1; + posYAxisHelper.position.y = 1; + posZAxisHelper.position.z = 1; + negXAxisHelper.position.x = - 1; + negXAxisHelper.scale.setScalar( 0.8 ); + negYAxisHelper.position.y = - 1; + negYAxisHelper.scale.setScalar( 0.8 ); + negZAxisHelper.position.z = - 1; + negZAxisHelper.scale.setScalar( 0.8 ); + + this.add( posXAxisHelper ); + this.add( posYAxisHelper ); + this.add( posZAxisHelper ); + this.add( negXAxisHelper ); + this.add( negYAxisHelper ); + this.add( negZAxisHelper ); + + interactiveObjects.push( posXAxisHelper ); + interactiveObjects.push( posYAxisHelper ); + interactiveObjects.push( posZAxisHelper ); + interactiveObjects.push( negXAxisHelper ); + interactiveObjects.push( negYAxisHelper ); + interactiveObjects.push( negZAxisHelper ); + + const point = new Vector3(); + const dim = 128; + const turnRate = 2 * Math.PI; // turn rate in angles per second + + this.render = function ( renderer ) { + + this.quaternion.copy( camera.quaternion ).invert(); + this.updateMatrixWorld(); + + point.set( 0, 0, 1 ); + point.applyQuaternion( camera.quaternion ); + + if ( point.x >= 0 ) { + + posXAxisHelper.material.opacity = 1; + negXAxisHelper.material.opacity = 0.5; + + } else { + + posXAxisHelper.material.opacity = 0.5; + negXAxisHelper.material.opacity = 1; + + } + + if ( point.y >= 0 ) { + + posYAxisHelper.material.opacity = 1; + negYAxisHelper.material.opacity = 0.5; + + } else { + + posYAxisHelper.material.opacity = 0.5; + negYAxisHelper.material.opacity = 1; + + } + + if ( point.z >= 0 ) { + + posZAxisHelper.material.opacity = 1; + negZAxisHelper.material.opacity = 0.5; + + } else { + + posZAxisHelper.material.opacity = 0.5; + negZAxisHelper.material.opacity = 1; + + } + + // + + const x = domElement.offsetWidth - dim; + + renderer.clearDepth(); + + renderer.getViewport( viewport ); + renderer.setViewport( x, 0, dim, dim ); + + renderer.render( this, orthoCamera ); + + renderer.setViewport( viewport.x, viewport.y, viewport.z, viewport.w ); + + }; + + const targetPosition = new Vector3(); + const targetQuaternion = new Quaternion(); + + const q1 = new Quaternion(); + const q2 = new Quaternion(); + const viewport = new Vector4(); + let radius = 0; + + this.handleClick = function ( event ) { + + if ( this.animating === true ) return false; + + const rect = domElement.getBoundingClientRect(); + const offsetX = rect.left + ( domElement.offsetWidth - dim ); + const offsetY = rect.top + ( domElement.offsetHeight - dim ); + mouse.x = ( ( event.clientX - offsetX ) / ( rect.width - offsetX ) ) * 2 - 1; + mouse.y = - ( ( event.clientY - offsetY ) / ( rect.bottom - offsetY ) ) * 2 + 1; + + raycaster.setFromCamera( mouse, orthoCamera ); + + const intersects = raycaster.intersectObjects( interactiveObjects ); + + if ( intersects.length > 0 ) { + + const intersection = intersects[ 0 ]; + const object = intersection.object; + + prepareAnimationData( object, this.center ); + + this.animating = true; + + return true; + + } else { + + return false; + + } + + }; + + this.update = function ( delta ) { + + const step = delta * turnRate; + + // animate position by doing a slerp and then scaling the position on the unit sphere + + q1.rotateTowards( q2, step ); + camera.position.set( 0, 0, 1 ).applyQuaternion( q1 ).multiplyScalar( radius ).add( this.center ); + + // animate orientation + + camera.quaternion.rotateTowards( targetQuaternion, step ); + + if ( q1.angleTo( q2 ) === 0 ) { + + this.animating = false; + + } + + }; + + this.dispose = function () { + + geometry.dispose(); + + xAxis.material.dispose(); + yAxis.material.dispose(); + zAxis.material.dispose(); + + posXAxisHelper.material.map.dispose(); + posYAxisHelper.material.map.dispose(); + posZAxisHelper.material.map.dispose(); + negXAxisHelper.material.map.dispose(); + negYAxisHelper.material.map.dispose(); + negZAxisHelper.material.map.dispose(); + + posXAxisHelper.material.dispose(); + posYAxisHelper.material.dispose(); + posZAxisHelper.material.dispose(); + negXAxisHelper.material.dispose(); + negYAxisHelper.material.dispose(); + negZAxisHelper.material.dispose(); + + }; + + function prepareAnimationData( object, focusPoint ) { + + switch ( object.userData.type ) { + + case 'posX': + targetPosition.set( 1, 0, 0 ); + targetQuaternion.setFromEuler( new Euler( 0, Math.PI * 0.5, 0 ) ); + break; + + case 'posY': + targetPosition.set( 0, 1, 0 ); + targetQuaternion.setFromEuler( new Euler( - Math.PI * 0.5, 0, 0 ) ); + break; + + case 'posZ': + targetPosition.set( 0, 0, 1 ); + targetQuaternion.setFromEuler( new Euler() ); + break; + + case 'negX': + targetPosition.set( - 1, 0, 0 ); + targetQuaternion.setFromEuler( new Euler( 0, - Math.PI * 0.5, 0 ) ); + break; + + case 'negY': + targetPosition.set( 0, - 1, 0 ); + targetQuaternion.setFromEuler( new Euler( Math.PI * 0.5, 0, 0 ) ); + break; + + case 'negZ': + targetPosition.set( 0, 0, - 1 ); + targetQuaternion.setFromEuler( new Euler( 0, Math.PI, 0 ) ); + break; + + default: + console.error( 'ViewHelper: Invalid axis.' ); + + } + + // + + radius = camera.position.distanceTo( focusPoint ); + targetPosition.multiplyScalar( radius ).add( focusPoint ); + + dummy.position.copy( focusPoint ); + + dummy.lookAt( camera.position ); + q1.copy( dummy.quaternion ); + + dummy.lookAt( targetPosition ); + q2.copy( dummy.quaternion ); + + } + + function getAxisMaterial( color ) { + + return new MeshBasicMaterial( { color: color, toneMapped: false } ); + + } + + function getSpriteMaterial( color, text = null ) { + + const canvas = document.createElement( 'canvas' ); + canvas.width = 64; + canvas.height = 64; + + const context = canvas.getContext( '2d' ); + context.beginPath(); + context.arc( 32, 32, 16, 0, 2 * Math.PI ); + context.closePath(); + context.fillStyle = color.getStyle(); + context.fill(); + + if ( text !== null ) { + + context.font = '24px Arial'; + context.textAlign = 'center'; + context.fillStyle = '#000000'; + context.fillText( text, 32, 41 ); + + } + + const texture = new CanvasTexture( canvas ); + + return new SpriteMaterial( { map: texture, toneMapped: false } ); + + } + + } + +} + +export { ViewHelper }; diff --git a/renderer/jsm/interactive/HTMLMesh.js b/renderer/jsm/interactive/HTMLMesh.js new file mode 100644 index 0000000..af093bc --- /dev/null +++ b/renderer/jsm/interactive/HTMLMesh.js @@ -0,0 +1,552 @@ +import { + CanvasTexture, + LinearFilter, + Mesh, + MeshBasicMaterial, + PlaneGeometry, + sRGBEncoding, + Color +} from 'three'; + +class HTMLMesh extends Mesh { + + constructor( dom ) { + + const texture = new HTMLTexture( dom ); + + const geometry = new PlaneGeometry( texture.image.width * 0.001, texture.image.height * 0.001 ); + const material = new MeshBasicMaterial( { map: texture, toneMapped: false, transparent: true } ); + + super( geometry, material ); + + function onEvent( event ) { + + material.map.dispatchDOMEvent( event ); + + } + + this.addEventListener( 'mousedown', onEvent ); + this.addEventListener( 'mousemove', onEvent ); + this.addEventListener( 'mouseup', onEvent ); + this.addEventListener( 'click', onEvent ); + + this.dispose = function () { + + geometry.dispose(); + material.dispose(); + + material.map.dispose(); + + canvases.delete( dom ); + + this.removeEventListener( 'mousedown', onEvent ); + this.removeEventListener( 'mousemove', onEvent ); + this.removeEventListener( 'mouseup', onEvent ); + this.removeEventListener( 'click', onEvent ); + + }; + + } + +} + +class HTMLTexture extends CanvasTexture { + + constructor( dom ) { + + super( html2canvas( dom ) ); + + this.dom = dom; + + this.anisotropy = 16; + this.encoding = sRGBEncoding; + this.minFilter = LinearFilter; + this.magFilter = LinearFilter; + + // Create an observer on the DOM, and run html2canvas update in the next loop + const observer = new MutationObserver( () => { + + if ( ! this.scheduleUpdate ) { + + // ideally should use xr.requestAnimationFrame, here setTimeout to avoid passing the renderer + this.scheduleUpdate = setTimeout( () => this.update(), 16 ); + + } + + } ); + + const config = { attributes: true, childList: true, subtree: true, characterData: true }; + observer.observe( dom, config ); + + this.observer = observer; + + } + + dispatchDOMEvent( event ) { + + if ( event.data ) { + + htmlevent( this.dom, event.type, event.data.x, event.data.y ); + + } + + } + + update() { + + this.image = html2canvas( this.dom ); + this.needsUpdate = true; + + this.scheduleUpdate = null; + + } + + dispose() { + + if ( this.observer ) { + + this.observer.disconnect(); + + } + + this.scheduleUpdate = clearTimeout( this.scheduleUpdate ); + + super.dispose(); + + } + +} + + +// + +const canvases = new WeakMap(); + +function html2canvas( element ) { + + const range = document.createRange(); + const color = new Color(); + + function Clipper( context ) { + + const clips = []; + let isClipping = false; + + function doClip() { + + if ( isClipping ) { + + isClipping = false; + context.restore(); + + } + + if ( clips.length === 0 ) return; + + let minX = - Infinity, minY = - Infinity; + let maxX = Infinity, maxY = Infinity; + + for ( let i = 0; i < clips.length; i ++ ) { + + const clip = clips[ i ]; + + minX = Math.max( minX, clip.x ); + minY = Math.max( minY, clip.y ); + maxX = Math.min( maxX, clip.x + clip.width ); + maxY = Math.min( maxY, clip.y + clip.height ); + + } + + context.save(); + context.beginPath(); + context.rect( minX, minY, maxX - minX, maxY - minY ); + context.clip(); + + isClipping = true; + + } + + return { + + add: function ( clip ) { + + clips.push( clip ); + doClip(); + + }, + + remove: function () { + + clips.pop(); + doClip(); + + } + + }; + + } + + function drawText( style, x, y, string ) { + + if ( string !== '' ) { + + if ( style.textTransform === 'uppercase' ) { + + string = string.toUpperCase(); + + } + + context.font = style.fontWeight + ' ' + style.fontSize + ' ' + style.fontFamily; + context.textBaseline = 'top'; + context.fillStyle = style.color; + context.fillText( string, x, y + parseFloat( style.fontSize ) * 0.1 ); + + } + + } + + function buildRectPath( x, y, w, h, r ) { + + if ( w < 2 * r ) r = w / 2; + if ( h < 2 * r ) r = h / 2; + + context.beginPath(); + context.moveTo( x + r, y ); + context.arcTo( x + w, y, x + w, y + h, r ); + context.arcTo( x + w, y + h, x, y + h, r ); + context.arcTo( x, y + h, x, y, r ); + context.arcTo( x, y, x + w, y, r ); + context.closePath(); + + } + + function drawBorder( style, which, x, y, width, height ) { + + const borderWidth = style[ which + 'Width' ]; + const borderStyle = style[ which + 'Style' ]; + const borderColor = style[ which + 'Color' ]; + + if ( borderWidth !== '0px' && borderStyle !== 'none' && borderColor !== 'transparent' && borderColor !== 'rgba(0, 0, 0, 0)' ) { + + context.strokeStyle = borderColor; + context.lineWidth = parseFloat( borderWidth ); + context.beginPath(); + context.moveTo( x, y ); + context.lineTo( x + width, y + height ); + context.stroke(); + + } + + } + + function drawElement( element, style ) { + + let x = 0, y = 0, width = 0, height = 0; + + if ( element.nodeType === Node.TEXT_NODE ) { + + // text + + range.selectNode( element ); + + const rect = range.getBoundingClientRect(); + + x = rect.left - offset.left - 0.5; + y = rect.top - offset.top - 0.5; + width = rect.width; + height = rect.height; + + drawText( style, x, y, element.nodeValue.trim() ); + + } else if ( element.nodeType === Node.COMMENT_NODE ) { + + return; + + } else if ( element instanceof HTMLCanvasElement ) { + + // Canvas element + if ( element.style.display === 'none' ) return; + + context.save(); + const dpr = window.devicePixelRatio; + context.scale( 1 / dpr, 1 / dpr ); + context.drawImage( element, 0, 0 ); + context.restore(); + + } else { + + if ( element.style.display === 'none' ) return; + + const rect = element.getBoundingClientRect(); + + x = rect.left - offset.left - 0.5; + y = rect.top - offset.top - 0.5; + width = rect.width; + height = rect.height; + + style = window.getComputedStyle( element ); + + // Get the border of the element used for fill and border + + buildRectPath( x, y, width, height, parseFloat( style.borderRadius ) ); + + const backgroundColor = style.backgroundColor; + + if ( backgroundColor !== 'transparent' && backgroundColor !== 'rgba(0, 0, 0, 0)' ) { + + context.fillStyle = backgroundColor; + context.fill(); + + } + + // If all the borders match then stroke the round rectangle + + const borders = [ 'borderTop', 'borderLeft', 'borderBottom', 'borderRight' ]; + + let match = true; + let prevBorder = null; + + for ( const border of borders ) { + + if ( prevBorder !== null ) { + + match = ( style[ border + 'Width' ] === style[ prevBorder + 'Width' ] ) && + ( style[ border + 'Color' ] === style[ prevBorder + 'Color' ] ) && + ( style[ border + 'Style' ] === style[ prevBorder + 'Style' ] ); + + } + + if ( match === false ) break; + + prevBorder = border; + + } + + if ( match === true ) { + + // They all match so stroke the rectangle from before allows for border-radius + + const width = parseFloat( style.borderTopWidth ); + + if ( style.borderTopWidth !== '0px' && style.borderTopStyle !== 'none' && style.borderTopColor !== 'transparent' && style.borderTopColor !== 'rgba(0, 0, 0, 0)' ) { + + context.strokeStyle = style.borderTopColor; + context.lineWidth = width; + context.stroke(); + + } + + } else { + + // Otherwise draw individual borders + + drawBorder( style, 'borderTop', x, y, width, 0 ); + drawBorder( style, 'borderLeft', x, y, 0, height ); + drawBorder( style, 'borderBottom', x, y + height, width, 0 ); + drawBorder( style, 'borderRight', x + width, y, 0, height ); + + } + + if ( element instanceof HTMLInputElement ) { + + let accentColor = style.accentColor; + + if ( accentColor === undefined || accentColor === 'auto' ) accentColor = style.color; + + color.set( accentColor ); + + const luminance = Math.sqrt( 0.299 * ( color.r ** 2 ) + 0.587 * ( color.g ** 2 ) + 0.114 * ( color.b ** 2 ) ); + const accentTextColor = luminance < 0.5 ? 'white' : '#111111'; + + if ( element.type === 'radio' ) { + + buildRectPath( x, y, width, height, height ); + + context.fillStyle = 'white'; + context.strokeStyle = accentColor; + context.lineWidth = 1; + context.fill(); + context.stroke(); + + if ( element.checked ) { + + buildRectPath( x + 2, y + 2, width - 4, height - 4, height ); + + context.fillStyle = accentColor; + context.strokeStyle = accentTextColor; + context.lineWidth = 2; + context.fill(); + context.stroke(); + + } + + } + + if ( element.type === 'checkbox' ) { + + buildRectPath( x, y, width, height, 2 ); + + context.fillStyle = element.checked ? accentColor : 'white'; + context.strokeStyle = element.checked ? accentTextColor : accentColor; + context.lineWidth = 1; + context.stroke(); + context.fill(); + + if ( element.checked ) { + + const currentTextAlign = context.textAlign; + + context.textAlign = 'center'; + + const properties = { + color: accentTextColor, + fontFamily: style.fontFamily, + fontSize: height + 'px', + fontWeight: 'bold' + }; + + drawText( properties, x + ( width / 2 ), y, '✔' ); + + context.textAlign = currentTextAlign; + + } + + } + + if ( element.type === 'range' ) { + + const [ min, max, value ] = [ 'min', 'max', 'value' ].map( property => parseFloat( element[ property ] ) ); + const position = ( ( value - min ) / ( max - min ) ) * ( width - height ); + + buildRectPath( x, y + ( height / 4 ), width, height / 2, height / 4 ); + context.fillStyle = accentTextColor; + context.strokeStyle = accentColor; + context.lineWidth = 1; + context.fill(); + context.stroke(); + + buildRectPath( x, y + ( height / 4 ), position + ( height / 2 ), height / 2, height / 4 ); + context.fillStyle = accentColor; + context.fill(); + + buildRectPath( x + position, y, height, height, height / 2 ); + context.fillStyle = accentColor; + context.fill(); + + } + + if ( element.type === 'color' || element.type === 'text' || element.type === 'number' ) { + + clipper.add( { x: x, y: y, width: width, height: height } ); + + drawText( style, x + parseInt( style.paddingLeft ), y + parseInt( style.paddingTop ), element.value ); + + clipper.remove(); + + } + + } + + } + + /* + // debug + context.strokeStyle = '#' + Math.random().toString( 16 ).slice( - 3 ); + context.strokeRect( x - 0.5, y - 0.5, width + 1, height + 1 ); + */ + + const isClipping = style.overflow === 'auto' || style.overflow === 'hidden'; + + if ( isClipping ) clipper.add( { x: x, y: y, width: width, height: height } ); + + for ( let i = 0; i < element.childNodes.length; i ++ ) { + + drawElement( element.childNodes[ i ], style ); + + } + + if ( isClipping ) clipper.remove(); + + } + + const offset = element.getBoundingClientRect(); + + let canvas = canvases.get( element ); + + if ( canvas === undefined ) { + + canvas = document.createElement( 'canvas' ); + canvas.width = offset.width; + canvas.height = offset.height; + canvases.set( element, canvas ); + + } + + const context = canvas.getContext( '2d'/*, { alpha: false }*/ ); + + const clipper = new Clipper( context ); + + // console.time( 'drawElement' ); + + drawElement( element ); + + // console.timeEnd( 'drawElement' ); + + return canvas; + +} + +function htmlevent( element, event, x, y ) { + + const mouseEventInit = { + clientX: ( x * element.offsetWidth ) + element.offsetLeft, + clientY: ( y * element.offsetHeight ) + element.offsetTop, + view: element.ownerDocument.defaultView + }; + + window.dispatchEvent( new MouseEvent( event, mouseEventInit ) ); + + const rect = element.getBoundingClientRect(); + + x = x * rect.width + rect.left; + y = y * rect.height + rect.top; + + function traverse( element ) { + + if ( element.nodeType !== Node.TEXT_NODE && element.nodeType !== Node.COMMENT_NODE ) { + + const rect = element.getBoundingClientRect(); + + if ( x > rect.left && x < rect.right && y > rect.top && y < rect.bottom ) { + + element.dispatchEvent( new MouseEvent( event, mouseEventInit ) ); + + if ( element instanceof HTMLInputElement && element.type === 'range' && ( event === 'mousedown' || event === 'click' ) ) { + + const [ min, max ] = [ 'min', 'max' ].map( property => parseFloat( element[ property ] ) ); + + const width = rect.width; + const offsetX = x - rect.x; + const proportion = offsetX / width; + element.value = min + ( max - min ) * proportion; + element.dispatchEvent( new InputEvent( 'input', { bubbles: true } ) ); + + } + + } + + for ( let i = 0; i < element.childNodes.length; i ++ ) { + + traverse( element.childNodes[ i ] ); + + } + + } + + } + + traverse( element ); + +} + +export { HTMLMesh }; diff --git a/renderer/jsm/interactive/InteractiveGroup.js b/renderer/jsm/interactive/InteractiveGroup.js new file mode 100644 index 0000000..a8d7b30 --- /dev/null +++ b/renderer/jsm/interactive/InteractiveGroup.js @@ -0,0 +1,116 @@ +import { + Group, + Matrix4, + Raycaster, + Vector2 +} from 'three'; + +const _pointer = new Vector2(); +const _event = { type: '', data: _pointer }; + +class InteractiveGroup extends Group { + + constructor( renderer, camera ) { + + super(); + + const scope = this; + + const raycaster = new Raycaster(); + const tempMatrix = new Matrix4(); + + // Pointer Events + + const element = renderer.domElement; + + function onPointerEvent( event ) { + + event.stopPropagation(); + + const rect = renderer.domElement.getBoundingClientRect(); + + _pointer.x = ( event.clientX - rect.left ) / rect.width * 2 - 1; + _pointer.y = - ( event.clientY - rect.top ) / rect.height * 2 + 1; + + raycaster.setFromCamera( _pointer, camera ); + + const intersects = raycaster.intersectObjects( scope.children, false ); + + if ( intersects.length > 0 ) { + + const intersection = intersects[ 0 ]; + + const object = intersection.object; + const uv = intersection.uv; + + _event.type = event.type; + _event.data.set( uv.x, 1 - uv.y ); + + object.dispatchEvent( _event ); + + } + + } + + element.addEventListener( 'pointerdown', onPointerEvent ); + element.addEventListener( 'pointerup', onPointerEvent ); + element.addEventListener( 'pointermove', onPointerEvent ); + element.addEventListener( 'mousedown', onPointerEvent ); + element.addEventListener( 'mouseup', onPointerEvent ); + element.addEventListener( 'mousemove', onPointerEvent ); + element.addEventListener( 'click', onPointerEvent ); + + // WebXR Controller Events + // TODO: Dispatch pointerevents too + + const events = { + 'move': 'mousemove', + 'select': 'click', + 'selectstart': 'mousedown', + 'selectend': 'mouseup' + }; + + function onXRControllerEvent( event ) { + + const controller = event.target; + + tempMatrix.identity().extractRotation( controller.matrixWorld ); + + raycaster.ray.origin.setFromMatrixPosition( controller.matrixWorld ); + raycaster.ray.direction.set( 0, 0, - 1 ).applyMatrix4( tempMatrix ); + + const intersections = raycaster.intersectObjects( scope.children, false ); + + if ( intersections.length > 0 ) { + + const intersection = intersections[ 0 ]; + + const object = intersection.object; + const uv = intersection.uv; + + _event.type = events[ event.type ]; + _event.data.set( uv.x, 1 - uv.y ); + + object.dispatchEvent( _event ); + + } + + } + + const controller1 = renderer.xr.getController( 0 ); + controller1.addEventListener( 'move', onXRControllerEvent ); + controller1.addEventListener( 'select', onXRControllerEvent ); + controller1.addEventListener( 'selectstart', onXRControllerEvent ); + controller1.addEventListener( 'selectend', onXRControllerEvent ); + + const controller2 = renderer.xr.getController( 1 ); + controller2.addEventListener( 'move', onXRControllerEvent ); + controller2.addEventListener( 'select', onXRControllerEvent ); + controller2.addEventListener( 'selectstart', onXRControllerEvent ); + controller2.addEventListener( 'selectend', onXRControllerEvent ); + + } + +} + +export { InteractiveGroup }; diff --git a/renderer/jsm/interactive/SelectionBox.js b/renderer/jsm/interactive/SelectionBox.js new file mode 100644 index 0000000..597b9b2 --- /dev/null +++ b/renderer/jsm/interactive/SelectionBox.js @@ -0,0 +1,227 @@ +import { + Frustum, + Vector3, + Matrix4, + Quaternion, +} from 'three'; + +/** + * This is a class to check whether objects are in a selection area in 3D space + */ + +const _frustum = new Frustum(); +const _center = new Vector3(); + +const _tmpPoint = new Vector3(); + +const _vecNear = new Vector3(); +const _vecTopLeft = new Vector3(); +const _vecTopRight = new Vector3(); +const _vecDownRight = new Vector3(); +const _vecDownLeft = new Vector3(); + +const _vecFarTopLeft = new Vector3(); +const _vecFarTopRight = new Vector3(); +const _vecFarDownRight = new Vector3(); +const _vecFarDownLeft = new Vector3(); + +const _vectemp1 = new Vector3(); +const _vectemp2 = new Vector3(); +const _vectemp3 = new Vector3(); + +const _matrix = new Matrix4(); +const _quaternion = new Quaternion(); +const _scale = new Vector3(); + +class SelectionBox { + + constructor( camera, scene, deep = Number.MAX_VALUE ) { + + this.camera = camera; + this.scene = scene; + this.startPoint = new Vector3(); + this.endPoint = new Vector3(); + this.collection = []; + this.instances = {}; + this.deep = deep; + + } + + select( startPoint, endPoint ) { + + this.startPoint = startPoint || this.startPoint; + this.endPoint = endPoint || this.endPoint; + this.collection = []; + + this.updateFrustum( this.startPoint, this.endPoint ); + this.searchChildInFrustum( _frustum, this.scene ); + + return this.collection; + + } + + updateFrustum( startPoint, endPoint ) { + + startPoint = startPoint || this.startPoint; + endPoint = endPoint || this.endPoint; + + // Avoid invalid frustum + + if ( startPoint.x === endPoint.x ) { + + endPoint.x += Number.EPSILON; + + } + + if ( startPoint.y === endPoint.y ) { + + endPoint.y += Number.EPSILON; + + } + + this.camera.updateProjectionMatrix(); + this.camera.updateMatrixWorld(); + + if ( this.camera.isPerspectiveCamera ) { + + _tmpPoint.copy( startPoint ); + _tmpPoint.x = Math.min( startPoint.x, endPoint.x ); + _tmpPoint.y = Math.max( startPoint.y, endPoint.y ); + endPoint.x = Math.max( startPoint.x, endPoint.x ); + endPoint.y = Math.min( startPoint.y, endPoint.y ); + + _vecNear.setFromMatrixPosition( this.camera.matrixWorld ); + _vecTopLeft.copy( _tmpPoint ); + _vecTopRight.set( endPoint.x, _tmpPoint.y, 0 ); + _vecDownRight.copy( endPoint ); + _vecDownLeft.set( _tmpPoint.x, endPoint.y, 0 ); + + _vecTopLeft.unproject( this.camera ); + _vecTopRight.unproject( this.camera ); + _vecDownRight.unproject( this.camera ); + _vecDownLeft.unproject( this.camera ); + + _vectemp1.copy( _vecTopLeft ).sub( _vecNear ); + _vectemp2.copy( _vecTopRight ).sub( _vecNear ); + _vectemp3.copy( _vecDownRight ).sub( _vecNear ); + _vectemp1.normalize(); + _vectemp2.normalize(); + _vectemp3.normalize(); + + _vectemp1.multiplyScalar( this.deep ); + _vectemp2.multiplyScalar( this.deep ); + _vectemp3.multiplyScalar( this.deep ); + _vectemp1.add( _vecNear ); + _vectemp2.add( _vecNear ); + _vectemp3.add( _vecNear ); + + const planes = _frustum.planes; + + planes[ 0 ].setFromCoplanarPoints( _vecNear, _vecTopLeft, _vecTopRight ); + planes[ 1 ].setFromCoplanarPoints( _vecNear, _vecTopRight, _vecDownRight ); + planes[ 2 ].setFromCoplanarPoints( _vecDownRight, _vecDownLeft, _vecNear ); + planes[ 3 ].setFromCoplanarPoints( _vecDownLeft, _vecTopLeft, _vecNear ); + planes[ 4 ].setFromCoplanarPoints( _vecTopRight, _vecDownRight, _vecDownLeft ); + planes[ 5 ].setFromCoplanarPoints( _vectemp3, _vectemp2, _vectemp1 ); + planes[ 5 ].normal.multiplyScalar( - 1 ); + + } else if ( this.camera.isOrthographicCamera ) { + + const left = Math.min( startPoint.x, endPoint.x ); + const top = Math.max( startPoint.y, endPoint.y ); + const right = Math.max( startPoint.x, endPoint.x ); + const down = Math.min( startPoint.y, endPoint.y ); + + _vecTopLeft.set( left, top, - 1 ); + _vecTopRight.set( right, top, - 1 ); + _vecDownRight.set( right, down, - 1 ); + _vecDownLeft.set( left, down, - 1 ); + + _vecFarTopLeft.set( left, top, 1 ); + _vecFarTopRight.set( right, top, 1 ); + _vecFarDownRight.set( right, down, 1 ); + _vecFarDownLeft.set( left, down, 1 ); + + _vecTopLeft.unproject( this.camera ); + _vecTopRight.unproject( this.camera ); + _vecDownRight.unproject( this.camera ); + _vecDownLeft.unproject( this.camera ); + + _vecFarTopLeft.unproject( this.camera ); + _vecFarTopRight.unproject( this.camera ); + _vecFarDownRight.unproject( this.camera ); + _vecFarDownLeft.unproject( this.camera ); + + const planes = _frustum.planes; + + planes[ 0 ].setFromCoplanarPoints( _vecTopLeft, _vecFarTopLeft, _vecFarTopRight ); + planes[ 1 ].setFromCoplanarPoints( _vecTopRight, _vecFarTopRight, _vecFarDownRight ); + planes[ 2 ].setFromCoplanarPoints( _vecFarDownRight, _vecFarDownLeft, _vecDownLeft ); + planes[ 3 ].setFromCoplanarPoints( _vecFarDownLeft, _vecFarTopLeft, _vecTopLeft ); + planes[ 4 ].setFromCoplanarPoints( _vecTopRight, _vecDownRight, _vecDownLeft ); + planes[ 5 ].setFromCoplanarPoints( _vecFarDownRight, _vecFarTopRight, _vecFarTopLeft ); + planes[ 5 ].normal.multiplyScalar( - 1 ); + + } else { + + console.error( 'THREE.SelectionBox: Unsupported camera type.' ); + + } + + } + + searchChildInFrustum( frustum, object ) { + + if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( object.isInstancedMesh ) { + + this.instances[ object.uuid ] = []; + + for ( let instanceId = 0; instanceId < object.count; instanceId ++ ) { + + object.getMatrixAt( instanceId, _matrix ); + _matrix.decompose( _center, _quaternion, _scale ); + _center.applyMatrix4( object.matrixWorld ); + + if ( frustum.containsPoint( _center ) ) { + + this.instances[ object.uuid ].push( instanceId ); + + } + + } + + } else { + + if ( object.geometry.boundingSphere === null ) object.geometry.computeBoundingSphere(); + + _center.copy( object.geometry.boundingSphere.center ); + + _center.applyMatrix4( object.matrixWorld ); + + if ( frustum.containsPoint( _center ) ) { + + this.collection.push( object ); + + } + + } + + } + + if ( object.children.length > 0 ) { + + for ( let x = 0; x < object.children.length; x ++ ) { + + this.searchChildInFrustum( frustum, object.children[ x ] ); + + } + + } + + } + +} + +export { SelectionBox }; diff --git a/renderer/jsm/interactive/SelectionHelper.js b/renderer/jsm/interactive/SelectionHelper.js new file mode 100644 index 0000000..cfa5422 --- /dev/null +++ b/renderer/jsm/interactive/SelectionHelper.js @@ -0,0 +1,97 @@ +import { Vector2 } from 'three'; + +class SelectionHelper { + + constructor( renderer, cssClassName ) { + + this.element = document.createElement( 'div' ); + this.element.classList.add( cssClassName ); + this.element.style.pointerEvents = 'none'; + + this.renderer = renderer; + + this.startPoint = new Vector2(); + this.pointTopLeft = new Vector2(); + this.pointBottomRight = new Vector2(); + + this.isDown = false; + + this.onPointerDown = function ( event ) { + + this.isDown = true; + this.onSelectStart( event ); + + }.bind( this ); + + this.onPointerMove = function ( event ) { + + if ( this.isDown ) { + + this.onSelectMove( event ); + + } + + }.bind( this ); + + this.onPointerUp = function ( ) { + + this.isDown = false; + this.onSelectOver(); + + }.bind( this ); + + this.renderer.domElement.addEventListener( 'pointerdown', this.onPointerDown ); + this.renderer.domElement.addEventListener( 'pointermove', this.onPointerMove ); + this.renderer.domElement.addEventListener( 'pointerup', this.onPointerUp ); + + } + + dispose() { + + this.renderer.domElement.removeEventListener( 'pointerdown', this.onPointerDown ); + this.renderer.domElement.removeEventListener( 'pointermove', this.onPointerMove ); + this.renderer.domElement.removeEventListener( 'pointerup', this.onPointerUp ); + + } + + onSelectStart( event ) { + + this.element.style.display = 'none'; + + this.renderer.domElement.parentElement.appendChild( this.element ); + + this.element.style.left = event.clientX + 'px'; + this.element.style.top = event.clientY + 'px'; + this.element.style.width = '0px'; + this.element.style.height = '0px'; + + this.startPoint.x = event.clientX; + this.startPoint.y = event.clientY; + + } + + onSelectMove( event ) { + + this.element.style.display = 'block'; + + this.pointBottomRight.x = Math.max( this.startPoint.x, event.clientX ); + this.pointBottomRight.y = Math.max( this.startPoint.y, event.clientY ); + this.pointTopLeft.x = Math.min( this.startPoint.x, event.clientX ); + this.pointTopLeft.y = Math.min( this.startPoint.y, event.clientY ); + + this.element.style.left = this.pointTopLeft.x + 'px'; + this.element.style.top = this.pointTopLeft.y + 'px'; + this.element.style.width = ( this.pointBottomRight.x - this.pointTopLeft.x ) + 'px'; + this.element.style.height = ( this.pointBottomRight.y - this.pointTopLeft.y ) + 'px'; + + } + + onSelectOver() { + + this.element.parentElement.removeChild( this.element ); + + } + +} + +export { SelectionHelper }; diff --git a/renderer/jsm/libs/OimoPhysics/OimoPhysics.js b/renderer/jsm/libs/OimoPhysics/OimoPhysics.js new file mode 100644 index 0000000..3c4eb49 --- /dev/null +++ b/renderer/jsm/libs/OimoPhysics/OimoPhysics.js @@ -0,0 +1,37071 @@ +// Generated by Haxe 4.2.0 +var oimo = oimo || {}; +if(!oimo.collision) oimo.collision = {}; +if(!oimo.collision.broadphase) oimo.collision.broadphase = {}; +oimo.collision.broadphase.BroadPhase = class oimo_collision_broadphase_BroadPhase { + constructor(type) { + this._type = type; + this._numProxies = 0; + this._proxyList = null; + this._proxyListLast = null; + this._proxyPairList = null; + this._incremental = false; + this._testCount = 0; + this._proxyPairPool = null; + this._idCount = 0; + this._convexSweep = new oimo.collision.broadphase._BroadPhase.ConvexSweepGeometry(); + this._aabb = new oimo.collision.broadphase._BroadPhase.AabbGeometry(); + this.identity = new oimo.common.Transform(); + this.zero = new oimo.common.Vec3(); + this.rayCastHit = new oimo.collision.geometry.RayCastHit(); + } + createProxy(userData,aabb) { + return null; + } + destroyProxy(proxy) { + } + moveProxy(proxy,aabb,displacement) { + } + isOverlapping(proxy1,proxy2) { + if(proxy1._aabbMinX < proxy2._aabbMaxX && proxy1._aabbMaxX > proxy2._aabbMinX && proxy1._aabbMinY < proxy2._aabbMaxY && proxy1._aabbMaxY > proxy2._aabbMinY && proxy1._aabbMinZ < proxy2._aabbMaxZ) { + return proxy1._aabbMaxZ > proxy2._aabbMinZ; + } else { + return false; + } + } + collectPairs() { + } + getProxyPairList() { + return this._proxyPairList; + } + isIncremental() { + return this._incremental; + } + getTestCount() { + return this._testCount; + } + rayCast(begin,end,callback) { + } + convexCast(convex,begin,translation,callback) { + } + aabbTest(aabb,callback) { + } +} +if(!oimo.collision.geometry) oimo.collision.geometry = {}; +oimo.collision.geometry.Geometry = class oimo_collision_geometry_Geometry { + constructor(type) { + this._type = type; + this._volume = 0; + } + _updateMass() { + } + _computeAabb(aabb,tf) { + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + return false; + } + getType() { + return this._type; + } + getVolume() { + return this._volume; + } + rayCast(begin,end,transform,hit) { + let beginLocalX; + let beginLocalY; + let beginLocalZ; + let endLocalX; + let endLocalY; + let endLocalZ; + beginLocalX = begin.x; + beginLocalY = begin.y; + beginLocalZ = begin.z; + endLocalX = end.x; + endLocalY = end.y; + endLocalZ = end.z; + beginLocalX -= transform._positionX; + beginLocalY -= transform._positionY; + beginLocalZ -= transform._positionZ; + endLocalX -= transform._positionX; + endLocalY -= transform._positionY; + endLocalZ -= transform._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = transform._rotation00 * beginLocalX + transform._rotation10 * beginLocalY + transform._rotation20 * beginLocalZ; + __tmp__Y = transform._rotation01 * beginLocalX + transform._rotation11 * beginLocalY + transform._rotation21 * beginLocalZ; + __tmp__Z = transform._rotation02 * beginLocalX + transform._rotation12 * beginLocalY + transform._rotation22 * beginLocalZ; + beginLocalX = __tmp__X; + beginLocalY = __tmp__Y; + beginLocalZ = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = transform._rotation00 * endLocalX + transform._rotation10 * endLocalY + transform._rotation20 * endLocalZ; + __tmp__Y1 = transform._rotation01 * endLocalX + transform._rotation11 * endLocalY + transform._rotation21 * endLocalZ; + __tmp__Z1 = transform._rotation02 * endLocalX + transform._rotation12 * endLocalY + transform._rotation22 * endLocalZ; + endLocalX = __tmp__X1; + endLocalY = __tmp__Y1; + endLocalZ = __tmp__Z1; + if(this._rayCastLocal(beginLocalX,beginLocalY,beginLocalZ,endLocalX,endLocalY,endLocalZ,hit)) { + let localPosX; + let localPosY; + let localPosZ; + let localNormalX; + let localNormalY; + let localNormalZ; + let v = hit.position; + localPosX = v.x; + localPosY = v.y; + localPosZ = v.z; + let v1 = hit.normal; + localNormalX = v1.x; + localNormalY = v1.y; + localNormalZ = v1.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = transform._rotation00 * localPosX + transform._rotation01 * localPosY + transform._rotation02 * localPosZ; + __tmp__Y = transform._rotation10 * localPosX + transform._rotation11 * localPosY + transform._rotation12 * localPosZ; + __tmp__Z = transform._rotation20 * localPosX + transform._rotation21 * localPosY + transform._rotation22 * localPosZ; + localPosX = __tmp__X; + localPosY = __tmp__Y; + localPosZ = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = transform._rotation00 * localNormalX + transform._rotation01 * localNormalY + transform._rotation02 * localNormalZ; + __tmp__Y1 = transform._rotation10 * localNormalX + transform._rotation11 * localNormalY + transform._rotation12 * localNormalZ; + __tmp__Z1 = transform._rotation20 * localNormalX + transform._rotation21 * localNormalY + transform._rotation22 * localNormalZ; + localNormalX = __tmp__X1; + localNormalY = __tmp__Y1; + localNormalZ = __tmp__Z1; + localPosX += transform._positionX; + localPosY += transform._positionY; + localPosZ += transform._positionZ; + let v2 = hit.position; + v2.x = localPosX; + v2.y = localPosY; + v2.z = localPosZ; + let v3 = hit.normal; + v3.x = localNormalX; + v3.y = localNormalY; + v3.z = localNormalZ; + return true; + } + return false; + } +} +oimo.collision.geometry.ConvexGeometry = class oimo_collision_geometry_ConvexGeometry extends oimo.collision.geometry.Geometry { + constructor(type) { + super(type); + this._gjkMargin = oimo.common.Setting.defaultGJKMargin; + this._useGjkRayCast = false; + } + getGjkMergin() { + return this._gjkMargin; + } + setGjkMergin(gjkMergin) { + if(gjkMergin < 0) { + gjkMergin = 0; + } + this._gjkMargin = gjkMergin; + } + computeLocalSupportingVertex(dir,out) { + } + rayCast(begin,end,transform,hit) { + if(this._useGjkRayCast) { + return oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance.rayCast(this,transform,begin,end,hit); + } else { + return super.rayCast(begin,end,transform,hit); + } + } +} +if(!oimo.collision.broadphase._BroadPhase) oimo.collision.broadphase._BroadPhase = {}; +oimo.collision.broadphase._BroadPhase.ConvexSweepGeometry = class oimo_collision_broadphase__$BroadPhase_ConvexSweepGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor() { + super(-1); + } + init(c,transform,translation) { + this.c = c; + let trX; + let trY; + let trZ; + trX = translation.x; + trY = translation.y; + trZ = translation.z; + let localTrX; + let localTrY; + let localTrZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = transform._rotation00 * trX + transform._rotation10 * trY + transform._rotation20 * trZ; + __tmp__Y = transform._rotation01 * trX + transform._rotation11 * trY + transform._rotation21 * trZ; + __tmp__Z = transform._rotation02 * trX + transform._rotation12 * trY + transform._rotation22 * trZ; + localTrX = __tmp__X; + localTrY = __tmp__Y; + localTrZ = __tmp__Z; + this.localTranslation = new oimo.common.Vec3(); + let v = this.localTranslation; + v.x = localTrX; + v.y = localTrY; + v.z = localTrZ; + this._gjkMargin = c._gjkMargin; + } + computeLocalSupportingVertex(dir,out) { + this.c.computeLocalSupportingVertex(dir,out); + let v = this.localTranslation; + if(dir.x * v.x + dir.y * v.y + dir.z * v.z > 0) { + let v = this.localTranslation; + out.x += v.x; + out.y += v.y; + out.z += v.z; + } + } +} +oimo.collision.broadphase._BroadPhase.AabbGeometry = class oimo_collision_broadphase__$BroadPhase_AabbGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor() { + super(-1); + this.min = new oimo.common.Vec3(); + this.max = new oimo.common.Vec3(); + } + computeLocalSupportingVertex(dir,out) { + out.x = dir.x > 0 ? this.max.x : this.min.x; + out.y = dir.y > 0 ? this.max.y : this.min.y; + out.z = dir.z > 0 ? this.max.z : this.min.z; + } +} +oimo.collision.broadphase.BroadPhaseProxyCallback = class oimo_collision_broadphase_BroadPhaseProxyCallback { + constructor() { + } + process(proxy) { + } +} +oimo.collision.broadphase.BroadPhaseType = class oimo_collision_broadphase_BroadPhaseType { +} +oimo.collision.broadphase.Proxy = class oimo_collision_broadphase_Proxy { + constructor(userData,id) { + this.userData = userData; + this._id = id; + this._prev = null; + this._next = null; + this._aabbMinX = 0; + this._aabbMinY = 0; + this._aabbMinZ = 0; + this._aabbMaxX = 0; + this._aabbMaxY = 0; + this._aabbMaxZ = 0; + } + getId() { + return this._id; + } + getFatAabb() { + let aabb = new oimo.collision.geometry.Aabb(); + aabb._minX = this._aabbMinX; + aabb._minY = this._aabbMinY; + aabb._minZ = this._aabbMinZ; + aabb._maxX = this._aabbMaxX; + aabb._maxY = this._aabbMaxY; + aabb._maxZ = this._aabbMaxZ; + return aabb; + } + getFatAabbTo(aabb) { + aabb._minX = this._aabbMinX; + aabb._minY = this._aabbMinY; + aabb._minZ = this._aabbMinZ; + aabb._maxX = this._aabbMaxX; + aabb._maxY = this._aabbMaxY; + aabb._maxZ = this._aabbMaxZ; + } +} +oimo.collision.broadphase.ProxyPair = class oimo_collision_broadphase_ProxyPair { + constructor() { + this._p1 = null; + this._p2 = null; + } + getProxy1() { + return this._p1; + } + getProxy2() { + return this._p2; + } + getNext() { + return this._next; + } +} +if(!oimo.collision.broadphase.bruteforce) oimo.collision.broadphase.bruteforce = {}; +oimo.collision.broadphase.bruteforce.BruteForceBroadPhase = class oimo_collision_broadphase_bruteforce_BruteForceBroadPhase extends oimo.collision.broadphase.BroadPhase { + constructor() { + super(1); + this._incremental = false; + } + createProxy(userData,aabb) { + let proxy = new oimo.collision.broadphase.Proxy(userData,this._idCount++); + this._numProxies++; + if(this._proxyList == null) { + this._proxyList = proxy; + this._proxyListLast = proxy; + } else { + this._proxyListLast._next = proxy; + proxy._prev = this._proxyListLast; + this._proxyListLast = proxy; + } + proxy._aabbMinX = aabb._minX; + proxy._aabbMinY = aabb._minY; + proxy._aabbMinZ = aabb._minZ; + proxy._aabbMaxX = aabb._maxX; + proxy._aabbMaxY = aabb._maxY; + proxy._aabbMaxZ = aabb._maxZ; + return proxy; + } + destroyProxy(proxy) { + this._numProxies--; + let prev = proxy._prev; + let next = proxy._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(proxy == this._proxyList) { + this._proxyList = this._proxyList._next; + } + if(proxy == this._proxyListLast) { + this._proxyListLast = this._proxyListLast._prev; + } + proxy._next = null; + proxy._prev = null; + proxy.userData = null; + } + moveProxy(proxy,aabb,dislacement) { + proxy._aabbMinX = aabb._minX; + proxy._aabbMinY = aabb._minY; + proxy._aabbMinZ = aabb._minZ; + proxy._aabbMaxX = aabb._maxX; + proxy._aabbMaxY = aabb._maxY; + proxy._aabbMaxZ = aabb._maxZ; + } + collectPairs() { + let p = this._proxyPairList; + if(p != null) { + while(true) { + p._p1 = null; + p._p2 = null; + p = p._next; + if(!(p != null)) { + break; + } + } + this._proxyPairList._next = this._proxyPairPool; + this._proxyPairPool = this._proxyPairList; + this._proxyPairList = null; + } + this._testCount = 0; + let p1 = this._proxyList; + while(p1 != null) { + let n = p1._next; + let p2 = p1._next; + while(p2 != null) { + let n = p2._next; + this._testCount++; + if(p1._aabbMinX < p2._aabbMaxX && p1._aabbMaxX > p2._aabbMinX && p1._aabbMinY < p2._aabbMaxY && p1._aabbMaxY > p2._aabbMinY && p1._aabbMinZ < p2._aabbMaxZ && p1._aabbMaxZ > p2._aabbMinZ) { + let first = this._proxyPairPool; + if(first != null) { + this._proxyPairPool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.ProxyPair(); + } + let pp = first; + if(this._proxyPairList == null) { + this._proxyPairList = pp; + } else { + pp._next = this._proxyPairList; + this._proxyPairList = pp; + } + pp._p1 = p1; + pp._p2 = p2; + } + p2 = n; + } + p1 = n; + } + } + rayCast(begin,end,callback) { + let p1X; + let p1Y; + let p1Z; + let p2X; + let p2Y; + let p2Z; + p1X = begin.x; + p1Y = begin.y; + p1Z = begin.z; + p2X = end.x; + p2Y = end.y; + p2Z = end.z; + let p = this._proxyList; + while(p != null) { + let n = p._next; + let x1 = p1X; + let y1 = p1Y; + let z1 = p1Z; + let x2 = p2X; + let y2 = p2Y; + let z2 = p2Z; + let pminx = p._aabbMinX; + let pminy = p._aabbMinY; + let pminz = p._aabbMinZ; + let pmaxx = p._aabbMaxX; + let pmaxy = p._aabbMaxY; + let pmaxz = p._aabbMaxZ; + let tmp; + if(pminx > (x1 > x2 ? x1 : x2) || pmaxx < (x1 < x2 ? x1 : x2) || pminy > (y1 > y2 ? y1 : y2) || pmaxy < (y1 < y2 ? y1 : y2) || pminz > (z1 > z2 ? z1 : z2) || pmaxz < (z1 < z2 ? z1 : z2)) { + tmp = false; + } else { + let dx = x2 - x1; + let dy = y2 - y1; + let dz = z2 - z1; + let adx = dx < 0 ? -dx : dx; + let ady = dy < 0 ? -dy : dy; + let adz = dz < 0 ? -dz : dz; + let pextx = (pmaxx - pminx) * 0.5; + let pexty = (pmaxy - pminy) * 0.5; + let pextz = (pmaxz - pminz) * 0.5; + let cpx = x1 - (pmaxx + pminx) * 0.5; + let cpy = y1 - (pmaxy + pminy) * 0.5; + let cpz = z1 - (pmaxz + pminz) * 0.5; + let tmp1; + let tmp2; + let x = cpy * dz - cpz * dy; + if(!((x < 0 ? -x : x) - (pexty * adz + pextz * ady) > 0)) { + let x = cpz * dx - cpx * dz; + tmp2 = (x < 0 ? -x : x) - (pextz * adx + pextx * adz) > 0; + } else { + tmp2 = true; + } + if(!tmp2) { + let x = cpx * dy - cpy * dx; + tmp1 = (x < 0 ? -x : x) - (pextx * ady + pexty * adx) > 0; + } else { + tmp1 = true; + } + tmp = tmp1 ? false : true; + } + if(tmp) { + callback.process(p); + } + p = n; + } + } + convexCast(convex,begin,translation,callback) { + let p = this._proxyList; + while(p != null) { + let n = p._next; + let v = this._aabb.min; + v.x = p._aabbMinX; + v.y = p._aabbMinY; + v.z = p._aabbMinZ; + let v1 = this._aabb.max; + v1.x = p._aabbMaxX; + v1.y = p._aabbMaxY; + v1.z = p._aabbMaxZ; + this._convexSweep.init(convex,begin,translation); + let gjkEpa = oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance; + if(gjkEpa.computeClosestPointsImpl(this._convexSweep,this._aabb,begin,this.identity,null,false) == 0 && gjkEpa.distance <= 0) { + callback.process(p); + } + p = n; + } + } + aabbTest(aabb,callback) { + let p = this._proxyList; + while(p != null) { + let n = p._next; + if(aabb._minX < p._aabbMaxX && aabb._maxX > p._aabbMinX && aabb._minY < p._aabbMaxY && aabb._maxY > p._aabbMinY && aabb._minZ < p._aabbMaxZ && aabb._maxZ > p._aabbMinZ) { + callback.process(p); + } + p = n; + } + } +} +if(!oimo.collision.broadphase.bvh) oimo.collision.broadphase.bvh = {}; +oimo.collision.broadphase.bvh.BvhBroadPhase = class oimo_collision_broadphase_bvh_BvhBroadPhase extends oimo.collision.broadphase.BroadPhase { + constructor() { + super(2); + this._incremental = true; + this._tree = new oimo.collision.broadphase.bvh.BvhTree(); + this.movedProxies = new Array(1024); + this.numMovedProxies = 0; + } + collide(n1,n2) { + this._testCount++; + let l1 = n1._height == 0; + let l2 = n2._height == 0; + if(n1 == n2) { + if(l1) { + return; + } + this.collide(n1._children[0],n2); + this.collide(n1._children[1],n2); + return; + } + if(!(n1._aabbMinX < n2._aabbMaxX && n1._aabbMaxX > n2._aabbMinX && n1._aabbMinY < n2._aabbMaxY && n1._aabbMaxY > n2._aabbMinY && n1._aabbMinZ < n2._aabbMaxZ && n1._aabbMaxZ > n2._aabbMinZ)) { + return; + } + if(l1 && l2) { + let first = this._proxyPairPool; + if(first != null) { + this._proxyPairPool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.ProxyPair(); + } + let pp = first; + if(this._proxyPairList == null) { + this._proxyPairList = pp; + } else { + pp._next = this._proxyPairList; + this._proxyPairList = pp; + } + pp._p1 = n1._proxy; + pp._p2 = n2._proxy; + return; + } + if(l2 || n1._height > n2._height) { + this.collide(n1._children[0],n2); + this.collide(n1._children[1],n2); + } else { + this.collide(n2._children[0],n1); + this.collide(n2._children[1],n1); + } + } + rayCastRecursive(node,_p1X,_p1Y,_p1Z,_p2X,_p2Y,_p2Z,callback) { + let x1 = _p1X; + let y1 = _p1Y; + let z1 = _p1Z; + let x2 = _p2X; + let y2 = _p2Y; + let z2 = _p2Z; + let pminx = node._aabbMinX; + let pminy = node._aabbMinY; + let pminz = node._aabbMinZ; + let pmaxx = node._aabbMaxX; + let pmaxy = node._aabbMaxY; + let pmaxz = node._aabbMaxZ; + let tmp; + if(pminx > (x1 > x2 ? x1 : x2) || pmaxx < (x1 < x2 ? x1 : x2) || pminy > (y1 > y2 ? y1 : y2) || pmaxy < (y1 < y2 ? y1 : y2) || pminz > (z1 > z2 ? z1 : z2) || pmaxz < (z1 < z2 ? z1 : z2)) { + tmp = false; + } else { + let dx = x2 - x1; + let dy = y2 - y1; + let dz = z2 - z1; + let adx = dx < 0 ? -dx : dx; + let ady = dy < 0 ? -dy : dy; + let adz = dz < 0 ? -dz : dz; + let pextx = (pmaxx - pminx) * 0.5; + let pexty = (pmaxy - pminy) * 0.5; + let pextz = (pmaxz - pminz) * 0.5; + let cpx = x1 - (pmaxx + pminx) * 0.5; + let cpy = y1 - (pmaxy + pminy) * 0.5; + let cpz = z1 - (pmaxz + pminz) * 0.5; + let tmp1; + let tmp2; + let x = cpy * dz - cpz * dy; + if(!((x < 0 ? -x : x) - (pexty * adz + pextz * ady) > 0)) { + let x = cpz * dx - cpx * dz; + tmp2 = (x < 0 ? -x : x) - (pextz * adx + pextx * adz) > 0; + } else { + tmp2 = true; + } + if(!tmp2) { + let x = cpx * dy - cpy * dx; + tmp1 = (x < 0 ? -x : x) - (pextx * ady + pexty * adx) > 0; + } else { + tmp1 = true; + } + tmp = tmp1 ? false : true; + } + if(!tmp) { + return; + } + if(node._height == 0) { + callback.process(node._proxy); + return; + } + this.rayCastRecursive(node._children[0],_p1X,_p1Y,_p1Z,_p2X,_p2Y,_p2Z,callback); + this.rayCastRecursive(node._children[1],_p1X,_p1Y,_p1Z,_p2X,_p2Y,_p2Z,callback); + } + convexCastRecursive(node,convex,begin,translation,callback) { + let v = this._aabb.min; + v.x = node._aabbMinX; + v.y = node._aabbMinY; + v.z = node._aabbMinZ; + let v1 = this._aabb.max; + v1.x = node._aabbMaxX; + v1.y = node._aabbMaxY; + v1.z = node._aabbMaxZ; + this._convexSweep.init(convex,begin,translation); + let gjkEpa = oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance; + if(!(gjkEpa.computeClosestPointsImpl(this._convexSweep,this._aabb,begin,this.identity,null,false) == 0 && gjkEpa.distance <= 0)) { + return; + } + if(node._height == 0) { + callback.process(node._proxy); + return; + } + this.convexCastRecursive(node._children[0],convex,begin,translation,callback); + this.convexCastRecursive(node._children[1],convex,begin,translation,callback); + } + aabbTestRecursive(node,aabb,callback) { + if(!(node._aabbMinX < aabb._maxX && node._aabbMaxX > aabb._minX && node._aabbMinY < aabb._maxY && node._aabbMaxY > aabb._minY && node._aabbMinZ < aabb._maxZ && node._aabbMaxZ > aabb._minZ)) { + return; + } + if(node._height == 0) { + callback.process(node._proxy); + return; + } + this.aabbTestRecursive(node._children[0],aabb,callback); + this.aabbTestRecursive(node._children[1],aabb,callback); + } + createProxy(userData,aabb) { + let p = new oimo.collision.broadphase.bvh.BvhProxy(userData,this._idCount++); + this._numProxies++; + if(this._proxyList == null) { + this._proxyList = p; + this._proxyListLast = p; + } else { + this._proxyListLast._next = p; + p._prev = this._proxyListLast; + this._proxyListLast = p; + } + p._aabbMinX = aabb._minX; + p._aabbMinY = aabb._minY; + p._aabbMinZ = aabb._minZ; + p._aabbMaxX = aabb._maxX; + p._aabbMaxY = aabb._maxY; + p._aabbMaxZ = aabb._maxZ; + let padding = oimo.common.Setting.bvhProxyPadding; + p._aabbMinX -= padding; + p._aabbMinY -= padding; + p._aabbMinZ -= padding; + p._aabbMaxX += padding; + p._aabbMaxY += padding; + p._aabbMaxZ += padding; + let _this = this._tree; + let first = _this._nodePool; + if(first != null) { + _this._nodePool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.bvh.BvhNode(); + } + let leaf = first; + leaf._proxy = p; + p._leaf = leaf; + leaf._aabbMinX = p._aabbMinX; + leaf._aabbMinY = p._aabbMinY; + leaf._aabbMinZ = p._aabbMinZ; + leaf._aabbMaxX = p._aabbMaxX; + leaf._aabbMaxY = p._aabbMaxY; + leaf._aabbMaxZ = p._aabbMaxZ; + _this._numLeaves++; + if(_this.leafList == null) { + _this.leafList = leaf; + _this.leafListLast = leaf; + } else { + _this.leafListLast._nextLeaf = leaf; + leaf._prevLeaf = _this.leafListLast; + _this.leafListLast = leaf; + } + if(_this._root == null) { + _this._root = leaf; + } else { + let sibling = _this._root; + while(sibling._height > 0) { + let nextStep = _this._strategy._decideInsertion(sibling,leaf); + if(nextStep == -1) { + break; + } else { + sibling = sibling._children[nextStep]; + } + } + let parent = sibling._parent; + let first = _this._nodePool; + if(first != null) { + _this._nodePool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.bvh.BvhNode(); + } + let node = first; + if(parent == null) { + _this._root = node; + } else { + let index = sibling._childIndex; + parent._children[index] = node; + node._parent = parent; + node._childIndex = index; + } + let index = sibling._childIndex; + node._children[index] = sibling; + sibling._parent = node; + sibling._childIndex = index; + let index1 = sibling._childIndex ^ 1; + node._children[index1] = leaf; + leaf._parent = node; + leaf._childIndex = index1; + while(node != null) { + if(_this._strategy._balancingEnabled) { + if(node._height >= 2) { + let p = node._parent; + let l = node._children[0]; + let r = node._children[1]; + let balance = l._height - r._height; + let nodeIndex = node._childIndex; + if(balance > 1) { + let ll = l._children[0]; + let lr = l._children[1]; + if(ll._height > lr._height) { + l._children[1] = node; + node._parent = l; + node._childIndex = 1; + node._children[0] = lr; + lr._parent = node; + lr._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + l._children[0] = node; + node._parent = l; + node._childIndex = 0; + node._children[0] = ll; + ll._parent = node; + ll._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = l; + l._parent = p; + l._childIndex = nodeIndex; + } else { + _this._root = l; + l._parent = null; + } + node = l; + } else if(balance < -1) { + let rl = r._children[0]; + let rr = r._children[1]; + if(rl._height > rr._height) { + r._children[1] = node; + node._parent = r; + node._childIndex = 1; + node._children[1] = rr; + rr._parent = node; + rr._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + r._children[0] = node; + node._parent = r; + node._childIndex = 0; + node._children[1] = rl; + rl._parent = node; + rl._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = r; + r._parent = p; + r._childIndex = nodeIndex; + } else { + _this._root = r; + r._parent = null; + } + node = r; + } + } + } + let h1 = node._children[0]._height; + let h2 = node._children[1]._height; + node._height = (h1 > h2 ? h1 : h2) + 1; + let c1 = node._children[0]; + let c2 = node._children[1]; + node._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + node._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + node._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + node._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + node._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + node._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + node = node._parent; + } + } + if(!p._moved) { + p._moved = true; + if(this.movedProxies.length == this.numMovedProxies) { + let newArray = new Array(this.numMovedProxies << 1); + let _g = 0; + let _g1 = this.numMovedProxies; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.movedProxies[i]; + this.movedProxies[i] = null; + } + this.movedProxies = newArray; + } + this.movedProxies[this.numMovedProxies++] = p; + } + return p; + } + destroyProxy(proxy) { + this._numProxies--; + let prev = proxy._prev; + let next = proxy._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(proxy == this._proxyList) { + this._proxyList = this._proxyList._next; + } + if(proxy == this._proxyListLast) { + this._proxyListLast = this._proxyListLast._prev; + } + proxy._next = null; + proxy._prev = null; + let bvhProxy = proxy; + let _this = this._tree; + let leaf = bvhProxy._leaf; + _this._numLeaves--; + let prev1 = leaf._prevLeaf; + let next1 = leaf._nextLeaf; + if(prev1 != null) { + prev1._nextLeaf = next1; + } + if(next1 != null) { + next1._prevLeaf = prev1; + } + if(leaf == _this.leafList) { + _this.leafList = _this.leafList._nextLeaf; + } + if(leaf == _this.leafListLast) { + _this.leafListLast = _this.leafListLast._prevLeaf; + } + leaf._nextLeaf = null; + leaf._prevLeaf = null; + if(_this._root == leaf) { + _this._root = null; + } else { + let parent = leaf._parent; + let sibling = parent._children[leaf._childIndex ^ 1]; + let grandParent = parent._parent; + if(grandParent == null) { + sibling._parent = null; + sibling._childIndex = 0; + _this._root = sibling; + parent._next = null; + parent._childIndex = 0; + parent._children[0] = null; + parent._children[1] = null; + parent._childIndex = 0; + parent._parent = null; + parent._height = 0; + parent._proxy = null; + parent._next = _this._nodePool; + _this._nodePool = parent; + } else { + sibling._parent = grandParent; + let index = parent._childIndex; + grandParent._children[index] = sibling; + sibling._parent = grandParent; + sibling._childIndex = index; + parent._next = null; + parent._childIndex = 0; + parent._children[0] = null; + parent._children[1] = null; + parent._childIndex = 0; + parent._parent = null; + parent._height = 0; + parent._proxy = null; + parent._next = _this._nodePool; + _this._nodePool = parent; + let node = grandParent; + while(node != null) { + if(_this._strategy._balancingEnabled) { + if(node._height >= 2) { + let p = node._parent; + let l = node._children[0]; + let r = node._children[1]; + let balance = l._height - r._height; + let nodeIndex = node._childIndex; + if(balance > 1) { + let ll = l._children[0]; + let lr = l._children[1]; + if(ll._height > lr._height) { + l._children[1] = node; + node._parent = l; + node._childIndex = 1; + node._children[0] = lr; + lr._parent = node; + lr._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + l._children[0] = node; + node._parent = l; + node._childIndex = 0; + node._children[0] = ll; + ll._parent = node; + ll._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = l; + l._parent = p; + l._childIndex = nodeIndex; + } else { + _this._root = l; + l._parent = null; + } + node = l; + } else if(balance < -1) { + let rl = r._children[0]; + let rr = r._children[1]; + if(rl._height > rr._height) { + r._children[1] = node; + node._parent = r; + node._childIndex = 1; + node._children[1] = rr; + rr._parent = node; + rr._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + r._children[0] = node; + node._parent = r; + node._childIndex = 0; + node._children[1] = rl; + rl._parent = node; + rl._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = r; + r._parent = p; + r._childIndex = nodeIndex; + } else { + _this._root = r; + r._parent = null; + } + node = r; + } + } + } + let h1 = node._children[0]._height; + let h2 = node._children[1]._height; + node._height = (h1 > h2 ? h1 : h2) + 1; + let c1 = node._children[0]; + let c2 = node._children[1]; + node._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + node._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + node._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + node._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + node._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + node._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + node = node._parent; + } + } + } + bvhProxy._leaf = null; + leaf._next = null; + leaf._childIndex = 0; + leaf._children[0] = null; + leaf._children[1] = null; + leaf._childIndex = 0; + leaf._parent = null; + leaf._height = 0; + leaf._proxy = null; + leaf._next = _this._nodePool; + _this._nodePool = leaf; + bvhProxy.userData = null; + bvhProxy._next = null; + bvhProxy._prev = null; + if(bvhProxy._moved) { + bvhProxy._moved = false; + } + } + moveProxy(proxy,aabb,displacement) { + let p = proxy; + if(p._aabbMinX <= aabb._minX && p._aabbMaxX >= aabb._maxX && p._aabbMinY <= aabb._minY && p._aabbMaxY >= aabb._maxY && p._aabbMinZ <= aabb._minZ && p._aabbMaxZ >= aabb._maxZ) { + return; + } + p._aabbMinX = aabb._minX; + p._aabbMinY = aabb._minY; + p._aabbMinZ = aabb._minZ; + p._aabbMaxX = aabb._maxX; + p._aabbMaxY = aabb._maxY; + p._aabbMaxZ = aabb._maxZ; + let padding = oimo.common.Setting.bvhProxyPadding; + p._aabbMinX -= padding; + p._aabbMinY -= padding; + p._aabbMinZ -= padding; + p._aabbMaxX += padding; + p._aabbMaxY += padding; + p._aabbMaxZ += padding; + if(displacement != null) { + let dX; + let dY; + let dZ; + let zeroX; + let zeroY; + let zeroZ; + let addToMinX; + let addToMinY; + let addToMinZ; + let addToMaxX; + let addToMaxY; + let addToMaxZ; + zeroX = 0; + zeroY = 0; + zeroZ = 0; + dX = displacement.x; + dY = displacement.y; + dZ = displacement.z; + addToMinX = zeroX < dX ? zeroX : dX; + addToMinY = zeroY < dY ? zeroY : dY; + addToMinZ = zeroZ < dZ ? zeroZ : dZ; + addToMaxX = zeroX > dX ? zeroX : dX; + addToMaxY = zeroY > dY ? zeroY : dY; + addToMaxZ = zeroZ > dZ ? zeroZ : dZ; + p._aabbMinX += addToMinX; + p._aabbMinY += addToMinY; + p._aabbMinZ += addToMinZ; + p._aabbMaxX += addToMaxX; + p._aabbMaxY += addToMaxY; + p._aabbMaxZ += addToMaxZ; + } + if(!p._moved) { + p._moved = true; + if(this.movedProxies.length == this.numMovedProxies) { + let newArray = new Array(this.numMovedProxies << 1); + let _g = 0; + let _g1 = this.numMovedProxies; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.movedProxies[i]; + this.movedProxies[i] = null; + } + this.movedProxies = newArray; + } + this.movedProxies[this.numMovedProxies++] = p; + } + } + collectPairs() { + let p = this._proxyPairList; + if(p != null) { + while(true) { + p._p1 = null; + p._p2 = null; + p = p._next; + if(!(p != null)) { + break; + } + } + this._proxyPairList._next = this._proxyPairPool; + this._proxyPairPool = this._proxyPairList; + this._proxyPairList = null; + } + this._testCount = 0; + if(this._numProxies < 2) { + return; + } + let incrementalCollision = this.numMovedProxies / this._numProxies < oimo.common.Setting.bvhIncrementalCollisionThreshold; + let _g = 0; + let _g1 = this.numMovedProxies; + while(_g < _g1) { + let i = _g++; + let p = this.movedProxies[i]; + if(p._moved) { + let _this = this._tree; + let leaf = p._leaf; + _this._numLeaves--; + let prev = leaf._prevLeaf; + let next = leaf._nextLeaf; + if(prev != null) { + prev._nextLeaf = next; + } + if(next != null) { + next._prevLeaf = prev; + } + if(leaf == _this.leafList) { + _this.leafList = _this.leafList._nextLeaf; + } + if(leaf == _this.leafListLast) { + _this.leafListLast = _this.leafListLast._prevLeaf; + } + leaf._nextLeaf = null; + leaf._prevLeaf = null; + if(_this._root == leaf) { + _this._root = null; + } else { + let parent = leaf._parent; + let sibling = parent._children[leaf._childIndex ^ 1]; + let grandParent = parent._parent; + if(grandParent == null) { + sibling._parent = null; + sibling._childIndex = 0; + _this._root = sibling; + parent._next = null; + parent._childIndex = 0; + parent._children[0] = null; + parent._children[1] = null; + parent._childIndex = 0; + parent._parent = null; + parent._height = 0; + parent._proxy = null; + parent._next = _this._nodePool; + _this._nodePool = parent; + } else { + sibling._parent = grandParent; + let index = parent._childIndex; + grandParent._children[index] = sibling; + sibling._parent = grandParent; + sibling._childIndex = index; + parent._next = null; + parent._childIndex = 0; + parent._children[0] = null; + parent._children[1] = null; + parent._childIndex = 0; + parent._parent = null; + parent._height = 0; + parent._proxy = null; + parent._next = _this._nodePool; + _this._nodePool = parent; + let node = grandParent; + while(node != null) { + if(_this._strategy._balancingEnabled) { + if(node._height >= 2) { + let p = node._parent; + let l = node._children[0]; + let r = node._children[1]; + let balance = l._height - r._height; + let nodeIndex = node._childIndex; + if(balance > 1) { + let ll = l._children[0]; + let lr = l._children[1]; + if(ll._height > lr._height) { + l._children[1] = node; + node._parent = l; + node._childIndex = 1; + node._children[0] = lr; + lr._parent = node; + lr._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + l._children[0] = node; + node._parent = l; + node._childIndex = 0; + node._children[0] = ll; + ll._parent = node; + ll._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = l; + l._parent = p; + l._childIndex = nodeIndex; + } else { + _this._root = l; + l._parent = null; + } + node = l; + } else if(balance < -1) { + let rl = r._children[0]; + let rr = r._children[1]; + if(rl._height > rr._height) { + r._children[1] = node; + node._parent = r; + node._childIndex = 1; + node._children[1] = rr; + rr._parent = node; + rr._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + r._children[0] = node; + node._parent = r; + node._childIndex = 0; + node._children[1] = rl; + rl._parent = node; + rl._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = r; + r._parent = p; + r._childIndex = nodeIndex; + } else { + _this._root = r; + r._parent = null; + } + node = r; + } + } + } + let h1 = node._children[0]._height; + let h2 = node._children[1]._height; + node._height = (h1 > h2 ? h1 : h2) + 1; + let c1 = node._children[0]; + let c2 = node._children[1]; + node._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + node._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + node._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + node._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + node._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + node._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + node = node._parent; + } + } + } + p._leaf = null; + leaf._next = null; + leaf._childIndex = 0; + leaf._children[0] = null; + leaf._children[1] = null; + leaf._childIndex = 0; + leaf._parent = null; + leaf._height = 0; + leaf._proxy = null; + leaf._next = _this._nodePool; + _this._nodePool = leaf; + let _this1 = this._tree; + let first = _this1._nodePool; + if(first != null) { + _this1._nodePool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.bvh.BvhNode(); + } + let leaf1 = first; + leaf1._proxy = p; + p._leaf = leaf1; + leaf1._aabbMinX = p._aabbMinX; + leaf1._aabbMinY = p._aabbMinY; + leaf1._aabbMinZ = p._aabbMinZ; + leaf1._aabbMaxX = p._aabbMaxX; + leaf1._aabbMaxY = p._aabbMaxY; + leaf1._aabbMaxZ = p._aabbMaxZ; + _this1._numLeaves++; + if(_this1.leafList == null) { + _this1.leafList = leaf1; + _this1.leafListLast = leaf1; + } else { + _this1.leafListLast._nextLeaf = leaf1; + leaf1._prevLeaf = _this1.leafListLast; + _this1.leafListLast = leaf1; + } + if(_this1._root == null) { + _this1._root = leaf1; + } else { + let sibling = _this1._root; + while(sibling._height > 0) { + let nextStep = _this1._strategy._decideInsertion(sibling,leaf1); + if(nextStep == -1) { + break; + } else { + sibling = sibling._children[nextStep]; + } + } + let parent = sibling._parent; + let first = _this1._nodePool; + if(first != null) { + _this1._nodePool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.bvh.BvhNode(); + } + let node = first; + if(parent == null) { + _this1._root = node; + } else { + let index = sibling._childIndex; + parent._children[index] = node; + node._parent = parent; + node._childIndex = index; + } + let index = sibling._childIndex; + node._children[index] = sibling; + sibling._parent = node; + sibling._childIndex = index; + let index1 = sibling._childIndex ^ 1; + node._children[index1] = leaf1; + leaf1._parent = node; + leaf1._childIndex = index1; + while(node != null) { + if(_this1._strategy._balancingEnabled) { + if(node._height >= 2) { + let p = node._parent; + let l = node._children[0]; + let r = node._children[1]; + let balance = l._height - r._height; + let nodeIndex = node._childIndex; + if(balance > 1) { + let ll = l._children[0]; + let lr = l._children[1]; + if(ll._height > lr._height) { + l._children[1] = node; + node._parent = l; + node._childIndex = 1; + node._children[0] = lr; + lr._parent = node; + lr._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + l._children[0] = node; + node._parent = l; + node._childIndex = 0; + node._children[0] = ll; + ll._parent = node; + ll._childIndex = 0; + let c1 = l._children[0]; + let c2 = l._children[1]; + l._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + l._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + l._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + l._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + l._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + l._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = l._children[0]._height; + let h2 = l._children[1]._height; + l._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = l; + l._parent = p; + l._childIndex = nodeIndex; + } else { + _this1._root = l; + l._parent = null; + } + node = l; + } else if(balance < -1) { + let rl = r._children[0]; + let rr = r._children[1]; + if(rl._height > rr._height) { + r._children[1] = node; + node._parent = r; + node._childIndex = 1; + node._children[1] = rr; + rr._parent = node; + rr._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } else { + r._children[0] = node; + node._parent = r; + node._childIndex = 0; + node._children[1] = rl; + rl._parent = node; + rl._childIndex = 1; + let c1 = r._children[0]; + let c2 = r._children[1]; + r._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + r._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + r._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + r._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + r._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + r._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = r._children[0]._height; + let h2 = r._children[1]._height; + r._height = (h1 > h2 ? h1 : h2) + 1; + let c11 = node._children[0]; + let c21 = node._children[1]; + node._aabbMinX = c11._aabbMinX < c21._aabbMinX ? c11._aabbMinX : c21._aabbMinX; + node._aabbMinY = c11._aabbMinY < c21._aabbMinY ? c11._aabbMinY : c21._aabbMinY; + node._aabbMinZ = c11._aabbMinZ < c21._aabbMinZ ? c11._aabbMinZ : c21._aabbMinZ; + node._aabbMaxX = c11._aabbMaxX > c21._aabbMaxX ? c11._aabbMaxX : c21._aabbMaxX; + node._aabbMaxY = c11._aabbMaxY > c21._aabbMaxY ? c11._aabbMaxY : c21._aabbMaxY; + node._aabbMaxZ = c11._aabbMaxZ > c21._aabbMaxZ ? c11._aabbMaxZ : c21._aabbMaxZ; + let h11 = node._children[0]._height; + let h21 = node._children[1]._height; + node._height = (h11 > h21 ? h11 : h21) + 1; + } + if(p != null) { + p._children[nodeIndex] = r; + r._parent = p; + r._childIndex = nodeIndex; + } else { + _this1._root = r; + r._parent = null; + } + node = r; + } + } + } + let h1 = node._children[0]._height; + let h2 = node._children[1]._height; + node._height = (h1 > h2 ? h1 : h2) + 1; + let c1 = node._children[0]; + let c2 = node._children[1]; + node._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + node._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + node._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + node._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + node._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + node._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + node = node._parent; + } + } + if(incrementalCollision) { + this.collide(this._tree._root,p._leaf); + } + p._moved = false; + } + this.movedProxies[i] = null; + } + if(!incrementalCollision) { + this.collide(this._tree._root,this._tree._root); + } + this.numMovedProxies = 0; + } + rayCast(begin,end,callback) { + if(this._tree._root == null) { + return; + } + let p1X; + let p1Y; + let p1Z; + let p2X; + let p2Y; + let p2Z; + p1X = begin.x; + p1Y = begin.y; + p1Z = begin.z; + p2X = end.x; + p2Y = end.y; + p2Z = end.z; + this.rayCastRecursive(this._tree._root,p1X,p1Y,p1Z,p2X,p2Y,p2Z,callback); + } + convexCast(convex,begin,translation,callback) { + if(this._tree._root == null) { + return; + } + this.convexCastRecursive(this._tree._root,convex,begin,translation,callback); + } + aabbTest(aabb,callback) { + if(this._tree._root == null) { + return; + } + this.aabbTestRecursive(this._tree._root,aabb,callback); + } + getTreeBalance() { + return this._tree._getBalance(); + } +} +oimo.collision.broadphase.bvh.BvhInsertionStrategy = class oimo_collision_broadphase_bvh_BvhInsertionStrategy { +} +oimo.collision.broadphase.bvh.BvhNode = class oimo_collision_broadphase_bvh_BvhNode { + constructor() { + this._next = null; + this._prevLeaf = null; + this._nextLeaf = null; + this._children = new Array(2); + this._childIndex = 0; + this._parent = null; + this._height = 0; + this._proxy = null; + this._aabbMinX = 0; + this._aabbMinY = 0; + this._aabbMinZ = 0; + this._aabbMaxX = 0; + this._aabbMaxY = 0; + this._aabbMaxZ = 0; + } +} +oimo.collision.broadphase.bvh.BvhProxy = class oimo_collision_broadphase_bvh_BvhProxy extends oimo.collision.broadphase.Proxy { + constructor(userData,id) { + super(userData,id); + this._leaf = null; + this._moved = false; + } +} +oimo.collision.broadphase.bvh.BvhStrategy = class oimo_collision_broadphase_bvh_BvhStrategy { + constructor() { + this._insertionStrategy = 0; + this._balancingEnabled = false; + } + _decideInsertion(currentNode,leaf) { + switch(this._insertionStrategy) { + case 0: + let centerX; + let centerY; + let centerZ; + centerX = leaf._aabbMinX + leaf._aabbMaxX; + centerY = leaf._aabbMinY + leaf._aabbMaxY; + centerZ = leaf._aabbMinZ + leaf._aabbMaxZ; + let c1 = currentNode._children[0]; + let c2 = currentNode._children[1]; + let diff1X; + let diff1Y; + let diff1Z; + let diff2X; + let diff2Y; + let diff2Z; + diff1X = c1._aabbMinX + c1._aabbMaxX; + diff1Y = c1._aabbMinY + c1._aabbMaxY; + diff1Z = c1._aabbMinZ + c1._aabbMaxZ; + diff2X = c2._aabbMinX + c2._aabbMaxX; + diff2Y = c2._aabbMinY + c2._aabbMaxY; + diff2Z = c2._aabbMinZ + c2._aabbMaxZ; + diff1X -= centerX; + diff1Y -= centerY; + diff1Z -= centerZ; + diff2X -= centerX; + diff2Y -= centerY; + diff2Z -= centerZ; + if(diff1X * diff1X + diff1Y * diff1Y + diff1Z * diff1Z < diff2X * diff2X + diff2Y * diff2Y + diff2Z * diff2Z) { + return 0; + } else { + return 1; + } + break; + case 1: + let c11 = currentNode._children[0]; + let c21 = currentNode._children[1]; + let ey = currentNode._aabbMaxY - currentNode._aabbMinY; + let ez = currentNode._aabbMaxZ - currentNode._aabbMinZ; + let combinedMinX; + let combinedMinY; + let combinedMinZ; + let combinedMaxX; + let combinedMaxY; + let combinedMaxZ; + combinedMinX = currentNode._aabbMinX < leaf._aabbMinX ? currentNode._aabbMinX : leaf._aabbMinX; + combinedMinY = currentNode._aabbMinY < leaf._aabbMinY ? currentNode._aabbMinY : leaf._aabbMinY; + combinedMinZ = currentNode._aabbMinZ < leaf._aabbMinZ ? currentNode._aabbMinZ : leaf._aabbMinZ; + combinedMaxX = currentNode._aabbMaxX > leaf._aabbMaxX ? currentNode._aabbMaxX : leaf._aabbMaxX; + combinedMaxY = currentNode._aabbMaxY > leaf._aabbMaxY ? currentNode._aabbMaxY : leaf._aabbMaxY; + combinedMaxZ = currentNode._aabbMaxZ > leaf._aabbMaxZ ? currentNode._aabbMaxZ : leaf._aabbMaxZ; + let ey1 = combinedMaxY - combinedMinY; + let ez1 = combinedMaxZ - combinedMinZ; + let newArea = ((combinedMaxX - combinedMinX) * (ey1 + ez1) + ey1 * ez1) * 2; + let creatingCost = newArea * 2; + let incrementalCost = (newArea - ((currentNode._aabbMaxX - currentNode._aabbMinX) * (ey + ez) + ey * ez) * 2) * 2; + let descendingCost1; + combinedMinX = c11._aabbMinX < leaf._aabbMinX ? c11._aabbMinX : leaf._aabbMinX; + combinedMinY = c11._aabbMinY < leaf._aabbMinY ? c11._aabbMinY : leaf._aabbMinY; + combinedMinZ = c11._aabbMinZ < leaf._aabbMinZ ? c11._aabbMinZ : leaf._aabbMinZ; + combinedMaxX = c11._aabbMaxX > leaf._aabbMaxX ? c11._aabbMaxX : leaf._aabbMaxX; + combinedMaxY = c11._aabbMaxY > leaf._aabbMaxY ? c11._aabbMaxY : leaf._aabbMaxY; + combinedMaxZ = c11._aabbMaxZ > leaf._aabbMaxZ ? c11._aabbMaxZ : leaf._aabbMaxZ; + if(c11._height == 0) { + let ey = combinedMaxY - combinedMinY; + let ez = combinedMaxZ - combinedMinZ; + descendingCost1 = incrementalCost + ((combinedMaxX - combinedMinX) * (ey + ez) + ey * ez) * 2; + } else { + let ey = combinedMaxY - combinedMinY; + let ez = combinedMaxZ - combinedMinZ; + let ey1 = c11._aabbMaxY - c11._aabbMinY; + let ez1 = c11._aabbMaxZ - c11._aabbMinZ; + descendingCost1 = incrementalCost + (((combinedMaxX - combinedMinX) * (ey + ez) + ey * ez) * 2 - ((c11._aabbMaxX - c11._aabbMinX) * (ey1 + ez1) + ey1 * ez1) * 2); + } + let descendingCost2; + combinedMinX = c21._aabbMinX < leaf._aabbMinX ? c21._aabbMinX : leaf._aabbMinX; + combinedMinY = c21._aabbMinY < leaf._aabbMinY ? c21._aabbMinY : leaf._aabbMinY; + combinedMinZ = c21._aabbMinZ < leaf._aabbMinZ ? c21._aabbMinZ : leaf._aabbMinZ; + combinedMaxX = c21._aabbMaxX > leaf._aabbMaxX ? c21._aabbMaxX : leaf._aabbMaxX; + combinedMaxY = c21._aabbMaxY > leaf._aabbMaxY ? c21._aabbMaxY : leaf._aabbMaxY; + combinedMaxZ = c21._aabbMaxZ > leaf._aabbMaxZ ? c21._aabbMaxZ : leaf._aabbMaxZ; + if(c21._height == 0) { + let ey = combinedMaxY - combinedMinY; + let ez = combinedMaxZ - combinedMinZ; + descendingCost2 = incrementalCost + ((combinedMaxX - combinedMinX) * (ey + ez) + ey * ez) * 2; + } else { + let ey = combinedMaxY - combinedMinY; + let ez = combinedMaxZ - combinedMinZ; + let ey1 = c21._aabbMaxY - c21._aabbMinY; + let ez1 = c21._aabbMaxZ - c21._aabbMinZ; + descendingCost2 = incrementalCost + (((combinedMaxX - combinedMinX) * (ey + ez) + ey * ez) * 2 - ((c21._aabbMaxX - c21._aabbMinX) * (ey1 + ez1) + ey1 * ez1) * 2); + } + if(creatingCost < descendingCost1) { + if(creatingCost < descendingCost2) { + return -1; + } else { + return 1; + } + } else if(descendingCost1 < descendingCost2) { + return 0; + } else { + return 1; + } + break; + default: + console.log("src/oimo/collision/broadphase/bvh/BvhStrategy.hx:37:","invalid BVH insertion strategy: " + this._insertionStrategy); + return -1; + } + } + _splitLeaves(leaves,from,until) { + let invN = 1.0 / (until - from); + let centerMeanX; + let centerMeanY; + let centerMeanZ; + centerMeanX = 0; + centerMeanY = 0; + centerMeanZ = 0; + let _g = from; + while(_g < until) { + let leaf = leaves[_g++]; + leaf._tmpX = leaf._aabbMaxX + leaf._aabbMinX; + leaf._tmpY = leaf._aabbMaxY + leaf._aabbMinY; + leaf._tmpZ = leaf._aabbMaxZ + leaf._aabbMinZ; + centerMeanX += leaf._tmpX; + centerMeanY += leaf._tmpY; + centerMeanZ += leaf._tmpZ; + } + centerMeanX *= invN; + centerMeanY *= invN; + centerMeanZ *= invN; + let varianceX; + let varianceY; + let varianceZ; + varianceX = 0; + varianceY = 0; + varianceZ = 0; + let _g1 = from; + while(_g1 < until) { + let leaf = leaves[_g1++]; + let diffX; + let diffY; + let diffZ; + diffX = leaf._tmpX - centerMeanX; + diffY = leaf._tmpY - centerMeanY; + diffZ = leaf._tmpZ - centerMeanZ; + diffX *= diffX; + diffY *= diffY; + diffZ *= diffZ; + varianceX += diffX; + varianceY += diffY; + varianceZ += diffZ; + } + let varX = varianceX; + let varY = varianceY; + let varZ = varianceZ; + let l = from; + let r = until - 1; + if(varX > varY) { + if(varX > varZ) { + let mean = centerMeanX; + while(true) { + while(!(leaves[l]._tmpX <= mean)) ++l; + while(!(leaves[r]._tmpX >= mean)) --r; + if(l >= r) { + break; + } + let tmp = leaves[l]; + leaves[l] = leaves[r]; + leaves[r] = tmp; + ++l; + --r; + } + } else { + let mean = centerMeanZ; + while(true) { + while(!(leaves[l]._tmpZ <= mean)) ++l; + while(!(leaves[r]._tmpZ >= mean)) --r; + if(l >= r) { + break; + } + let tmp = leaves[l]; + leaves[l] = leaves[r]; + leaves[r] = tmp; + ++l; + --r; + } + } + } else if(varY > varZ) { + let mean = centerMeanY; + while(true) { + while(!(leaves[l]._tmpY <= mean)) ++l; + while(!(leaves[r]._tmpY >= mean)) --r; + if(l >= r) { + break; + } + let tmp = leaves[l]; + leaves[l] = leaves[r]; + leaves[r] = tmp; + ++l; + --r; + } + } else { + let mean = centerMeanZ; + while(true) { + while(!(leaves[l]._tmpZ <= mean)) ++l; + while(!(leaves[r]._tmpZ >= mean)) --r; + if(l >= r) { + break; + } + let tmp = leaves[l]; + leaves[l] = leaves[r]; + leaves[r] = tmp; + ++l; + --r; + } + } + return l; + } +} +oimo.collision.broadphase.bvh.BvhTree = class oimo_collision_broadphase_bvh_BvhTree { + constructor() { + this._root = null; + this._numLeaves = 0; + this._strategy = new oimo.collision.broadphase.bvh.BvhStrategy(); + this._nodePool = null; + this.leafList = null; + this.leafListLast = null; + this.tmp = new Array(1024); + } + _print(root,indent) { + if(indent == null) { + indent = ""; + } + if(root == null) { + return; + } + if(root._height == 0) { + console.log("src/oimo/collision/broadphase/bvh/BvhTree.hx:39:",indent + root._proxy._id); + } else { + this._print(root._children[0],indent + " "); + let tmp; + let sizeX; + let sizeY; + let sizeZ; + sizeX = root._aabbMaxX - root._aabbMinX; + sizeY = root._aabbMaxY - root._aabbMinY; + sizeZ = root._aabbMaxZ - root._aabbMinZ; + let y = sizeY; + let z = sizeZ; + if(sizeX * (y + z) + y * z > 0) { + let sizeX; + let sizeY; + let sizeZ; + sizeX = root._aabbMaxX - root._aabbMinX; + sizeY = root._aabbMaxY - root._aabbMinY; + sizeZ = root._aabbMaxZ - root._aabbMinZ; + let y = sizeY; + let z = sizeZ; + tmp = ((sizeX * (y + z) + y * z) * 1000 + 0.5 | 0) / 1000; + } else { + let sizeX; + let sizeY; + let sizeZ; + sizeX = root._aabbMaxX - root._aabbMinX; + sizeY = root._aabbMaxY - root._aabbMinY; + sizeZ = root._aabbMaxZ - root._aabbMinZ; + let y = sizeY; + let z = sizeZ; + tmp = ((sizeX * (y + z) + y * z) * 1000 - 0.5 | 0) / 1000; + } + console.log("src/oimo/collision/broadphase/bvh/BvhTree.hx:42:",indent + "#" + root._height + ", " + tmp); + this._print(root._children[1],indent + " "); + } + } + _getBalance() { + return this.getBalanceRecursive(this._root); + } + deleteRecursive(root) { + if(root._height == 0) { + let prev = root._prevLeaf; + let next = root._nextLeaf; + if(prev != null) { + prev._nextLeaf = next; + } + if(next != null) { + next._prevLeaf = prev; + } + if(root == this.leafList) { + this.leafList = this.leafList._nextLeaf; + } + if(root == this.leafListLast) { + this.leafListLast = this.leafListLast._prevLeaf; + } + root._nextLeaf = null; + root._prevLeaf = null; + root._proxy._leaf = null; + root._next = null; + root._childIndex = 0; + root._children[0] = null; + root._children[1] = null; + root._childIndex = 0; + root._parent = null; + root._height = 0; + root._proxy = null; + root._next = this._nodePool; + this._nodePool = root; + return; + } + this.deleteRecursive(root._children[0]); + this.deleteRecursive(root._children[1]); + root._next = null; + root._childIndex = 0; + root._children[0] = null; + root._children[1] = null; + root._childIndex = 0; + root._parent = null; + root._height = 0; + root._proxy = null; + root._next = this._nodePool; + this._nodePool = root; + } + decomposeRecursive(root) { + if(root._height == 0) { + root._childIndex = 0; + root._parent = null; + return; + } + this.decomposeRecursive(root._children[0]); + this.decomposeRecursive(root._children[1]); + root._next = null; + root._childIndex = 0; + root._children[0] = null; + root._children[1] = null; + root._childIndex = 0; + root._parent = null; + root._height = 0; + root._proxy = null; + root._next = this._nodePool; + this._nodePool = root; + } + buildTopDownRecursive(leaves,from,until) { + if(until - from == 1) { + let leaf = leaves[from]; + let proxy = leaf._proxy; + leaf._aabbMinX = proxy._aabbMinX; + leaf._aabbMinY = proxy._aabbMinY; + leaf._aabbMinZ = proxy._aabbMinZ; + leaf._aabbMaxX = proxy._aabbMaxX; + leaf._aabbMaxY = proxy._aabbMaxY; + leaf._aabbMaxZ = proxy._aabbMaxZ; + return leaf; + } + let splitAt = this._strategy._splitLeaves(leaves,from,until); + let child1 = this.buildTopDownRecursive(leaves,from,splitAt); + let child2 = this.buildTopDownRecursive(leaves,splitAt,until); + let first = this._nodePool; + if(first != null) { + this._nodePool = first._next; + first._next = null; + } else { + first = new oimo.collision.broadphase.bvh.BvhNode(); + } + let parent = first; + parent._children[0] = child1; + child1._parent = parent; + child1._childIndex = 0; + parent._children[1] = child2; + child2._parent = parent; + child2._childIndex = 1; + let c1 = parent._children[0]; + let c2 = parent._children[1]; + parent._aabbMinX = c1._aabbMinX < c2._aabbMinX ? c1._aabbMinX : c2._aabbMinX; + parent._aabbMinY = c1._aabbMinY < c2._aabbMinY ? c1._aabbMinY : c2._aabbMinY; + parent._aabbMinZ = c1._aabbMinZ < c2._aabbMinZ ? c1._aabbMinZ : c2._aabbMinZ; + parent._aabbMaxX = c1._aabbMaxX > c2._aabbMaxX ? c1._aabbMaxX : c2._aabbMaxX; + parent._aabbMaxY = c1._aabbMaxY > c2._aabbMaxY ? c1._aabbMaxY : c2._aabbMaxY; + parent._aabbMaxZ = c1._aabbMaxZ > c2._aabbMaxZ ? c1._aabbMaxZ : c2._aabbMaxZ; + let h1 = parent._children[0]._height; + let h2 = parent._children[1]._height; + parent._height = (h1 > h2 ? h1 : h2) + 1; + return parent; + } + getBalanceRecursive(root) { + if(root == null || root._height == 0) { + return 0; + } + let balance = root._children[0]._height - root._children[1]._height; + if(balance < 0) { + balance = -balance; + } + return balance + this.getBalanceRecursive(root._children[0]) + this.getBalanceRecursive(root._children[1]); + } +} +oimo.collision.geometry.Aabb = class oimo_collision_geometry_Aabb { + constructor() { + this._minX = 0; + this._minY = 0; + this._minZ = 0; + this._maxX = 0; + this._maxY = 0; + this._maxZ = 0; + } + init(min,max) { + this._minX = min.x; + this._minY = min.y; + this._minZ = min.z; + this._maxX = max.x; + this._maxY = max.y; + this._maxZ = max.z; + return this; + } + getMin() { + let min = new oimo.common.Vec3(); + min.x = this._minX; + min.y = this._minY; + min.z = this._minZ; + return min; + } + getMinTo(min) { + min.x = this._minX; + min.y = this._minY; + min.z = this._minZ; + } + setMin(min) { + this._minX = min.x; + this._minY = min.y; + this._minZ = min.z; + return this; + } + getMax() { + let max = new oimo.common.Vec3(); + max.x = this._maxX; + max.y = this._maxY; + max.z = this._maxZ; + return max; + } + getMaxTo(max) { + max.x = this._maxX; + max.y = this._maxY; + max.z = this._maxZ; + } + setMax(max) { + this._maxX = max.x; + this._maxY = max.y; + this._maxZ = max.z; + return this; + } + getCenter() { + let v = new oimo.common.Vec3(); + let cX; + let cY; + let cZ; + cX = this._minX + this._maxX; + cY = this._minY + this._maxY; + cZ = this._minZ + this._maxZ; + cX *= 0.5; + cY *= 0.5; + cZ *= 0.5; + v.x = cX; + v.y = cY; + v.z = cZ; + return v; + } + getCenterTo(center) { + let cX; + let cY; + let cZ; + cX = this._minX + this._maxX; + cY = this._minY + this._maxY; + cZ = this._minZ + this._maxZ; + cX *= 0.5; + cY *= 0.5; + cZ *= 0.5; + center.x = cX; + center.y = cY; + center.z = cZ; + } + getExtents() { + let v = new oimo.common.Vec3(); + let cX; + let cY; + let cZ; + cX = this._maxX - this._minX; + cY = this._maxY - this._minY; + cZ = this._maxZ - this._minZ; + cX *= 0.5; + cY *= 0.5; + cZ *= 0.5; + v.x = cX; + v.y = cY; + v.z = cZ; + return v; + } + getExtentsTo(halfExtents) { + let cX; + let cY; + let cZ; + cX = this._maxX - this._minX; + cY = this._maxY - this._minY; + cZ = this._maxZ - this._minZ; + cX *= 0.5; + cY *= 0.5; + cZ *= 0.5; + halfExtents.x = cX; + halfExtents.y = cY; + halfExtents.z = cZ; + } + combine(other) { + this._minX = this._minX < other._minX ? this._minX : other._minX; + this._minY = this._minY < other._minY ? this._minY : other._minY; + this._minZ = this._minZ < other._minZ ? this._minZ : other._minZ; + this._maxX = this._maxX > other._maxX ? this._maxX : other._maxX; + this._maxY = this._maxY > other._maxY ? this._maxY : other._maxY; + this._maxZ = this._maxZ > other._maxZ ? this._maxZ : other._maxZ; + return this; + } + combined(other) { + let aabb = new oimo.collision.geometry.Aabb(); + aabb._minX = this._minX < other._minX ? this._minX : other._minX; + aabb._minY = this._minY < other._minY ? this._minY : other._minY; + aabb._minZ = this._minZ < other._minZ ? this._minZ : other._minZ; + aabb._maxX = this._maxX > other._maxX ? this._maxX : other._maxX; + aabb._maxY = this._maxY > other._maxY ? this._maxY : other._maxY; + aabb._maxZ = this._maxZ > other._maxZ ? this._maxZ : other._maxZ; + return aabb; + } + overlap(other) { + if(this._minX < other._maxX && this._maxX > other._minX && this._minY < other._maxY && this._maxY > other._minY && this._minZ < other._maxZ) { + return this._maxZ > other._minZ; + } else { + return false; + } + } + getIntersection(other) { + let aabb = new oimo.collision.geometry.Aabb(); + aabb._minX = this._minX > other._minX ? this._minX : other._minX; + aabb._minY = this._minY > other._minY ? this._minY : other._minY; + aabb._minZ = this._minZ > other._minZ ? this._minZ : other._minZ; + aabb._maxX = this._maxX < other._maxX ? this._maxX : other._maxX; + aabb._maxY = this._maxY < other._maxY ? this._maxY : other._maxY; + aabb._maxZ = this._maxZ < other._maxZ ? this._maxZ : other._maxZ; + return aabb; + } + getIntersectionTo(other,intersection) { + intersection._minX = this._minX > other._minX ? this._minX : other._minX; + intersection._minY = this._minY > other._minY ? this._minY : other._minY; + intersection._minZ = this._minZ > other._minZ ? this._minZ : other._minZ; + intersection._maxX = this._maxX < other._maxX ? this._maxX : other._maxX; + intersection._maxY = this._maxY < other._maxY ? this._maxY : other._maxY; + intersection._maxZ = this._maxZ < other._maxZ ? this._maxZ : other._maxZ; + } + copyFrom(aabb) { + this._minX = aabb._minX; + this._minY = aabb._minY; + this._minZ = aabb._minZ; + this._maxX = aabb._maxX; + this._maxY = aabb._maxY; + this._maxZ = aabb._maxZ; + return this; + } + clone() { + let aabb = new oimo.collision.geometry.Aabb(); + aabb._minX = this._minX; + aabb._minY = this._minY; + aabb._minZ = this._minZ; + aabb._maxX = this._maxX; + aabb._maxY = this._maxY; + aabb._maxZ = this._maxZ; + return aabb; + } +} +oimo.collision.geometry.BoxGeometry = class oimo_collision_geometry_BoxGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(halfExtents) { + super(1); + this._halfExtentsX = halfExtents.x; + this._halfExtentsY = halfExtents.y; + this._halfExtentsZ = halfExtents.z; + this._halfAxisXX = halfExtents.x; + this._halfAxisXY = 0; + this._halfAxisXZ = 0; + this._halfAxisYX = 0; + this._halfAxisYY = halfExtents.y; + this._halfAxisYZ = 0; + this._halfAxisZX = 0; + this._halfAxisZY = 0; + this._halfAxisZZ = halfExtents.z; + this._updateMass(); + let minHalfExtents = halfExtents.x < halfExtents.y ? halfExtents.z < halfExtents.x ? halfExtents.z : halfExtents.x : halfExtents.z < halfExtents.y ? halfExtents.z : halfExtents.y; + if(this._gjkMargin > minHalfExtents * 0.2) { + this._gjkMargin = minHalfExtents * 0.2; + } + } + getHalfExtents() { + let v = new oimo.common.Vec3(); + v.x = this._halfExtentsX; + v.y = this._halfExtentsY; + v.z = this._halfExtentsZ; + return v; + } + getHalfExtentsTo(halfExtents) { + halfExtents.x = this._halfExtentsX; + halfExtents.y = this._halfExtentsY; + halfExtents.z = this._halfExtentsZ; + } + _updateMass() { + this._volume = 8 * (this._halfExtentsX * this._halfExtentsY * this._halfExtentsZ); + let sqX; + let sqY; + let sqZ; + sqX = this._halfExtentsX * this._halfExtentsX; + sqY = this._halfExtentsY * this._halfExtentsY; + sqZ = this._halfExtentsZ * this._halfExtentsZ; + this._inertiaCoeff00 = 0.33333333333333331 * (sqY + sqZ); + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 0.33333333333333331 * (sqZ + sqX); + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 0.33333333333333331 * (sqX + sqY); + } + _computeAabb(aabb,tf) { + let tfxX; + let tfxY; + let tfxZ; + let tfyX; + let tfyY; + let tfyZ; + let tfzX; + let tfzY; + let tfzZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf._rotation00 * this._halfAxisXX + tf._rotation01 * this._halfAxisXY + tf._rotation02 * this._halfAxisXZ; + __tmp__Y = tf._rotation10 * this._halfAxisXX + tf._rotation11 * this._halfAxisXY + tf._rotation12 * this._halfAxisXZ; + __tmp__Z = tf._rotation20 * this._halfAxisXX + tf._rotation21 * this._halfAxisXY + tf._rotation22 * this._halfAxisXZ; + tfxX = __tmp__X; + tfxY = __tmp__Y; + tfxZ = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf._rotation00 * this._halfAxisYX + tf._rotation01 * this._halfAxisYY + tf._rotation02 * this._halfAxisYZ; + __tmp__Y1 = tf._rotation10 * this._halfAxisYX + tf._rotation11 * this._halfAxisYY + tf._rotation12 * this._halfAxisYZ; + __tmp__Z1 = tf._rotation20 * this._halfAxisYX + tf._rotation21 * this._halfAxisYY + tf._rotation22 * this._halfAxisYZ; + tfyX = __tmp__X1; + tfyY = __tmp__Y1; + tfyZ = __tmp__Z1; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = tf._rotation00 * this._halfAxisZX + tf._rotation01 * this._halfAxisZY + tf._rotation02 * this._halfAxisZZ; + __tmp__Y2 = tf._rotation10 * this._halfAxisZX + tf._rotation11 * this._halfAxisZY + tf._rotation12 * this._halfAxisZZ; + __tmp__Z2 = tf._rotation20 * this._halfAxisZX + tf._rotation21 * this._halfAxisZY + tf._rotation22 * this._halfAxisZZ; + tfzX = __tmp__X2; + tfzY = __tmp__Y2; + tfzZ = __tmp__Z2; + if(tfxX < 0) { + tfxX = -tfxX; + } + if(tfxY < 0) { + tfxY = -tfxY; + } + if(tfxZ < 0) { + tfxZ = -tfxZ; + } + if(tfyX < 0) { + tfyX = -tfyX; + } + if(tfyY < 0) { + tfyY = -tfyY; + } + if(tfyZ < 0) { + tfyZ = -tfyZ; + } + if(tfzX < 0) { + tfzX = -tfzX; + } + if(tfzY < 0) { + tfzY = -tfzY; + } + if(tfzZ < 0) { + tfzZ = -tfzZ; + } + let tfsX; + let tfsY; + let tfsZ; + tfsX = tfxX + tfyX; + tfsY = tfxY + tfyY; + tfsZ = tfxZ + tfyZ; + tfsX += tfzX; + tfsY += tfzY; + tfsZ += tfzZ; + aabb._minX = tf._positionX - tfsX; + aabb._minY = tf._positionY - tfsY; + aabb._minZ = tf._positionZ - tfsZ; + aabb._maxX = tf._positionX + tfsX; + aabb._maxY = tf._positionY + tfsY; + aabb._maxZ = tf._positionZ + tfsZ; + } + computeLocalSupportingVertex(dir,out) { + let gjkMarginsX; + let gjkMarginsY; + let gjkMarginsZ; + let coreExtentsX; + let coreExtentsY; + let coreExtentsZ; + gjkMarginsX = this._gjkMargin; + gjkMarginsY = this._gjkMargin; + gjkMarginsZ = this._gjkMargin; + if(!(gjkMarginsX < this._halfExtentsX)) { + gjkMarginsX = this._halfExtentsX; + } + if(!(gjkMarginsY < this._halfExtentsY)) { + gjkMarginsY = this._halfExtentsY; + } + if(!(gjkMarginsZ < this._halfExtentsZ)) { + gjkMarginsZ = this._halfExtentsZ; + } + coreExtentsX = this._halfExtentsX - gjkMarginsX; + coreExtentsY = this._halfExtentsY - gjkMarginsY; + coreExtentsZ = this._halfExtentsZ - gjkMarginsZ; + out.x = dir.x > 0 ? coreExtentsX : -coreExtentsX; + out.y = dir.y > 0 ? coreExtentsY : -coreExtentsY; + out.z = dir.z > 0 ? coreExtentsZ : -coreExtentsZ; + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + let halfW = this._halfExtentsX; + let halfH = this._halfExtentsY; + let halfD = this._halfExtentsZ; + let dx = endX - beginX; + let dy = endY - beginY; + let dz = endZ - beginZ; + let tminx = 0; + let tminy = 0; + let tminz = 0; + let tmaxx = 1; + let tmaxy = 1; + let tmaxz = 1; + if(dx > -1e-6 && dx < 1e-6) { + if(beginX <= -halfW || beginX >= halfW) { + return false; + } + } else { + let invDx = 1 / dx; + let t1 = (-halfW - beginX) * invDx; + let t2 = (halfW - beginX) * invDx; + if(t1 > t2) { + let tmp = t1; + t1 = t2; + t2 = tmp; + } + if(t1 > 0) { + tminx = t1; + } + if(t2 < 1) { + tmaxx = t2; + } + } + if(dy > -1e-6 && dy < 1e-6) { + if(beginY <= -halfH || beginY >= halfH) { + return false; + } + } else { + let invDy = 1 / dy; + let t1 = (-halfH - beginY) * invDy; + let t2 = (halfH - beginY) * invDy; + if(t1 > t2) { + let tmp = t1; + t1 = t2; + t2 = tmp; + } + if(t1 > 0) { + tminy = t1; + } + if(t2 < 1) { + tmaxy = t2; + } + } + if(dz > -1e-6 && dz < 1e-6) { + if(beginZ <= -halfD || beginZ >= halfD) { + return false; + } + } else { + let invDz = 1 / dz; + let t1 = (-halfD - beginZ) * invDz; + let t2 = (halfD - beginZ) * invDz; + if(t1 > t2) { + let tmp = t1; + t1 = t2; + t2 = tmp; + } + if(t1 > 0) { + tminz = t1; + } + if(t2 < 1) { + tmaxz = t2; + } + } + if(tminx >= 1 || tminy >= 1 || tminz >= 1 || tmaxx <= 0 || tmaxy <= 0 || tmaxz <= 0) { + return false; + } + let min = tminx; + let max = tmaxx; + let hitDirection = 0; + if(tminy > min) { + min = tminy; + hitDirection = 1; + } + if(tminz > min) { + min = tminz; + hitDirection = 2; + } + if(tmaxy < max) { + max = tmaxy; + } + if(tmaxz < max) { + max = tmaxz; + } + if(min > max) { + return false; + } + if(min == 0) { + return false; + } + switch(hitDirection) { + case 0: + hit.normal.init(dx > 0 ? -1 : 1,0,0); + break; + case 1: + hit.normal.init(0,dy > 0 ? -1 : 1,0); + break; + case 2: + hit.normal.init(0,0,dz > 0 ? -1 : 1); + break; + } + hit.position.init(beginX + min * dx,beginY + min * dy,beginZ + min * dz); + hit.fraction = min; + return true; + } +} +oimo.collision.geometry.CapsuleGeometry = class oimo_collision_geometry_CapsuleGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(radius,halfHeight) { + super(4); + this._radius = radius; + this._halfHeight = halfHeight; + this._gjkMargin = this._radius; + this._updateMass(); + } + getRadius() { + return this._radius; + } + getHalfHeight() { + return this._halfHeight; + } + _updateMass() { + let r2 = this._radius * this._radius; + let hh2 = this._halfHeight * this._halfHeight; + let cylinderVolume = 6.28318530717958 * r2 * this._halfHeight; + let sphereVolume = 3.14159265358979 * r2 * this._radius * 4 / 3; + this._volume = cylinderVolume + sphereVolume; + let invVolume = this._volume == 0 ? 0 : 1 / this._volume; + let inertiaXZ = invVolume * (cylinderVolume * (r2 * 0.25 + hh2 / 3) + sphereVolume * (r2 * 0.4 + this._halfHeight * this._radius * 0.75 + hh2)); + this._inertiaCoeff00 = inertiaXZ; + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = invVolume * (cylinderVolume * r2 * 0.5 + sphereVolume * r2 * 0.4); + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = inertiaXZ; + } + _computeAabb(aabb,tf) { + let radVecX; + let radVecY; + let radVecZ; + radVecX = this._radius; + radVecY = this._radius; + radVecZ = this._radius; + let axisX; + let axisY; + let axisZ; + axisX = tf._rotation01; + axisY = tf._rotation11; + axisZ = tf._rotation21; + if(axisX < 0) { + axisX = -axisX; + } + if(axisY < 0) { + axisY = -axisY; + } + if(axisZ < 0) { + axisZ = -axisZ; + } + axisX *= this._halfHeight; + axisY *= this._halfHeight; + axisZ *= this._halfHeight; + radVecX += axisX; + radVecY += axisY; + radVecZ += axisZ; + aabb._minX = tf._positionX - radVecX; + aabb._minY = tf._positionY - radVecY; + aabb._minZ = tf._positionZ - radVecZ; + aabb._maxX = tf._positionX + radVecX; + aabb._maxY = tf._positionY + radVecY; + aabb._maxZ = tf._positionZ + radVecZ; + } + computeLocalSupportingVertex(dir,out) { + if(dir.y > 0) { + out.init(0,this._halfHeight,0); + } else { + out.init(0,-this._halfHeight,0); + } + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + let halfH = this._halfHeight; + let dx = endX - beginX; + let dz = endZ - beginZ; + let tminxz = 0; + let tmaxxz; + let a = dx * dx + dz * dz; + let b = beginX * dx + beginZ * dz; + let c = beginX * beginX + beginZ * beginZ - this._radius * this._radius; + let D = b * b - a * c; + if(D < 0) { + return false; + } + if(a > 0) { + let sqrtD = Math.sqrt(D); + tminxz = (-b - sqrtD) / a; + tmaxxz = (-b + sqrtD) / a; + if(tminxz >= 1 || tmaxxz <= 0) { + return false; + } + } else { + if(c >= 0) { + return false; + } + tminxz = 0; + } + let crossY = beginY + (endY - beginY) * tminxz; + let min; + if(crossY > -halfH && crossY < halfH) { + if(tminxz > 0) { + min = tminxz; + let _this = hit.normal.init(beginX + dx * min,0,beginZ + dz * min); + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + hit.position.init(beginX + min * dx,crossY,beginZ + min * dz); + hit.fraction = min; + return true; + } + return false; + } + let spherePosX; + let spherePosY; + let spherePosZ; + let sphereToBeginX; + let sphereToBeginY; + let sphereToBeginZ; + spherePosX = 0; + spherePosY = crossY < 0 ? -halfH : halfH; + spherePosZ = 0; + sphereToBeginX = beginX - spherePosX; + sphereToBeginY = beginY - spherePosY; + sphereToBeginZ = beginZ - spherePosZ; + let dX; + let dY; + let dZ; + dX = endX - beginX; + dY = endY - beginY; + dZ = endZ - beginZ; + a = dX * dX + dY * dY + dZ * dZ; + b = sphereToBeginX * dX + sphereToBeginY * dY + sphereToBeginZ * dZ; + c = sphereToBeginX * sphereToBeginX + sphereToBeginY * sphereToBeginY + sphereToBeginZ * sphereToBeginZ - this._radius * this._radius; + D = b * b - a * c; + if(D < 0) { + return false; + } + let t = (-b - Math.sqrt(D)) / a; + if(t < 0 || t > 1) { + return false; + } + let hitPosX; + let hitPosY; + let hitPosZ; + let hitNormalX; + let hitNormalY; + let hitNormalZ; + hitPosX = sphereToBeginX + dX * t; + hitPosY = sphereToBeginY + dY * t; + hitPosZ = sphereToBeginZ + dZ * t; + let l = hitPosX * hitPosX + hitPosY * hitPosY + hitPosZ * hitPosZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + hitNormalX = hitPosX * l; + hitNormalY = hitPosY * l; + hitNormalZ = hitPosZ * l; + hitPosX += spherePosX; + hitPosY += spherePosY; + hitPosZ += spherePosZ; + let v = hit.position; + v.x = hitPosX; + v.y = hitPosY; + v.z = hitPosZ; + let v1 = hit.normal; + v1.x = hitNormalX; + v1.y = hitNormalY; + v1.z = hitNormalZ; + hit.fraction = t; + return true; + } +} +oimo.collision.geometry.ConeGeometry = class oimo_collision_geometry_ConeGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(radius,halfHeight) { + super(3); + this._radius = radius; + this._halfHeight = halfHeight; + this.sinTheta = radius / Math.sqrt(radius * radius + 4 * halfHeight * halfHeight); + this.cosTheta = 2 * halfHeight / Math.sqrt(radius * radius + 4 * halfHeight * halfHeight); + this._updateMass(); + } + getRadius() { + return this._radius; + } + getHalfHeight() { + return this._halfHeight; + } + _updateMass() { + let r2 = this._radius * this._radius; + let h2 = this._halfHeight * this._halfHeight * 4; + this._volume = 3.14159265358979 * r2 * this._halfHeight * 2 / 3; + this._inertiaCoeff00 = 0.05 * (3 * r2 + 2 * h2); + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 0.3 * r2; + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 0.05 * (3 * r2 + 2 * h2); + } + _computeAabb(aabb,tf) { + let axisX; + let axisY; + let axisZ; + let axis2X; + let axis2Y; + let axis2Z; + let ehX; + let ehY; + let ehZ; + let erX; + let erY; + let erZ; + axisX = tf._rotation01; + axisY = tf._rotation11; + axisZ = tf._rotation21; + axis2X = axisX * axisX; + axis2Y = axisY * axisY; + axis2Z = axisZ * axisZ; + erX = Math.sqrt(1 - axis2X); + erY = Math.sqrt(1 - axis2Y); + erZ = Math.sqrt(1 - axis2Z); + erX *= this._radius; + erY *= this._radius; + erZ *= this._radius; + ehX = axisX * this._halfHeight; + ehY = axisY * this._halfHeight; + ehZ = axisZ * this._halfHeight; + let rminX; + let rminY; + let rminZ; + let rmaxX; + let rmaxY; + let rmaxZ; + rminX = -ehX; + rminY = -ehY; + rminZ = -ehZ; + rminX -= erX; + rminY -= erY; + rminZ -= erZ; + rmaxX = -ehX; + rmaxY = -ehY; + rmaxZ = -ehZ; + rmaxX += erX; + rmaxY += erY; + rmaxZ += erZ; + let maxX; + let maxY; + let maxZ; + let minX; + let minY; + let minZ; + maxX = rminX > rmaxX ? rminX : rmaxX; + maxY = rminY > rmaxY ? rminY : rmaxY; + maxZ = rminZ > rmaxZ ? rminZ : rmaxZ; + if(!(maxX > ehX)) { + maxX = ehX; + } + if(!(maxY > ehY)) { + maxY = ehY; + } + if(!(maxZ > ehZ)) { + maxZ = ehZ; + } + minX = rminX < rmaxX ? rminX : rmaxX; + minY = rminY < rmaxY ? rminY : rmaxY; + minZ = rminZ < rmaxZ ? rminZ : rmaxZ; + if(!(minX < ehX)) { + minX = ehX; + } + if(!(minY < ehY)) { + minY = ehY; + } + if(!(minZ < ehZ)) { + minZ = ehZ; + } + aabb._minX = tf._positionX + minX; + aabb._minY = tf._positionY + minY; + aabb._minZ = tf._positionZ + minZ; + aabb._maxX = tf._positionX + maxX; + aabb._maxY = tf._positionY + maxY; + aabb._maxZ = tf._positionZ + maxZ; + } + computeLocalSupportingVertex(dir,out) { + let dx = dir.x; + let dy = dir.y; + let dz = dir.z; + if(dy > 0 && dy * dy > this.sinTheta * this.sinTheta * (dx * dx + dy * dy + dz * dz)) { + out.init(0,this._halfHeight - this._gjkMargin / this.sinTheta,0); + if(out.y < 0) { + out.y = 0; + } + return; + } + let rx = dir.x; + let rz = dir.z; + let len = rx * rx + rz * rz; + let height = 2 * this._halfHeight; + let coreRadius = (height - this._gjkMargin) / height * this._radius - this._gjkMargin / this.cosTheta; + if(coreRadius < 0) { + coreRadius = 0; + } + let invLen = len > 0 ? coreRadius / Math.sqrt(len) : 0; + let coreHalfHeight = this._halfHeight - this._gjkMargin; + if(coreHalfHeight < 0) { + coreHalfHeight = 0; + } + out.x = rx * invLen; + out.y = -coreHalfHeight; + out.z = rz * invLen; + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + let p1y; + let halfH = this._halfHeight; + let dx = endX - beginX; + let dy = endY - beginY; + let dz = endZ - beginZ; + let tminy = 0; + let tmaxy = 1; + if(dy > -1e-6 && dy < 1e-6) { + if(beginY <= -halfH || beginY >= halfH) { + return false; + } + } else { + let invDy = 1 / dy; + let t1 = (-halfH - beginY) * invDy; + let t2 = (halfH - beginY) * invDy; + if(t1 > t2) { + let tmp = t1; + t1 = t2; + t2 = tmp; + } + if(t1 > 0) { + tminy = t1; + } + if(t2 < 1) { + tmaxy = t2; + } + } + if(tminy >= 1 || tmaxy <= 0) { + return false; + } + let tminxz = 0; + let tmaxxz = 0; + p1y = beginY - halfH; + let cos2 = this.cosTheta * this.cosTheta; + let a = cos2 * (dx * dx + dy * dy + dz * dz) - dy * dy; + let b = cos2 * (beginX * dx + p1y * dy + beginZ * dz) - p1y * dy; + let c = cos2 * (beginX * beginX + p1y * p1y + beginZ * beginZ) - p1y * p1y; + let D = b * b - a * c; + if(a != 0) { + if(D < 0) { + return false; + } + let sqrtD = Math.sqrt(D); + if(a < 0) { + if(dy > 0) { + tminxz = 0; + tmaxxz = (-b + sqrtD) / a; + if(tmaxxz <= 0) { + return false; + } + } else { + tminxz = (-b - sqrtD) / a; + tmaxxz = 1; + if(tminxz >= 1) { + return false; + } + } + } else { + tminxz = (-b - sqrtD) / a; + tmaxxz = (-b + sqrtD) / a; + if(tminxz >= 1 || tmaxxz <= 0) { + return false; + } + } + } else { + let t = -c / (2 * b); + if(b > 0) { + tminxz = 0; + tmaxxz = t; + if(t <= 0) { + return false; + } + } else { + tminxz = t; + tmaxxz = 1; + if(t >= 1) { + return false; + } + } + } + p1y += halfH; + let min; + if(tmaxxz <= tminy || tmaxy <= tminxz) { + return false; + } + if(tminxz < tminy) { + min = tminy; + if(min == 0) { + return false; + } + hit.normal.init(0,dy > 0 ? -1 : 1,0); + } else { + min = tminxz; + if(min == 0) { + return false; + } + let _this = hit.normal.init(beginX + dx * min,0,beginZ + dz * min); + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + let s = this.cosTheta; + _this.x *= s; + _this.y *= s; + _this.z *= s; + hit.normal.y += this.sinTheta; + } + hit.position.init(beginX + min * dx,p1y + min * dy,beginZ + min * dz); + hit.fraction = min; + return true; + } +} +oimo.collision.geometry.ConvexHullGeometry = class oimo_collision_geometry_ConvexHullGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(vertices) { + super(5); + this._numVertices = vertices.length; + this._vertices = new Array(this._numVertices); + this._tmpVertices = new Array(this._numVertices); + let _g = 0; + let _g1 = this._numVertices; + while(_g < _g1) { + let i = _g++; + this._vertices[i] = vertices[i]; + this._tmpVertices[i] = new oimo.common.Vec3(); + } + this._useGjkRayCast = true; + this._updateMass(); + } + getVertices() { + return this._vertices; + } + _updateMass() { + this._volume = 1; + this._inertiaCoeff00 = 1; + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 1; + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 1; + let minx = this._vertices[0].x; + let miny = this._vertices[0].y; + let minz = this._vertices[0].z; + let maxx = this._vertices[0].x; + let maxy = this._vertices[0].y; + let maxz = this._vertices[0].z; + let _g = 1; + let _g1 = this._numVertices; + while(_g < _g1) { + let i = _g++; + let vx = this._vertices[i].x; + let vy = this._vertices[i].y; + let vz = this._vertices[i].z; + if(vx < minx) { + minx = vx; + } else if(vx > maxx) { + maxx = vx; + } + if(vy < miny) { + miny = vy; + } else if(vy > maxy) { + maxy = vy; + } + if(vz < minz) { + minz = vz; + } else if(vz > maxz) { + maxz = vz; + } + } + let sizex = maxx - minx; + let sizey = maxy - miny; + let sizez = maxz - minz; + this._volume = sizex * sizey * sizez; + let diffCog = ((minx + maxx) * (minx + maxx) + (miny + maxy) * (miny + maxy) + (minz + maxz) * (minz + maxz)) * 0.25; + sizex = sizex * sizex * 0.25; + sizey = sizey * sizey * 0.25; + sizez = sizez * sizez * 0.25; + this._inertiaCoeff00 = 0.33333333333333331 * (sizey + sizez) + diffCog; + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 0.33333333333333331 * (sizez + sizex) + diffCog; + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 0.33333333333333331 * (sizex + sizey) + diffCog; + } + _computeAabb(aabb,tf) { + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + let marginX; + let marginY; + let marginZ; + marginX = this._gjkMargin; + marginY = this._gjkMargin; + marginZ = this._gjkMargin; + let localVX; + let localVY; + let localVZ; + let v = this._vertices[0]; + localVX = v.x; + localVY = v.y; + localVZ = v.z; + let worldVX; + let worldVY; + let worldVZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf._rotation00 * localVX + tf._rotation01 * localVY + tf._rotation02 * localVZ; + __tmp__Y = tf._rotation10 * localVX + tf._rotation11 * localVY + tf._rotation12 * localVZ; + __tmp__Z = tf._rotation20 * localVX + tf._rotation21 * localVY + tf._rotation22 * localVZ; + worldVX = __tmp__X; + worldVY = __tmp__Y; + worldVZ = __tmp__Z; + worldVX += tf._positionX; + worldVY += tf._positionY; + worldVZ += tf._positionZ; + minX = worldVX; + minY = worldVY; + minZ = worldVZ; + maxX = worldVX; + maxY = worldVY; + maxZ = worldVZ; + let _g = 1; + let _g1 = this._numVertices; + while(_g < _g1) { + let v = this._vertices[_g++]; + localVX = v.x; + localVY = v.y; + localVZ = v.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf._rotation00 * localVX + tf._rotation01 * localVY + tf._rotation02 * localVZ; + __tmp__Y = tf._rotation10 * localVX + tf._rotation11 * localVY + tf._rotation12 * localVZ; + __tmp__Z = tf._rotation20 * localVX + tf._rotation21 * localVY + tf._rotation22 * localVZ; + worldVX = __tmp__X; + worldVY = __tmp__Y; + worldVZ = __tmp__Z; + worldVX += tf._positionX; + worldVY += tf._positionY; + worldVZ += tf._positionZ; + if(!(minX < worldVX)) { + minX = worldVX; + } + if(!(minY < worldVY)) { + minY = worldVY; + } + if(!(minZ < worldVZ)) { + minZ = worldVZ; + } + if(!(maxX > worldVX)) { + maxX = worldVX; + } + if(!(maxY > worldVY)) { + maxY = worldVY; + } + if(!(maxZ > worldVZ)) { + maxZ = worldVZ; + } + } + aabb._minX = minX - marginX; + aabb._minY = minY - marginY; + aabb._minZ = minZ - marginZ; + aabb._maxX = maxX + marginX; + aabb._maxY = maxY + marginY; + aabb._maxZ = maxZ + marginZ; + } + computeLocalSupportingVertex(dir,out) { + let _this = this._vertices[0]; + let maxDot = _this.x * dir.x + _this.y * dir.y + _this.z * dir.z; + let maxIndex = 0; + let _g = 1; + let _g1 = this._numVertices; + while(_g < _g1) { + let i = _g++; + let _this = this._vertices[i]; + let dot = _this.x * dir.x + _this.y * dir.y + _this.z * dir.z; + if(dot > maxDot) { + maxDot = dot; + maxIndex = i; + } + } + let v = this._vertices[maxIndex]; + out.x = v.x; + out.y = v.y; + out.z = v.z; + } +} +oimo.collision.geometry.CylinderGeometry = class oimo_collision_geometry_CylinderGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(radius,halfHeight) { + super(2); + this._radius = radius; + this._halfHeight = halfHeight; + this._updateMass(); + } + getRadius() { + return this._radius; + } + getHalfHeight() { + return this._halfHeight; + } + _updateMass() { + let r2 = this._radius * this._radius; + let h2 = this._halfHeight * this._halfHeight * 4; + this._volume = 3.14159265358979 * r2 * this._halfHeight * 2; + this._inertiaCoeff00 = 0.083333333333333329 * (3 * r2 + h2); + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 0.5 * r2; + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 0.083333333333333329 * (3 * r2 + h2); + } + _computeAabb(aabb,tf) { + let axisX; + let axisY; + let axisZ; + let axis2X; + let axis2Y; + let axis2Z; + let ehX; + let ehY; + let ehZ; + let erX; + let erY; + let erZ; + axisX = tf._rotation01; + axisY = tf._rotation11; + axisZ = tf._rotation21; + if(axisX < 0) { + axisX = -axisX; + } + if(axisY < 0) { + axisY = -axisY; + } + if(axisZ < 0) { + axisZ = -axisZ; + } + axis2X = axisX * axisX; + axis2Y = axisY * axisY; + axis2Z = axisZ * axisZ; + erX = Math.sqrt(1 - axis2X); + erY = Math.sqrt(1 - axis2Y); + erZ = Math.sqrt(1 - axis2Z); + erX *= this._radius; + erY *= this._radius; + erZ *= this._radius; + ehX = axisX * this._halfHeight; + ehY = axisY * this._halfHeight; + ehZ = axisZ * this._halfHeight; + let maxX; + let maxY; + let maxZ; + maxX = erX + ehX; + maxY = erY + ehY; + maxZ = erZ + ehZ; + aabb._minX = tf._positionX - maxX; + aabb._minY = tf._positionY - maxY; + aabb._minZ = tf._positionZ - maxZ; + aabb._maxX = tf._positionX + maxX; + aabb._maxY = tf._positionY + maxY; + aabb._maxZ = tf._positionZ + maxZ; + } + computeLocalSupportingVertex(dir,out) { + let rx = dir.x; + let rz = dir.z; + let len = rx * rx + rz * rz; + let coreRadius = this._radius - this._gjkMargin; + if(coreRadius < 0) { + coreRadius = 0; + } + let invLen = len > 0 ? coreRadius / Math.sqrt(len) : 0; + let coreHeight = this._halfHeight - this._gjkMargin; + if(coreHeight < 0) { + coreHeight = 0; + } + out.x = rx * invLen; + out.y = dir.y > 0 ? coreHeight : -coreHeight; + out.z = rz * invLen; + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + let halfH = this._halfHeight; + let dx = endX - beginX; + let dy = endY - beginY; + let dz = endZ - beginZ; + let tminy = 0; + let tmaxy = 1; + if(dy > -1e-6 && dy < 1e-6) { + if(beginY <= -halfH || beginY >= halfH) { + return false; + } + } else { + let invDy = 1 / dy; + let t1 = (-halfH - beginY) * invDy; + let t2 = (halfH - beginY) * invDy; + if(t1 > t2) { + let tmp = t1; + t1 = t2; + t2 = tmp; + } + if(t1 > 0) { + tminy = t1; + } + if(t2 < 1) { + tmaxy = t2; + } + } + if(tminy >= 1 || tmaxy <= 0) { + return false; + } + let tminxz = 0; + let tmaxxz; + let a = dx * dx + dz * dz; + let b = beginX * dx + beginZ * dz; + let c = beginX * beginX + beginZ * beginZ - this._radius * this._radius; + let D = b * b - a * c; + if(D < 0) { + return false; + } + if(a > 0) { + let sqrtD = Math.sqrt(D); + tminxz = (-b - sqrtD) / a; + tmaxxz = (-b + sqrtD) / a; + if(tminxz >= 1 || tmaxxz <= 0) { + return false; + } + } else { + if(c >= 0) { + return false; + } + tminxz = 0; + tmaxxz = 1; + } + let min; + if(tmaxxz <= tminy || tmaxy <= tminxz) { + return false; + } + if(tminxz < tminy) { + min = tminy; + if(min == 0) { + return false; + } + hit.normal.init(0,dy > 0 ? -1 : 1,0); + } else { + min = tminxz; + if(min == 0) { + return false; + } + let _this = hit.normal.init(beginX + dx * min,0,beginZ + dz * min); + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + } + hit.position.init(beginX + min * dx,beginY + min * dy,beginZ + min * dz); + hit.fraction = min; + return true; + } +} +oimo.collision.geometry.GeometryType = class oimo_collision_geometry_GeometryType { +} +oimo.collision.geometry.RayCastHit = class oimo_collision_geometry_RayCastHit { + constructor() { + this.position = new oimo.common.Vec3(); + this.normal = new oimo.common.Vec3(); + this.fraction = 0; + } +} +oimo.collision.geometry.SphereGeometry = class oimo_collision_geometry_SphereGeometry extends oimo.collision.geometry.ConvexGeometry { + constructor(radius) { + super(0); + this._radius = radius; + this._gjkMargin = this._radius; + this._updateMass(); + } + getRadius() { + return this._radius; + } + _updateMass() { + this._volume = 4.1887902047863861 * this._radius * this._radius * this._radius; + this._inertiaCoeff00 = 0.4 * this._radius * this._radius; + this._inertiaCoeff01 = 0; + this._inertiaCoeff02 = 0; + this._inertiaCoeff10 = 0; + this._inertiaCoeff11 = 0.4 * this._radius * this._radius; + this._inertiaCoeff12 = 0; + this._inertiaCoeff20 = 0; + this._inertiaCoeff21 = 0; + this._inertiaCoeff22 = 0.4 * this._radius * this._radius; + } + _computeAabb(aabb,tf) { + let radVecX; + let radVecY; + let radVecZ; + radVecX = this._radius; + radVecY = this._radius; + radVecZ = this._radius; + aabb._minX = tf._positionX - radVecX; + aabb._minY = tf._positionY - radVecY; + aabb._minZ = tf._positionZ - radVecZ; + aabb._maxX = tf._positionX + radVecX; + aabb._maxY = tf._positionY + radVecY; + aabb._maxZ = tf._positionZ + radVecZ; + } + computeLocalSupportingVertex(dir,out) { + out.zero(); + } + _rayCastLocal(beginX,beginY,beginZ,endX,endY,endZ,hit) { + let dX; + let dY; + let dZ; + dX = endX - beginX; + dY = endY - beginY; + dZ = endZ - beginZ; + let a = dX * dX + dY * dY + dZ * dZ; + let b = beginX * dX + beginY * dY + beginZ * dZ; + let D = b * b - a * (beginX * beginX + beginY * beginY + beginZ * beginZ - this._radius * this._radius); + if(D < 0) { + return false; + } + let t = (-b - Math.sqrt(D)) / a; + if(t < 0 || t > 1) { + return false; + } + let hitPosX; + let hitPosY; + let hitPosZ; + let hitNormalX; + let hitNormalY; + let hitNormalZ; + hitPosX = beginX + dX * t; + hitPosY = beginY + dY * t; + hitPosZ = beginZ + dZ * t; + let l = hitPosX * hitPosX + hitPosY * hitPosY + hitPosZ * hitPosZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + hitNormalX = hitPosX * l; + hitNormalY = hitPosY * l; + hitNormalZ = hitPosZ * l; + let v = hit.position; + v.x = hitPosX; + v.y = hitPosY; + v.z = hitPosZ; + let v1 = hit.normal; + v1.x = hitNormalX; + v1.y = hitNormalY; + v1.z = hitNormalZ; + hit.fraction = t; + return true; + } +} +if(!oimo.collision.narrowphase) oimo.collision.narrowphase = {}; +oimo.collision.narrowphase.CollisionMatrix = class oimo_collision_narrowphase_CollisionMatrix { + constructor() { + this.detectors = new Array(8); + this.detectors[0] = new Array(8); + this.detectors[1] = new Array(8); + this.detectors[2] = new Array(8); + this.detectors[3] = new Array(8); + this.detectors[4] = new Array(8); + this.detectors[5] = new Array(8); + let gjkEpaDetector = new oimo.collision.narrowphase.detector.GjkEpaDetector(); + this.detectors[0][0] = new oimo.collision.narrowphase.detector.SphereSphereDetector(); + this.detectors[0][1] = new oimo.collision.narrowphase.detector.SphereBoxDetector(false); + this.detectors[0][2] = gjkEpaDetector; + this.detectors[0][3] = gjkEpaDetector; + this.detectors[0][4] = new oimo.collision.narrowphase.detector.SphereCapsuleDetector(false); + this.detectors[0][5] = gjkEpaDetector; + this.detectors[1][0] = new oimo.collision.narrowphase.detector.SphereBoxDetector(true); + this.detectors[1][1] = new oimo.collision.narrowphase.detector.BoxBoxDetector(); + this.detectors[1][2] = gjkEpaDetector; + this.detectors[1][3] = gjkEpaDetector; + this.detectors[1][4] = gjkEpaDetector; + this.detectors[1][5] = gjkEpaDetector; + this.detectors[2][0] = gjkEpaDetector; + this.detectors[2][1] = gjkEpaDetector; + this.detectors[2][2] = gjkEpaDetector; + this.detectors[2][3] = gjkEpaDetector; + this.detectors[2][4] = gjkEpaDetector; + this.detectors[2][5] = gjkEpaDetector; + this.detectors[3][0] = gjkEpaDetector; + this.detectors[3][1] = gjkEpaDetector; + this.detectors[3][2] = gjkEpaDetector; + this.detectors[3][3] = gjkEpaDetector; + this.detectors[3][4] = gjkEpaDetector; + this.detectors[3][5] = gjkEpaDetector; + this.detectors[4][0] = new oimo.collision.narrowphase.detector.SphereCapsuleDetector(true); + this.detectors[4][1] = gjkEpaDetector; + this.detectors[4][2] = gjkEpaDetector; + this.detectors[4][3] = gjkEpaDetector; + this.detectors[4][4] = new oimo.collision.narrowphase.detector.CapsuleCapsuleDetector(); + this.detectors[4][5] = gjkEpaDetector; + this.detectors[5][0] = gjkEpaDetector; + this.detectors[5][1] = gjkEpaDetector; + this.detectors[5][2] = gjkEpaDetector; + this.detectors[5][3] = gjkEpaDetector; + this.detectors[5][4] = gjkEpaDetector; + this.detectors[5][5] = gjkEpaDetector; + } + getDetector(geomType1,geomType2) { + return this.detectors[geomType1][geomType2]; + } +} +oimo.collision.narrowphase.DetectorResult = class oimo_collision_narrowphase_DetectorResult { + constructor() { + this.numPoints = 0; + this.normal = new oimo.common.Vec3(); + this.points = new Array(oimo.common.Setting.maxManifoldPoints); + this.incremental = false; + let _g = 0; + let _g1 = oimo.common.Setting.maxManifoldPoints; + while(_g < _g1) this.points[_g++] = new oimo.collision.narrowphase.DetectorResultPoint(); + } + getMaxDepth() { + let max = 0; + let _g = 0; + let _g1 = this.numPoints; + while(_g < _g1) { + let i = _g++; + if(this.points[i].depth > max) { + max = this.points[i].depth; + } + } + return max; + } + clear() { + this.numPoints = 0; + let _g = 0; + let _g1 = this.points; + while(_g < _g1.length) { + let p = _g1[_g]; + ++_g; + p.position1.zero(); + p.position2.zero(); + p.depth = 0; + p.id = 0; + } + this.normal.zero(); + } +} +oimo.collision.narrowphase.DetectorResultPoint = class oimo_collision_narrowphase_DetectorResultPoint { + constructor() { + this.position1 = new oimo.common.Vec3(); + this.position2 = new oimo.common.Vec3(); + this.depth = 0; + this.id = 0; + } +} +if(!oimo.collision.narrowphase.detector) oimo.collision.narrowphase.detector = {}; +oimo.collision.narrowphase.detector.Detector = class oimo_collision_narrowphase_detector_Detector { + constructor(swapped) { + this.swapped = swapped; + } + setNormal(result,nX,nY,nZ) { + let v = result.normal; + v.x = nX; + v.y = nY; + v.z = nZ; + if(this.swapped) { + let _this = result.normal; + _this.x = -_this.x; + _this.y = -_this.y; + _this.z = -_this.z; + } + } + addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,depth,id) { + let p = result.points[result.numPoints++]; + p.depth = depth; + p.id = id; + if(this.swapped) { + let v = p.position1; + v.x = pos2X; + v.y = pos2Y; + v.z = pos2Z; + let v1 = p.position2; + v1.x = pos1X; + v1.y = pos1Y; + v1.z = pos1Z; + } else { + let v = p.position1; + v.x = pos1X; + v.y = pos1Y; + v.z = pos1Z; + let v1 = p.position2; + v1.x = pos2X; + v1.y = pos2Y; + v1.z = pos2Z; + } + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + } + detect(result,geom1,geom2,transform1,transform2,cachedData) { + result.numPoints = 0; + let _g = 0; + let _g1 = result.points; + while(_g < _g1.length) { + let p = _g1[_g]; + ++_g; + p.position1.zero(); + p.position2.zero(); + p.depth = 0; + p.id = 0; + } + result.normal.zero(); + if(this.swapped) { + this.detectImpl(result,geom2,geom1,transform2,transform1,cachedData); + } else { + this.detectImpl(result,geom1,geom2,transform1,transform2,cachedData); + } + } +} +oimo.collision.narrowphase.detector.BoxBoxDetector = class oimo_collision_narrowphase_detector_BoxBoxDetector extends oimo.collision.narrowphase.detector.Detector { + constructor() { + super(false); + this.clipper = new oimo.collision.narrowphase.detector._BoxBoxDetector.FaceClipper(); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + let b1 = geom1; + let b2 = geom2; + result.incremental = false; + let c1X; + let c1Y; + let c1Z; + let c2X; + let c2Y; + let c2Z; + let c12X; + let c12Y; + let c12Z; + c1X = tf1._positionX; + c1Y = tf1._positionY; + c1Z = tf1._positionZ; + c2X = tf2._positionX; + c2Y = tf2._positionY; + c2Z = tf2._positionZ; + c12X = c2X - c1X; + c12Y = c2Y - c1Y; + c12Z = c2Z - c1Z; + let x1X; + let x1Y; + let x1Z; + let y1X; + let y1Y; + let y1Z; + let z1X; + let z1Y; + let z1Z; + let x2X; + let x2Y; + let x2Z; + let y2X; + let y2Y; + let y2Z; + let z2X; + let z2Y; + let z2Z; + x1X = tf1._rotation00; + x1Y = tf1._rotation10; + x1Z = tf1._rotation20; + y1X = tf1._rotation01; + y1Y = tf1._rotation11; + y1Z = tf1._rotation21; + z1X = tf1._rotation02; + z1Y = tf1._rotation12; + z1Z = tf1._rotation22; + x2X = tf2._rotation00; + x2Y = tf2._rotation10; + x2Z = tf2._rotation20; + y2X = tf2._rotation01; + y2Y = tf2._rotation11; + y2Z = tf2._rotation21; + z2X = tf2._rotation02; + z2Y = tf2._rotation12; + z2Z = tf2._rotation22; + let w1 = b1._halfExtentsX; + let h1 = b1._halfExtentsY; + let d1 = b1._halfExtentsZ; + let w2 = b2._halfExtentsX; + let h2 = b2._halfExtentsY; + let d2 = b2._halfExtentsZ; + let sx1X; + let sx1Y; + let sx1Z; + let sy1X; + let sy1Y; + let sy1Z; + let sz1X; + let sz1Y; + let sz1Z; + let sx2X; + let sx2Y; + let sx2Z; + let sy2X; + let sy2Y; + let sy2Z; + let sz2X; + let sz2Y; + let sz2Z; + sx1X = x1X * w1; + sx1Y = x1Y * w1; + sx1Z = x1Z * w1; + sy1X = y1X * h1; + sy1Y = y1Y * h1; + sy1Z = y1Z * h1; + sz1X = z1X * d1; + sz1Y = z1Y * d1; + sz1Z = z1Z * d1; + sx2X = x2X * w2; + sx2Y = x2Y * w2; + sx2Z = x2Z * w2; + sy2X = y2X * h2; + sy2Y = y2Y * h2; + sy2Z = y2Z * h2; + sz2X = z2X * d2; + sz2Y = z2Y * d2; + sz2Z = z2Z * d2; + let mDepth = 1e65536; + let mId = -1; + let mSign = 0; + let mAxisX; + let mAxisY; + let mAxisZ; + mAxisX = 0; + mAxisY = 0; + mAxisZ = 0; + let proj1 = w1; + let dx = x1X * sx2X + x1Y * sx2Y + x1Z * sx2Z; + let dy = x1X * sy2X + x1Y * sy2Y + x1Z * sy2Z; + let dz = x1X * sz2X + x1Y * sz2Y + x1Z * sz2Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + if(dz < 0) { + dz = -dz; + } + let proj2 = dx + dy + dz; + let projC12 = x1X * c12X + x1Y * c12Y + x1Z * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < 1e65536) { + mDepth = depth; + mId = 0; + mAxisX = x1X; + mAxisY = x1Y; + mAxisZ = x1Z; + mSign = neg ? -1 : 1; + } + } else { + return; + } + proj1 = h1; + let dx1 = y1X * sx2X + y1Y * sx2Y + y1Z * sx2Z; + let dy1 = y1X * sy2X + y1Y * sy2Y + y1Z * sy2Z; + let dz1 = y1X * sz2X + y1Y * sz2Y + y1Z * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + if(dz1 < 0) { + dz1 = -dz1; + } + proj2 = dx1 + dy1 + dz1; + projC12 = y1X * c12X + y1Y * c12Y + y1Z * c12Z; + let sum1 = proj1 + proj2; + let neg1 = projC12 < 0; + let abs1 = neg1 ? -projC12 : projC12; + if(abs1 < sum1) { + let depth = sum1 - abs1; + if(depth < mDepth) { + mDepth = depth; + mId = 1; + mAxisX = y1X; + mAxisY = y1Y; + mAxisZ = y1Z; + mSign = neg1 ? -1 : 1; + } + } else { + return; + } + proj1 = d1; + let dx2 = z1X * sx2X + z1Y * sx2Y + z1Z * sx2Z; + let dy2 = z1X * sy2X + z1Y * sy2Y + z1Z * sy2Z; + let dz2 = z1X * sz2X + z1Y * sz2Y + z1Z * sz2Z; + if(dx2 < 0) { + dx2 = -dx2; + } + if(dy2 < 0) { + dy2 = -dy2; + } + if(dz2 < 0) { + dz2 = -dz2; + } + proj2 = dx2 + dy2 + dz2; + projC12 = z1X * c12X + z1Y * c12Y + z1Z * c12Z; + let sum2 = proj1 + proj2; + let neg2 = projC12 < 0; + let abs2 = neg2 ? -projC12 : projC12; + if(abs2 < sum2) { + let depth = sum2 - abs2; + if(depth < mDepth) { + mDepth = depth; + mId = 2; + mAxisX = z1X; + mAxisY = z1Y; + mAxisZ = z1Z; + mSign = neg2 ? -1 : 1; + } + } else { + return; + } + if(mDepth > oimo.common.Setting.linearSlop) { + mDepth -= oimo.common.Setting.linearSlop; + } else { + mDepth = 0; + } + let dx3 = x2X * sx1X + x2Y * sx1Y + x2Z * sx1Z; + let dy3 = x2X * sy1X + x2Y * sy1Y + x2Z * sy1Z; + let dz3 = x2X * sz1X + x2Y * sz1Y + x2Z * sz1Z; + if(dx3 < 0) { + dx3 = -dx3; + } + if(dy3 < 0) { + dy3 = -dy3; + } + if(dz3 < 0) { + dz3 = -dz3; + } + proj1 = dx3 + dy3 + dz3; + proj2 = w2; + projC12 = x2X * c12X + x2Y * c12Y + x2Z * c12Z; + let sum3 = proj1 + proj2; + let neg3 = projC12 < 0; + let abs3 = neg3 ? -projC12 : projC12; + if(abs3 < sum3) { + let depth = sum3 - abs3; + if(depth < mDepth) { + mDepth = depth; + mId = 3; + mAxisX = x2X; + mAxisY = x2Y; + mAxisZ = x2Z; + mSign = neg3 ? -1 : 1; + } + } else { + return; + } + let dx4 = y2X * sx1X + y2Y * sx1Y + y2Z * sx1Z; + let dy4 = y2X * sy1X + y2Y * sy1Y + y2Z * sy1Z; + let dz4 = y2X * sz1X + y2Y * sz1Y + y2Z * sz1Z; + if(dx4 < 0) { + dx4 = -dx4; + } + if(dy4 < 0) { + dy4 = -dy4; + } + if(dz4 < 0) { + dz4 = -dz4; + } + proj1 = dx4 + dy4 + dz4; + proj2 = h2; + projC12 = y2X * c12X + y2Y * c12Y + y2Z * c12Z; + let sum4 = proj1 + proj2; + let neg4 = projC12 < 0; + let abs4 = neg4 ? -projC12 : projC12; + if(abs4 < sum4) { + let depth = sum4 - abs4; + if(depth < mDepth) { + mDepth = depth; + mId = 4; + mAxisX = y2X; + mAxisY = y2Y; + mAxisZ = y2Z; + mSign = neg4 ? -1 : 1; + } + } else { + return; + } + let dx5 = z2X * sx1X + z2Y * sx1Y + z2Z * sx1Z; + let dy5 = z2X * sy1X + z2Y * sy1Y + z2Z * sy1Z; + let dz5 = z2X * sz1X + z2Y * sz1Y + z2Z * sz1Z; + if(dx5 < 0) { + dx5 = -dx5; + } + if(dy5 < 0) { + dy5 = -dy5; + } + if(dz5 < 0) { + dz5 = -dz5; + } + proj1 = dx5 + dy5 + dz5; + proj2 = d2; + projC12 = z2X * c12X + z2Y * c12Y + z2Z * c12Z; + let sum5 = proj1 + proj2; + let neg5 = projC12 < 0; + let abs5 = neg5 ? -projC12 : projC12; + if(abs5 < sum5) { + let depth = sum5 - abs5; + if(depth < mDepth) { + mDepth = depth; + mId = 5; + mAxisX = z2X; + mAxisY = z2Y; + mAxisZ = z2Z; + mSign = neg5 ? -1 : 1; + } + } else { + return; + } + if(mDepth > oimo.common.Setting.linearSlop) { + mDepth -= oimo.common.Setting.linearSlop; + } else { + mDepth = 0; + } + let edgeAxisX; + let edgeAxisY; + let edgeAxisZ; + edgeAxisX = x1Y * x2Z - x1Z * x2Y; + edgeAxisY = x1Z * x2X - x1X * x2Z; + edgeAxisZ = x1X * x2Y - x1Y * x2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 6; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = x1Y * y2Z - x1Z * y2Y; + edgeAxisY = x1Z * y2X - x1X * y2Z; + edgeAxisZ = x1X * y2Y - x1Y * y2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 7; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = x1Y * z2Z - x1Z * z2Y; + edgeAxisY = x1Z * z2X - x1X * z2Z; + edgeAxisZ = x1X * z2Y - x1Y * z2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 8; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = y1Y * x2Z - y1Z * x2Y; + edgeAxisY = y1Z * x2X - y1X * x2Z; + edgeAxisZ = y1X * x2Y - y1Y * x2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 9; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = y1Y * y2Z - y1Z * y2Y; + edgeAxisY = y1Z * y2X - y1X * y2Z; + edgeAxisZ = y1X * y2Y - y1Y * y2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 10; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = y1Y * z2Z - y1Z * z2Y; + edgeAxisY = y1Z * z2X - y1X * z2Z; + edgeAxisZ = y1X * z2Y - y1Y * z2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sz1X + edgeAxisY * sz1Y + edgeAxisZ * sz1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 11; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = z1Y * x2Z - z1Z * x2Y; + edgeAxisY = z1Z * x2X - z1X * x2Z; + edgeAxisZ = z1X * x2Y - z1Y * x2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 12; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = z1Y * y2Z - z1Z * y2Y; + edgeAxisY = z1Z * y2X - z1X * y2Z; + edgeAxisZ = z1X * y2Y - z1Y * y2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sz2X + edgeAxisY * sz2Y + edgeAxisZ * sz2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 13; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + edgeAxisX = z1Y * z2Z - z1Z * z2Y; + edgeAxisY = z1Z * z2X - z1X * z2Z; + edgeAxisZ = z1X * z2Y - z1Y * z2X; + if(!(edgeAxisX == 0 && edgeAxisY == 0 && edgeAxisZ == 0)) { + let l = edgeAxisX * edgeAxisX + edgeAxisY * edgeAxisY + edgeAxisZ * edgeAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + edgeAxisX *= l; + edgeAxisY *= l; + edgeAxisZ *= l; + let dx = edgeAxisX * sx1X + edgeAxisY * sx1Y + edgeAxisZ * sx1Z; + let dy = edgeAxisX * sy1X + edgeAxisY * sy1Y + edgeAxisZ * sy1Z; + if(dx < 0) { + dx = -dx; + } + if(dy < 0) { + dy = -dy; + } + proj1 = dx + dy; + let dx1 = edgeAxisX * sx2X + edgeAxisY * sx2Y + edgeAxisZ * sx2Z; + let dy1 = edgeAxisX * sy2X + edgeAxisY * sy2Y + edgeAxisZ * sy2Z; + if(dx1 < 0) { + dx1 = -dx1; + } + if(dy1 < 0) { + dy1 = -dy1; + } + proj2 = dx1 + dy1; + projC12 = edgeAxisX * c12X + edgeAxisY * c12Y + edgeAxisZ * c12Z; + let sum = proj1 + proj2; + let neg = projC12 < 0; + let abs = neg ? -projC12 : projC12; + if(abs < sum) { + let depth = sum - abs; + if(depth < mDepth) { + mDepth = depth; + mId = 14; + mAxisX = edgeAxisX; + mAxisY = edgeAxisY; + mAxisZ = edgeAxisZ; + mSign = neg ? -1 : 1; + } + } else { + return; + } + } + if(mId >= 6) { + mAxisX *= mSign; + mAxisY *= mSign; + mAxisZ *= mSign; + let id1 = (mId - 6) / 3 | 0; + let id2 = mId - 6 - id1 * 3; + let p1X; + let p1Y; + let p1Z; + let p2X; + let p2Y; + let p2Z; + let d1X; + let d1Y; + let d1Z; + let d2X; + let d2Y; + let d2Z; + switch(id1) { + case 0: + d1X = x1X; + d1Y = x1Y; + d1Z = x1Z; + let signY = sz1X * mAxisX + sz1Y * mAxisY + sz1Z * mAxisZ > 0; + if(sy1X * mAxisX + sy1Y * mAxisY + sy1Z * mAxisZ > 0) { + if(signY) { + p1X = sy1X + sz1X; + p1Y = sy1Y + sz1Y; + p1Z = sy1Z + sz1Z; + } else { + p1X = sy1X - sz1X; + p1Y = sy1Y - sz1Y; + p1Z = sy1Z - sz1Z; + } + } else if(signY) { + p1X = sz1X - sy1X; + p1Y = sz1Y - sy1Y; + p1Z = sz1Z - sy1Z; + } else { + p1X = sy1X + sz1X; + p1Y = sy1Y + sz1Y; + p1Z = sy1Z + sz1Z; + p1X = -p1X; + p1Y = -p1Y; + p1Z = -p1Z; + } + break; + case 1: + d1X = y1X; + d1Y = y1Y; + d1Z = y1Z; + let signY1 = sz1X * mAxisX + sz1Y * mAxisY + sz1Z * mAxisZ > 0; + if(sx1X * mAxisX + sx1Y * mAxisY + sx1Z * mAxisZ > 0) { + if(signY1) { + p1X = sx1X + sz1X; + p1Y = sx1Y + sz1Y; + p1Z = sx1Z + sz1Z; + } else { + p1X = sx1X - sz1X; + p1Y = sx1Y - sz1Y; + p1Z = sx1Z - sz1Z; + } + } else if(signY1) { + p1X = sz1X - sx1X; + p1Y = sz1Y - sx1Y; + p1Z = sz1Z - sx1Z; + } else { + p1X = sx1X + sz1X; + p1Y = sx1Y + sz1Y; + p1Z = sx1Z + sz1Z; + p1X = -p1X; + p1Y = -p1Y; + p1Z = -p1Z; + } + break; + default: + d1X = z1X; + d1Y = z1Y; + d1Z = z1Z; + let signY2 = sy1X * mAxisX + sy1Y * mAxisY + sy1Z * mAxisZ > 0; + if(sx1X * mAxisX + sx1Y * mAxisY + sx1Z * mAxisZ > 0) { + if(signY2) { + p1X = sx1X + sy1X; + p1Y = sx1Y + sy1Y; + p1Z = sx1Z + sy1Z; + } else { + p1X = sx1X - sy1X; + p1Y = sx1Y - sy1Y; + p1Z = sx1Z - sy1Z; + } + } else if(signY2) { + p1X = sy1X - sx1X; + p1Y = sy1Y - sx1Y; + p1Z = sy1Z - sx1Z; + } else { + p1X = sx1X + sy1X; + p1Y = sx1Y + sy1Y; + p1Z = sx1Z + sy1Z; + p1X = -p1X; + p1Y = -p1Y; + p1Z = -p1Z; + } + } + p1X = c1X + p1X; + p1Y = c1Y + p1Y; + p1Z = c1Z + p1Z; + switch(id2) { + case 0: + d2X = x2X; + d2Y = x2Y; + d2Z = x2Z; + let signY3 = sz2X * mAxisX + sz2Y * mAxisY + sz2Z * mAxisZ > 0; + if(sy2X * mAxisX + sy2Y * mAxisY + sy2Z * mAxisZ > 0) { + if(signY3) { + p2X = sy2X + sz2X; + p2Y = sy2Y + sz2Y; + p2Z = sy2Z + sz2Z; + } else { + p2X = sy2X - sz2X; + p2Y = sy2Y - sz2Y; + p2Z = sy2Z - sz2Z; + } + } else if(signY3) { + p2X = sz2X - sy2X; + p2Y = sz2Y - sy2Y; + p2Z = sz2Z - sy2Z; + } else { + p2X = sy2X + sz2X; + p2Y = sy2Y + sz2Y; + p2Z = sy2Z + sz2Z; + p2X = -p2X; + p2Y = -p2Y; + p2Z = -p2Z; + } + break; + case 1: + d2X = y2X; + d2Y = y2Y; + d2Z = y2Z; + let signY4 = sz2X * mAxisX + sz2Y * mAxisY + sz2Z * mAxisZ > 0; + if(sx2X * mAxisX + sx2Y * mAxisY + sx2Z * mAxisZ > 0) { + if(signY4) { + p2X = sx2X + sz2X; + p2Y = sx2Y + sz2Y; + p2Z = sx2Z + sz2Z; + } else { + p2X = sx2X - sz2X; + p2Y = sx2Y - sz2Y; + p2Z = sx2Z - sz2Z; + } + } else if(signY4) { + p2X = sz2X - sx2X; + p2Y = sz2Y - sx2Y; + p2Z = sz2Z - sx2Z; + } else { + p2X = sx2X + sz2X; + p2Y = sx2Y + sz2Y; + p2Z = sx2Z + sz2Z; + p2X = -p2X; + p2Y = -p2Y; + p2Z = -p2Z; + } + break; + default: + d2X = z2X; + d2Y = z2Y; + d2Z = z2Z; + let signY5 = sy2X * mAxisX + sy2Y * mAxisY + sy2Z * mAxisZ > 0; + if(sx2X * mAxisX + sx2Y * mAxisY + sx2Z * mAxisZ > 0) { + if(signY5) { + p2X = sx2X + sy2X; + p2Y = sx2Y + sy2Y; + p2Z = sx2Z + sy2Z; + } else { + p2X = sx2X - sy2X; + p2Y = sx2Y - sy2Y; + p2Z = sx2Z - sy2Z; + } + } else if(signY5) { + p2X = sy2X - sx2X; + p2Y = sy2Y - sx2Y; + p2Z = sy2Z - sx2Z; + } else { + p2X = sx2X + sy2X; + p2Y = sx2Y + sy2Y; + p2Z = sx2Z + sy2Z; + p2X = -p2X; + p2Y = -p2Y; + p2Z = -p2Z; + } + } + p2X = c2X - p2X; + p2Y = c2Y - p2Y; + p2Z = c2Z - p2Z; + let rX; + let rY; + let rZ; + rX = p1X - p2X; + rY = p1Y - p2Y; + rZ = p1Z - p2Z; + let dot12 = d1X * d2X + d1Y * d2Y + d1Z * d2Z; + let dot1r = d1X * rX + d1Y * rY + d1Z * rZ; + let dot2r = d2X * rX + d2Y * rY + d2Z * rZ; + let invDet = 1 / (1 - dot12 * dot12); + let t1 = (dot12 * dot2r - dot1r) * invDet; + let t2 = (dot2r - dot12 * dot1r) * invDet; + let cp1X; + let cp1Y; + let cp1Z; + let cp2X; + let cp2Y; + let cp2Z; + cp1X = p1X + d1X * t1; + cp1Y = p1Y + d1Y * t1; + cp1Z = p1Z + d1Z * t1; + cp2X = p2X + d2X * t2; + cp2Y = p2Y + d2Y * t2; + cp2Z = p2Z + d2Z * t2; + let normalX; + let normalY; + let normalZ; + normalX = -mAxisX; + normalY = -mAxisY; + normalZ = -mAxisZ; + this.setNormal(result,normalX,normalY,normalZ); + this.addPoint(result,cp1X,cp1Y,cp1Z,cp2X,cp2Y,cp2Z,mDepth,4); + return; + } + let tmpX; + let tmpY; + let tmpZ; + let swapped; + if(mId >= 3) { + mSign = -mSign; + c12X = -c12X; + c12Y = -c12Y; + c12Z = -c12Z; + + + + + w1 = w2; + + + h1 = h2; + + + d1 = d2; + + + + + c1X = c2X; + c1Y = c2Y; + c1Z = c2Z; + + + + tmpX = x1X; + tmpY = x1Y; + tmpZ = x1Z; + x1X = x2X; + x1Y = x2Y; + x1Z = x2Z; + x2X = tmpX; + x2Y = tmpY; + x2Z = tmpZ; + tmpX = y1X; + tmpY = y1Y; + tmpZ = y1Z; + y1X = y2X; + y1Y = y2Y; + y1Z = y2Z; + y2X = tmpX; + y2Y = tmpY; + y2Z = tmpZ; + tmpX = z1X; + tmpY = z1Y; + tmpZ = z1Z; + z1X = z2X; + z1Y = z2Y; + z1Z = z2Z; + z2X = tmpX; + z2Y = tmpY; + z2Z = tmpZ; + tmpX = sx1X; + tmpY = sx1Y; + tmpZ = sx1Z; + sx1X = sx2X; + sx1Y = sx2Y; + sx1Z = sx2Z; + sx2X = tmpX; + sx2Y = tmpY; + sx2Z = tmpZ; + tmpX = sy1X; + tmpY = sy1Y; + tmpZ = sy1Z; + sy1X = sy2X; + sy1Y = sy2Y; + sy1Z = sy2Z; + sy2X = tmpX; + sy2Y = tmpY; + sy2Z = tmpZ; + tmpX = sz1X; + tmpY = sz1Y; + tmpZ = sz1Z; + sz1X = sz2X; + sz1Y = sz2Y; + sz1Z = sz2Z; + sz2X = tmpX; + sz2Y = tmpY; + sz2Z = tmpZ; + mId -= 3; + swapped = true; + } else { + swapped = false; + } + let refCenterX; + let refCenterY; + let refCenterZ; + let refNormalX; + let refNormalY; + let refNormalZ; + let refXX; + let refXY; + let refXZ; + let refYX; + let refYY; + let refYZ; + let refW; + let refH; + switch(mId) { + case 0: + refCenterX = sx1X; + refCenterY = sx1Y; + refCenterZ = sx1Z; + refNormalX = x1X; + refNormalY = x1Y; + refNormalZ = x1Z; + refXX = y1X; + refXY = y1Y; + refXZ = y1Z; + refYX = z1X; + refYY = z1Y; + refYZ = z1Z; + refW = h1; + refH = d1; + break; + case 1: + refCenterX = sy1X; + refCenterY = sy1Y; + refCenterZ = sy1Z; + refNormalX = y1X; + refNormalY = y1Y; + refNormalZ = y1Z; + refXX = z1X; + refXY = z1Y; + refXZ = z1Z; + refYX = x1X; + refYY = x1Y; + refYZ = x1Z; + refW = d1; + refH = w1; + break; + default: + refCenterX = sz1X; + refCenterY = sz1Y; + refCenterZ = sz1Z; + refNormalX = z1X; + refNormalY = z1Y; + refNormalZ = z1Z; + refXX = x1X; + refXY = x1Y; + refXZ = x1Z; + refYX = y1X; + refYY = y1Y; + refYZ = y1Z; + refW = w1; + refH = h1; + } + if(mSign < 0) { + refCenterX = -refCenterX; + refCenterY = -refCenterY; + refCenterZ = -refCenterZ; + refNormalX = -refNormalX; + refNormalY = -refNormalY; + refNormalZ = -refNormalZ; + tmpX = refXX; + tmpY = refXY; + tmpZ = refXZ; + refXX = refYX; + refXY = refYY; + refXZ = refYZ; + refYX = tmpX; + refYY = tmpY; + refYZ = tmpZ; + let tmp = refW; + refW = refH; + refH = tmp; + } + refCenterX += c1X; + refCenterY += c1Y; + refCenterZ += c1Z; + let minIncDot = 1; + let incId = 0; + let incDot = refNormalX * x2X + refNormalY * x2Y + refNormalZ * x2Z; + if(incDot < minIncDot) { + minIncDot = incDot; + incId = 0; + } + if(-incDot < minIncDot) { + minIncDot = -incDot; + incId = 1; + } + incDot = refNormalX * y2X + refNormalY * y2Y + refNormalZ * y2Z; + if(incDot < minIncDot) { + minIncDot = incDot; + incId = 2; + } + if(-incDot < minIncDot) { + minIncDot = -incDot; + incId = 3; + } + incDot = refNormalX * z2X + refNormalY * z2Y + refNormalZ * z2Z; + if(incDot < minIncDot) { + minIncDot = incDot; + incId = 4; + } + if(-incDot < minIncDot) { + + incId = 5; + } + let incV1X; + let incV1Y; + let incV1Z; + let incV2X; + let incV2Y; + let incV2Z; + let incV3X; + let incV3Y; + let incV3Z; + let incV4X; + let incV4Y; + let incV4Z; + switch(incId) { + case 0: + incV1X = sx2X + sy2X; + incV1Y = sx2Y + sy2Y; + incV1Z = sx2Z + sy2Z; + incV1X += sz2X; + incV1Y += sz2Y; + incV1Z += sz2Z; + incV2X = sx2X - sy2X; + incV2Y = sx2Y - sy2Y; + incV2Z = sx2Z - sy2Z; + incV2X += sz2X; + incV2Y += sz2Y; + incV2Z += sz2Z; + incV3X = sx2X - sy2X; + incV3Y = sx2Y - sy2Y; + incV3Z = sx2Z - sy2Z; + incV3X -= sz2X; + incV3Y -= sz2Y; + incV3Z -= sz2Z; + incV4X = sx2X + sy2X; + incV4Y = sx2Y + sy2Y; + incV4Z = sx2Z + sy2Z; + incV4X -= sz2X; + incV4Y -= sz2Y; + incV4Z -= sz2Z; + break; + case 1: + incV1X = sy2X - sx2X; + incV1Y = sy2Y - sx2Y; + incV1Z = sy2Z - sx2Z; + incV1X += sz2X; + incV1Y += sz2Y; + incV1Z += sz2Z; + incV2X = sy2X - sx2X; + incV2Y = sy2Y - sx2Y; + incV2Z = sy2Z - sx2Z; + incV2X -= sz2X; + incV2Y -= sz2Y; + incV2Z -= sz2Z; + incV3X = sx2X + sy2X; + incV3Y = sx2Y + sy2Y; + incV3Z = sx2Z + sy2Z; + incV3X = -incV3X; + incV3Y = -incV3Y; + incV3Z = -incV3Z; + incV3X -= sz2X; + incV3Y -= sz2Y; + incV3Z -= sz2Z; + incV4X = sx2X + sy2X; + incV4Y = sx2Y + sy2Y; + incV4Z = sx2Z + sy2Z; + incV4X = -incV4X; + incV4Y = -incV4Y; + incV4Z = -incV4Z; + incV4X += sz2X; + incV4Y += sz2Y; + incV4Z += sz2Z; + break; + case 2: + incV1X = sx2X + sy2X; + incV1Y = sx2Y + sy2Y; + incV1Z = sx2Z + sy2Z; + incV1X += sz2X; + incV1Y += sz2Y; + incV1Z += sz2Z; + incV2X = sx2X + sy2X; + incV2Y = sx2Y + sy2Y; + incV2Z = sx2Z + sy2Z; + incV2X -= sz2X; + incV2Y -= sz2Y; + incV2Z -= sz2Z; + incV3X = sy2X - sx2X; + incV3Y = sy2Y - sx2Y; + incV3Z = sy2Z - sx2Z; + incV3X -= sz2X; + incV3Y -= sz2Y; + incV3Z -= sz2Z; + incV4X = sy2X - sx2X; + incV4Y = sy2Y - sx2Y; + incV4Z = sy2Z - sx2Z; + incV4X += sz2X; + incV4Y += sz2Y; + incV4Z += sz2Z; + break; + case 3: + incV1X = sx2X - sy2X; + incV1Y = sx2Y - sy2Y; + incV1Z = sx2Z - sy2Z; + incV1X += sz2X; + incV1Y += sz2Y; + incV1Z += sz2Z; + incV2X = sx2X + sy2X; + incV2Y = sx2Y + sy2Y; + incV2Z = sx2Z + sy2Z; + incV2X = -incV2X; + incV2Y = -incV2Y; + incV2Z = -incV2Z; + incV2X += sz2X; + incV2Y += sz2Y; + incV2Z += sz2Z; + incV3X = sx2X + sy2X; + incV3Y = sx2Y + sy2Y; + incV3Z = sx2Z + sy2Z; + incV3X = -incV3X; + incV3Y = -incV3Y; + incV3Z = -incV3Z; + incV3X -= sz2X; + incV3Y -= sz2Y; + incV3Z -= sz2Z; + incV4X = sx2X - sy2X; + incV4Y = sx2Y - sy2Y; + incV4Z = sx2Z - sy2Z; + incV4X -= sz2X; + incV4Y -= sz2Y; + incV4Z -= sz2Z; + break; + case 4: + incV1X = sx2X + sy2X; + incV1Y = sx2Y + sy2Y; + incV1Z = sx2Z + sy2Z; + incV1X += sz2X; + incV1Y += sz2Y; + incV1Z += sz2Z; + incV2X = sy2X - sx2X; + incV2Y = sy2Y - sx2Y; + incV2Z = sy2Z - sx2Z; + incV2X += sz2X; + incV2Y += sz2Y; + incV2Z += sz2Z; + incV3X = sx2X + sy2X; + incV3Y = sx2Y + sy2Y; + incV3Z = sx2Z + sy2Z; + incV3X = -incV3X; + incV3Y = -incV3Y; + incV3Z = -incV3Z; + incV3X += sz2X; + incV3Y += sz2Y; + incV3Z += sz2Z; + incV4X = sx2X - sy2X; + incV4Y = sx2Y - sy2Y; + incV4Z = sx2Z - sy2Z; + incV4X += sz2X; + incV4Y += sz2Y; + incV4Z += sz2Z; + break; + default: + incV1X = sx2X + sy2X; + incV1Y = sx2Y + sy2Y; + incV1Z = sx2Z + sy2Z; + incV1X -= sz2X; + incV1Y -= sz2Y; + incV1Z -= sz2Z; + incV2X = sx2X - sy2X; + incV2Y = sx2Y - sy2Y; + incV2Z = sx2Z - sy2Z; + incV2X -= sz2X; + incV2Y -= sz2Y; + incV2Z -= sz2Z; + incV3X = sx2X + sy2X; + incV3Y = sx2Y + sy2Y; + incV3Z = sx2Z + sy2Z; + incV3X = -incV3X; + incV3Y = -incV3Y; + incV3Z = -incV3Z; + incV3X -= sz2X; + incV3Y -= sz2Y; + incV3Z -= sz2Z; + incV4X = sy2X - sx2X; + incV4Y = sy2Y - sx2Y; + incV4Z = sy2Z - sx2Z; + incV4X -= sz2X; + incV4Y -= sz2Y; + incV4Z -= sz2Z; + } + incV1X += c12X; + incV1Y += c12Y; + incV1Z += c12Z; + incV2X += c12X; + incV2Y += c12Y; + incV2Z += c12Z; + incV3X += c12X; + incV3Y += c12Y; + incV3Z += c12Z; + incV4X += c12X; + incV4Y += c12Y; + incV4Z += c12Z; + let _this = this.clipper; + _this.w = refW; + _this.h = refH; + _this.numVertices = 0; + _this.numTmpVertices = 0; + let _this1 = this.clipper; + let _this2 = _this1.vertices[_this1.numVertices++]; + _this2.x = incV1X * refXX + incV1Y * refXY + incV1Z * refXZ; + _this2.y = incV1X * refYX + incV1Y * refYY + incV1Z * refYZ; + _this2.wx = incV1X; + _this2.wy = incV1Y; + _this2.wz = incV1Z; + let _this3 = this.clipper; + let _this4 = _this3.vertices[_this3.numVertices++]; + _this4.x = incV2X * refXX + incV2Y * refXY + incV2Z * refXZ; + _this4.y = incV2X * refYX + incV2Y * refYY + incV2Z * refYZ; + _this4.wx = incV2X; + _this4.wy = incV2Y; + _this4.wz = incV2Z; + let _this5 = this.clipper; + let _this6 = _this5.vertices[_this5.numVertices++]; + _this6.x = incV3X * refXX + incV3Y * refXY + incV3Z * refXZ; + _this6.y = incV3X * refYX + incV3Y * refYY + incV3Z * refYZ; + _this6.wx = incV3X; + _this6.wy = incV3Y; + _this6.wz = incV3Z; + let _this7 = this.clipper; + let _this8 = _this7.vertices[_this7.numVertices++]; + _this8.x = incV4X * refXX + incV4Y * refXY + incV4Z * refXZ; + _this8.y = incV4X * refYX + incV4Y * refYY + incV4Z * refYZ; + _this8.wx = incV4X; + _this8.wy = incV4Y; + _this8.wz = incV4Z; + this.clipper.clip(); + this.clipper.reduce(); + let normalX; + let normalY; + let normalZ; + if(swapped) { + normalX = refNormalX; + normalY = refNormalY; + normalZ = refNormalZ; + } else { + normalX = -refNormalX; + normalY = -refNormalY; + normalZ = -refNormalZ; + } + this.setNormal(result,normalX,normalY,normalZ); + let _g = 0; + let _g1 = this.clipper.numVertices; + while(_g < _g1) { + let i = _g++; + let v = this.clipper.vertices[i]; + let clippedVertexX; + let clippedVertexY; + let clippedVertexZ; + clippedVertexX = v.wx; + clippedVertexY = v.wy; + clippedVertexZ = v.wz; + clippedVertexX += c1X; + clippedVertexY += c1Y; + clippedVertexZ += c1Z; + let clippedVertexToRefCenterX; + let clippedVertexToRefCenterY; + let clippedVertexToRefCenterZ; + clippedVertexToRefCenterX = refCenterX - clippedVertexX; + clippedVertexToRefCenterY = refCenterY - clippedVertexY; + clippedVertexToRefCenterZ = refCenterZ - clippedVertexZ; + let depth = clippedVertexToRefCenterX * refNormalX + clippedVertexToRefCenterY * refNormalY + clippedVertexToRefCenterZ * refNormalZ; + let clippedVertexOnRefFaceX; + let clippedVertexOnRefFaceY; + let clippedVertexOnRefFaceZ; + clippedVertexOnRefFaceX = clippedVertexX + refNormalX * depth; + clippedVertexOnRefFaceY = clippedVertexY + refNormalY * depth; + clippedVertexOnRefFaceZ = clippedVertexZ + refNormalZ * depth; + if(depth > -oimo.common.Setting.contactPersistenceThreshold) { + if(swapped) { + this.addPoint(result,clippedVertexX,clippedVertexY,clippedVertexZ,clippedVertexOnRefFaceX,clippedVertexOnRefFaceY,clippedVertexOnRefFaceZ,depth,i); + } else { + this.addPoint(result,clippedVertexOnRefFaceX,clippedVertexOnRefFaceY,clippedVertexOnRefFaceZ,clippedVertexX,clippedVertexY,clippedVertexZ,depth,i); + } + } + } + } +} +if(!oimo.collision.narrowphase.detector._BoxBoxDetector) oimo.collision.narrowphase.detector._BoxBoxDetector = {}; +oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex = class oimo_collision_narrowphase_detector__$BoxBoxDetector_IncidentVertex { + constructor() { + this.x = 0; + this.y = 0; + this.wx = 0; + this.wy = 0; + this.wz = 0; + } +} +oimo.collision.narrowphase.detector._BoxBoxDetector.FaceClipper = class oimo_collision_narrowphase_detector__$BoxBoxDetector_FaceClipper { + constructor() { + this.w = 0; + this.h = 0; + this.numVertices = 0; + this.numTmpVertices = 0; + this.vertices = new Array(8); + this.tmpVertices = new Array(8); + this.vertices[0] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[0] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[1] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[1] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[2] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[2] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[3] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[3] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[4] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[4] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[5] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[5] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[6] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[6] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.vertices[7] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + this.tmpVertices[7] = new oimo.collision.narrowphase.detector._BoxBoxDetector.IncidentVertex(); + } + clip() { + let _g = 0; + let _g1 = this.numVertices; + while(_g < _g1) { + let i = _g++; + let v1 = this.vertices[i]; + let v2 = this.vertices[(i + 1) % this.numVertices]; + let s1 = this.w + v1.x; + let s2 = this.w + v2.x; + if(s1 > 0 && s2 > 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + } else if(s1 > 0 && s2 <= 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + let t = s1 / (s1 - s2); + let _this1 = this.tmpVertices[this.numTmpVertices++]; + _this1.x = v1.x + (v2.x - v1.x) * t; + _this1.y = v1.y + (v2.y - v1.y) * t; + _this1.wx = v1.wx + (v2.wx - v1.wx) * t; + _this1.wy = v1.wy + (v2.wy - v1.wy) * t; + _this1.wz = v1.wz + (v2.wz - v1.wz) * t; + } else if(s1 <= 0 && s2 > 0) { + let t = s1 / (s1 - s2); + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x + (v2.x - v1.x) * t; + _this.y = v1.y + (v2.y - v1.y) * t; + _this.wx = v1.wx + (v2.wx - v1.wx) * t; + _this.wy = v1.wy + (v2.wy - v1.wy) * t; + _this.wz = v1.wz + (v2.wz - v1.wz) * t; + } + } + let tmp = this.vertices; + this.vertices = this.tmpVertices; + this.tmpVertices = tmp; + this.numVertices = this.numTmpVertices; + this.numTmpVertices = 0; + let _g2 = 0; + let _g3 = this.numVertices; + while(_g2 < _g3) { + let i = _g2++; + let v1 = this.vertices[i]; + let v2 = this.vertices[(i + 1) % this.numVertices]; + let s1 = this.w - v1.x; + let s2 = this.w - v2.x; + if(s1 > 0 && s2 > 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + } else if(s1 > 0 && s2 <= 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + let t = s1 / (s1 - s2); + let _this1 = this.tmpVertices[this.numTmpVertices++]; + _this1.x = v1.x + (v2.x - v1.x) * t; + _this1.y = v1.y + (v2.y - v1.y) * t; + _this1.wx = v1.wx + (v2.wx - v1.wx) * t; + _this1.wy = v1.wy + (v2.wy - v1.wy) * t; + _this1.wz = v1.wz + (v2.wz - v1.wz) * t; + } else if(s1 <= 0 && s2 > 0) { + let t = s1 / (s1 - s2); + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x + (v2.x - v1.x) * t; + _this.y = v1.y + (v2.y - v1.y) * t; + _this.wx = v1.wx + (v2.wx - v1.wx) * t; + _this.wy = v1.wy + (v2.wy - v1.wy) * t; + _this.wz = v1.wz + (v2.wz - v1.wz) * t; + } + } + let tmp1 = this.vertices; + this.vertices = this.tmpVertices; + this.tmpVertices = tmp1; + this.numVertices = this.numTmpVertices; + this.numTmpVertices = 0; + let _g4 = 0; + let _g5 = this.numVertices; + while(_g4 < _g5) { + let i = _g4++; + let v1 = this.vertices[i]; + let v2 = this.vertices[(i + 1) % this.numVertices]; + let s1 = this.h + v1.y; + let s2 = this.h + v2.y; + if(s1 > 0 && s2 > 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + } else if(s1 > 0 && s2 <= 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + let t = s1 / (s1 - s2); + let _this1 = this.tmpVertices[this.numTmpVertices++]; + _this1.x = v1.x + (v2.x - v1.x) * t; + _this1.y = v1.y + (v2.y - v1.y) * t; + _this1.wx = v1.wx + (v2.wx - v1.wx) * t; + _this1.wy = v1.wy + (v2.wy - v1.wy) * t; + _this1.wz = v1.wz + (v2.wz - v1.wz) * t; + } else if(s1 <= 0 && s2 > 0) { + let t = s1 / (s1 - s2); + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x + (v2.x - v1.x) * t; + _this.y = v1.y + (v2.y - v1.y) * t; + _this.wx = v1.wx + (v2.wx - v1.wx) * t; + _this.wy = v1.wy + (v2.wy - v1.wy) * t; + _this.wz = v1.wz + (v2.wz - v1.wz) * t; + } + } + let tmp2 = this.vertices; + this.vertices = this.tmpVertices; + this.tmpVertices = tmp2; + this.numVertices = this.numTmpVertices; + this.numTmpVertices = 0; + let _g6 = 0; + let _g7 = this.numVertices; + while(_g6 < _g7) { + let i = _g6++; + let v1 = this.vertices[i]; + let v2 = this.vertices[(i + 1) % this.numVertices]; + let s1 = this.h - v1.y; + let s2 = this.h - v2.y; + if(s1 > 0 && s2 > 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + } else if(s1 > 0 && s2 <= 0) { + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x; + _this.y = v1.y; + _this.wx = v1.wx; + _this.wy = v1.wy; + _this.wz = v1.wz; + let t = s1 / (s1 - s2); + let _this1 = this.tmpVertices[this.numTmpVertices++]; + _this1.x = v1.x + (v2.x - v1.x) * t; + _this1.y = v1.y + (v2.y - v1.y) * t; + _this1.wx = v1.wx + (v2.wx - v1.wx) * t; + _this1.wy = v1.wy + (v2.wy - v1.wy) * t; + _this1.wz = v1.wz + (v2.wz - v1.wz) * t; + } else if(s1 <= 0 && s2 > 0) { + let t = s1 / (s1 - s2); + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = v1.x + (v2.x - v1.x) * t; + _this.y = v1.y + (v2.y - v1.y) * t; + _this.wx = v1.wx + (v2.wx - v1.wx) * t; + _this.wy = v1.wy + (v2.wy - v1.wy) * t; + _this.wz = v1.wz + (v2.wz - v1.wz) * t; + } + } + let tmp3 = this.vertices; + this.vertices = this.tmpVertices; + this.tmpVertices = tmp3; + this.numVertices = this.numTmpVertices; + this.numTmpVertices = 0; + } + reduce() { + if(this.numVertices < 4) { + return; + } + let max1 = -1e65536; + let min1 = 1e65536; + let max2 = -1e65536; + let min2 = 1e65536; + let max1V = null; + let min1V = null; + let max2V = null; + let min2V = null; + let e1x = 1; + let e1y = 1; + let e2x = -1; + let e2y = 1; + let _g = 0; + let _g1 = this.numVertices; + while(_g < _g1) { + let v = this.vertices[_g++]; + let dot1 = v.x * e1x + v.y * e1y; + let dot2 = v.x * e2x + v.y * e2y; + if(dot1 > max1) { + max1 = dot1; + max1V = v; + } + if(dot1 < min1) { + min1 = dot1; + min1V = v; + } + if(dot2 > max2) { + max2 = dot2; + max2V = v; + } + if(dot2 < min2) { + min2 = dot2; + min2V = v; + } + } + let _this = this.tmpVertices[this.numTmpVertices++]; + _this.x = max1V.x; + _this.y = max1V.y; + _this.wx = max1V.wx; + _this.wy = max1V.wy; + _this.wz = max1V.wz; + let _this1 = this.tmpVertices[this.numTmpVertices++]; + _this1.x = max2V.x; + _this1.y = max2V.y; + _this1.wx = max2V.wx; + _this1.wy = max2V.wy; + _this1.wz = max2V.wz; + let _this2 = this.tmpVertices[this.numTmpVertices++]; + _this2.x = min1V.x; + _this2.y = min1V.y; + _this2.wx = min1V.wx; + _this2.wy = min1V.wy; + _this2.wz = min1V.wz; + let _this3 = this.tmpVertices[this.numTmpVertices++]; + _this3.x = min2V.x; + _this3.y = min2V.y; + _this3.wx = min2V.wx; + _this3.wy = min2V.wy; + _this3.wz = min2V.wz; + let tmp = this.vertices; + this.vertices = this.tmpVertices; + this.tmpVertices = tmp; + this.numVertices = this.numTmpVertices; + this.numTmpVertices = 0; + } +} +oimo.collision.narrowphase.detector.BoxBoxDetectorMacro = class oimo_collision_narrowphase_detector_BoxBoxDetectorMacro { +} +oimo.collision.narrowphase.detector.CachedDetectorData = class oimo_collision_narrowphase_detector_CachedDetectorData { + constructor() { + } + _clear() { + if(this._gjkCache != null) { + this._gjkCache.clear(); + } + } +} +oimo.collision.narrowphase.detector.CapsuleCapsuleDetector = class oimo_collision_narrowphase_detector_CapsuleCapsuleDetector extends oimo.collision.narrowphase.detector.Detector { + constructor() { + super(false); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + let c1 = geom1; + let c2 = geom2; + result.incremental = false; + let axis1X; + let axis1Y; + let axis1Z; + let axis2X; + let axis2Y; + let axis2Z; + axis1X = tf1._rotation01; + axis1Y = tf1._rotation11; + axis1Z = tf1._rotation21; + axis2X = tf2._rotation01; + axis2Y = tf2._rotation11; + axis2Z = tf2._rotation21; + let hh1 = c1._halfHeight; + let hh2 = c2._halfHeight; + let r1 = c1._radius; + let r2 = c2._radius; + let p1X; + let p1Y; + let p1Z; + let q1X; + let q1Y; + let q1Z; + let p2X; + let p2Y; + let p2Z; + let q2X; + let q2Y; + let q2Z; + p1X = tf1._positionX + axis1X * -hh1; + p1Y = tf1._positionY + axis1Y * -hh1; + p1Z = tf1._positionZ + axis1Z * -hh1; + q1X = tf1._positionX + axis1X * hh1; + q1Y = tf1._positionY + axis1Y * hh1; + q1Z = tf1._positionZ + axis1Z * hh1; + p2X = tf2._positionX + axis2X * -hh2; + p2Y = tf2._positionY + axis2Y * -hh2; + p2Z = tf2._positionZ + axis2Z * -hh2; + q2X = tf2._positionX + axis2X * hh2; + q2Y = tf2._positionY + axis2Y * hh2; + q2Z = tf2._positionZ + axis2Z * hh2; + let p12X; + let p12Y; + let p12Z; + p12X = p1X - p2X; + p12Y = p1Y - p2Y; + p12Z = p1Z - p2Z; + let d1X; + let d1Y; + let d1Z; + let d2X; + let d2Y; + let d2Z; + d1X = q1X - p1X; + d1Y = q1Y - p1Y; + d1Z = q1Z - p1Z; + d2X = q2X - p2X; + d2Y = q2Y - p2Y; + d2Z = q2Z - p2Z; + let p21d1 = -(p12X * d1X + p12Y * d1Y + p12Z * d1Z); + let p12d2 = p12X * d2X + p12Y * d2Y + p12Z * d2Z; + let d11 = hh1 * hh1 * 4; + let d12 = d1X * d2X + d1Y * d2Y + d1Z * d2Z; + let d22 = hh2 * hh2 * 4; + let t1; + let t2; + if(d11 == 0 && d22 == 0) { + t1 = 0; + t2 = 0; + } else if(d11 == 0) { + t1 = 0; + + if(p12d2 < 0) { + t2 = 0; + } else if(p12d2 > d22) { + t2 = 1; + } else { + t2 = p12d2 / d22; + } + } else if(d22 == 0) { + t2 = 0; + + if(p21d1 < 0) { + t1 = 0; + } else if(p21d1 > d11) { + t1 = 1; + } else { + t1 = p21d1 / d11; + } + } else { + let det = d11 * d22 - d12 * d12; + if(det == 0) { + t1 = 0; + } else { + t1 = d12 * p12d2 + d22 * p21d1; + if(t1 < 0) { + t1 = 0; + } else if(t1 > det) { + t1 = 1; + } else { + t1 /= det; + } + } + t2 = t1 * d12 + p12d2; + if(t2 < 0) { + t2 = 0; + + if(p21d1 < 0) { + t1 = 0; + } else if(p21d1 > d11) { + t1 = 1; + } else { + t1 = p21d1 / d11; + } + } else if(t2 > d22) { + t2 = 1; + t1 = d12 + p21d1; + if(t1 < 0) { + t1 = 0; + } else if(t1 > d11) { + t1 = 1; + } else { + t1 /= d11; + } + } else { + t2 /= d22; + } + } + let cp1X; + let cp1Y; + let cp1Z; + let cp2X; + let cp2Y; + let cp2Z; + cp1X = p1X + d1X * t1; + cp1Y = p1Y + d1Y * t1; + cp1Z = p1Z + d1Z * t1; + cp2X = p2X + d2X * t2; + cp2Y = p2Y + d2Y * t2; + cp2Z = p2Z + d2Z * t2; + let dX; + let dY; + let dZ; + dX = cp1X - cp2X; + dY = cp1Y - cp2Y; + dZ = cp1Z - cp2Z; + let len2 = dX * dX + dY * dY + dZ * dZ; + if(len2 >= (r1 + r2) * (r1 + r2)) { + return; + } + let len = Math.sqrt(len2); + let nX; + let nY; + let nZ; + if(len > 0) { + nX = dX * (1 / len); + nY = dY * (1 / len); + nZ = dZ * (1 / len); + } else { + nX = 1; + nY = 0; + nZ = 0; + } + this.setNormal(result,nX,nY,nZ); + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + pos1X = cp1X + nX * -r1; + pos1Y = cp1Y + nY * -r1; + pos1Z = cp1Z + nZ * -r1; + pos2X = cp2X + nX * r2; + pos2Y = cp2Y + nY * r2; + pos2Z = cp2Z + nZ * r2; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,r1 + r2 - len,0); + } +} +oimo.collision.narrowphase.detector.GjkEpaDetector = class oimo_collision_narrowphase_detector_GjkEpaDetector extends oimo.collision.narrowphase.detector.Detector { + constructor() { + super(false); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + let gjkEpa = oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance; + let g1 = geom1; + let g2 = geom2; + let status = gjkEpa.computeClosestPointsImpl(g1,g2,tf1,tf2,oimo.common.Setting.enableGJKCaching ? cachedData : null,true); + result.incremental = true; + if(status != oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.SUCCEEDED) { + console.log("src/oimo/collision/narrowphase/detector/GjkEpaDetector.hx:28:","GJK/EPA failed: status=" + status); + return; + } + if(gjkEpa.distance > g1._gjkMargin + g2._gjkMargin) { + return; + } + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + let v = gjkEpa.closestPoint1; + pos1X = v.x; + pos1Y = v.y; + pos1Z = v.z; + let v1 = gjkEpa.closestPoint2; + pos2X = v1.x; + pos2Y = v1.y; + pos2Z = v1.z; + let normalX; + let normalY; + let normalZ; + normalX = pos1X - pos2X; + normalY = pos1Y - pos2Y; + normalZ = pos1Z - pos2Z; + if(normalX * normalX + normalY * normalY + normalZ * normalZ == 0) { + return; + } + if(gjkEpa.distance < 0) { + normalX = -normalX; + normalY = -normalY; + normalZ = -normalZ; + } + let l = normalX * normalX + normalY * normalY + normalZ * normalZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + normalX *= l; + normalY *= l; + normalZ *= l; + this.setNormal(result,normalX,normalY,normalZ); + pos1X += normalX * -g1._gjkMargin; + pos1Y += normalY * -g1._gjkMargin; + pos1Z += normalZ * -g1._gjkMargin; + pos2X += normalX * g2._gjkMargin; + pos2Y += normalY * g2._gjkMargin; + pos2Z += normalZ * g2._gjkMargin; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,g1._gjkMargin + g2._gjkMargin - gjkEpa.distance,0); + } +} +oimo.collision.narrowphase.detector.SphereBoxDetector = class oimo_collision_narrowphase_detector_SphereBoxDetector extends oimo.collision.narrowphase.detector.Detector { + constructor(swapped) { + super(swapped); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + let b = geom2; + result.incremental = false; + let halfExtX; + let halfExtY; + let halfExtZ; + let negHalfExtX; + let negHalfExtY; + let negHalfExtZ; + halfExtX = b._halfExtentsX; + halfExtY = b._halfExtentsY; + halfExtZ = b._halfExtentsZ; + negHalfExtX = -halfExtX; + negHalfExtY = -halfExtY; + negHalfExtZ = -halfExtZ; + let r = geom1._radius; + let boxToSphereX; + let boxToSphereY; + let boxToSphereZ; + boxToSphereX = tf1._positionX - tf2._positionX; + boxToSphereY = tf1._positionY - tf2._positionY; + boxToSphereZ = tf1._positionZ - tf2._positionZ; + let boxToSphereInBoxX; + let boxToSphereInBoxY; + let boxToSphereInBoxZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf2._rotation00 * boxToSphereX + tf2._rotation10 * boxToSphereY + tf2._rotation20 * boxToSphereZ; + __tmp__Y = tf2._rotation01 * boxToSphereX + tf2._rotation11 * boxToSphereY + tf2._rotation21 * boxToSphereZ; + __tmp__Z = tf2._rotation02 * boxToSphereX + tf2._rotation12 * boxToSphereY + tf2._rotation22 * boxToSphereZ; + boxToSphereInBoxX = __tmp__X; + boxToSphereInBoxY = __tmp__Y; + boxToSphereInBoxZ = __tmp__Z; + if(negHalfExtX < boxToSphereInBoxX && halfExtX > boxToSphereInBoxX && negHalfExtY < boxToSphereInBoxY && halfExtY > boxToSphereInBoxY && negHalfExtZ < boxToSphereInBoxZ && halfExtZ > boxToSphereInBoxZ) { + let sphereToBoxSurfaceX; + let sphereToBoxSurfaceY; + let sphereToBoxSurfaceZ; + sphereToBoxSurfaceX = boxToSphereInBoxX < 0 ? -boxToSphereInBoxX : boxToSphereInBoxX; + sphereToBoxSurfaceY = boxToSphereInBoxY < 0 ? -boxToSphereInBoxY : boxToSphereInBoxY; + sphereToBoxSurfaceZ = boxToSphereInBoxZ < 0 ? -boxToSphereInBoxZ : boxToSphereInBoxZ; + sphereToBoxSurfaceX = halfExtX - sphereToBoxSurfaceX; + sphereToBoxSurfaceY = halfExtY - sphereToBoxSurfaceY; + sphereToBoxSurfaceZ = halfExtZ - sphereToBoxSurfaceZ; + let normalInBoxX; + let normalInBoxY; + let normalInBoxZ; + let distX = sphereToBoxSurfaceX; + let distY = sphereToBoxSurfaceY; + let distZ = sphereToBoxSurfaceZ; + let depth; + let projectionMaskX; + let projectionMaskY; + let projectionMaskZ; + if(distX < distY) { + if(distX < distZ) { + if(boxToSphereInBoxX > 0) { + normalInBoxX = 1; + normalInBoxY = 0; + normalInBoxZ = 0; + } else { + normalInBoxX = -1; + normalInBoxY = 0; + normalInBoxZ = 0; + } + projectionMaskX = 0; + projectionMaskY = 1; + projectionMaskZ = 1; + depth = distX; + } else { + if(boxToSphereInBoxZ > 0) { + normalInBoxX = 0; + normalInBoxY = 0; + normalInBoxZ = 1; + } else { + normalInBoxX = 0; + normalInBoxY = 0; + normalInBoxZ = -1; + } + projectionMaskX = 1; + projectionMaskY = 1; + projectionMaskZ = 0; + depth = distZ; + } + } else if(distY < distZ) { + if(boxToSphereInBoxY > 0) { + normalInBoxX = 0; + normalInBoxY = 1; + normalInBoxZ = 0; + } else { + normalInBoxX = 0; + normalInBoxY = -1; + normalInBoxZ = 0; + } + projectionMaskX = 1; + projectionMaskY = 0; + projectionMaskZ = 1; + depth = distY; + } else { + if(boxToSphereInBoxZ > 0) { + normalInBoxX = 0; + normalInBoxY = 0; + normalInBoxZ = 1; + } else { + normalInBoxX = 0; + normalInBoxY = 0; + normalInBoxZ = -1; + } + projectionMaskX = 1; + projectionMaskY = 1; + projectionMaskZ = 0; + depth = distZ; + } + let baseX; + let baseY; + let baseZ; + baseX = projectionMaskX * boxToSphereInBoxX; + baseY = projectionMaskY * boxToSphereInBoxY; + baseZ = projectionMaskZ * boxToSphereInBoxZ; + let boxToClosestPointInBoxX; + let boxToClosestPointInBoxY; + let boxToClosestPointInBoxZ; + boxToClosestPointInBoxX = normalInBoxX * halfExtX; + boxToClosestPointInBoxY = normalInBoxY * halfExtY; + boxToClosestPointInBoxZ = normalInBoxZ * halfExtZ; + boxToClosestPointInBoxX += baseX; + boxToClosestPointInBoxY += baseY; + boxToClosestPointInBoxZ += baseZ; + let boxToClosestPointX; + let boxToClosestPointY; + let boxToClosestPointZ; + let normalX; + let normalY; + let normalZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf2._rotation00 * boxToClosestPointInBoxX + tf2._rotation01 * boxToClosestPointInBoxY + tf2._rotation02 * boxToClosestPointInBoxZ; + __tmp__Y = tf2._rotation10 * boxToClosestPointInBoxX + tf2._rotation11 * boxToClosestPointInBoxY + tf2._rotation12 * boxToClosestPointInBoxZ; + __tmp__Z = tf2._rotation20 * boxToClosestPointInBoxX + tf2._rotation21 * boxToClosestPointInBoxY + tf2._rotation22 * boxToClosestPointInBoxZ; + boxToClosestPointX = __tmp__X; + boxToClosestPointY = __tmp__Y; + boxToClosestPointZ = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * normalInBoxX + tf2._rotation01 * normalInBoxY + tf2._rotation02 * normalInBoxZ; + __tmp__Y1 = tf2._rotation10 * normalInBoxX + tf2._rotation11 * normalInBoxY + tf2._rotation12 * normalInBoxZ; + __tmp__Z1 = tf2._rotation20 * normalInBoxX + tf2._rotation21 * normalInBoxY + tf2._rotation22 * normalInBoxZ; + normalX = __tmp__X1; + normalY = __tmp__Y1; + normalZ = __tmp__Z1; + this.setNormal(result,normalX,normalY,normalZ); + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + pos1X = tf1._positionX + normalX * -r; + pos1Y = tf1._positionY + normalY * -r; + pos1Z = tf1._positionZ + normalZ * -r; + pos2X = tf2._positionX + boxToClosestPointX; + pos2Y = tf2._positionY + boxToClosestPointY; + pos2Z = tf2._positionZ + boxToClosestPointZ; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,depth,0); + return; + } + let boxToClosestPointInBoxX; + let boxToClosestPointInBoxY; + let boxToClosestPointInBoxZ; + halfExtX -= 1e-9; + halfExtY -= 1e-9; + halfExtZ -= 1e-9; + negHalfExtX += 1e-9; + negHalfExtY += 1e-9; + negHalfExtZ += 1e-9; + boxToClosestPointInBoxX = boxToSphereInBoxX < halfExtX ? boxToSphereInBoxX : halfExtX; + boxToClosestPointInBoxY = boxToSphereInBoxY < halfExtY ? boxToSphereInBoxY : halfExtY; + boxToClosestPointInBoxZ = boxToSphereInBoxZ < halfExtZ ? boxToSphereInBoxZ : halfExtZ; + if(!(boxToClosestPointInBoxX > negHalfExtX)) { + boxToClosestPointInBoxX = negHalfExtX; + } + if(!(boxToClosestPointInBoxY > negHalfExtY)) { + boxToClosestPointInBoxY = negHalfExtY; + } + if(!(boxToClosestPointInBoxZ > negHalfExtZ)) { + boxToClosestPointInBoxZ = negHalfExtZ; + } + let closestPointToSphereInBoxX; + let closestPointToSphereInBoxY; + let closestPointToSphereInBoxZ; + closestPointToSphereInBoxX = boxToSphereInBoxX - boxToClosestPointInBoxX; + closestPointToSphereInBoxY = boxToSphereInBoxY - boxToClosestPointInBoxY; + closestPointToSphereInBoxZ = boxToSphereInBoxZ - boxToClosestPointInBoxZ; + let dist = closestPointToSphereInBoxX * closestPointToSphereInBoxX + closestPointToSphereInBoxY * closestPointToSphereInBoxY + closestPointToSphereInBoxZ * closestPointToSphereInBoxZ; + if(dist >= r * r) { + return; + } + dist = Math.sqrt(dist); + let boxToClosestPointX; + let boxToClosestPointY; + let boxToClosestPointZ; + let closestPointToSphereX; + let closestPointToSphereY; + let closestPointToSphereZ; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * boxToClosestPointInBoxX + tf2._rotation01 * boxToClosestPointInBoxY + tf2._rotation02 * boxToClosestPointInBoxZ; + __tmp__Y1 = tf2._rotation10 * boxToClosestPointInBoxX + tf2._rotation11 * boxToClosestPointInBoxY + tf2._rotation12 * boxToClosestPointInBoxZ; + __tmp__Z1 = tf2._rotation20 * boxToClosestPointInBoxX + tf2._rotation21 * boxToClosestPointInBoxY + tf2._rotation22 * boxToClosestPointInBoxZ; + boxToClosestPointX = __tmp__X1; + boxToClosestPointY = __tmp__Y1; + boxToClosestPointZ = __tmp__Z1; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = tf2._rotation00 * closestPointToSphereInBoxX + tf2._rotation01 * closestPointToSphereInBoxY + tf2._rotation02 * closestPointToSphereInBoxZ; + __tmp__Y2 = tf2._rotation10 * closestPointToSphereInBoxX + tf2._rotation11 * closestPointToSphereInBoxY + tf2._rotation12 * closestPointToSphereInBoxZ; + __tmp__Z2 = tf2._rotation20 * closestPointToSphereInBoxX + tf2._rotation21 * closestPointToSphereInBoxY + tf2._rotation22 * closestPointToSphereInBoxZ; + closestPointToSphereX = __tmp__X2; + closestPointToSphereY = __tmp__Y2; + closestPointToSphereZ = __tmp__Z2; + let normalX; + let normalY; + let normalZ; + let l = closestPointToSphereX * closestPointToSphereX + closestPointToSphereY * closestPointToSphereY + closestPointToSphereZ * closestPointToSphereZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + normalX = closestPointToSphereX * l; + normalY = closestPointToSphereY * l; + normalZ = closestPointToSphereZ * l; + this.setNormal(result,normalX,normalY,normalZ); + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + pos1X = tf1._positionX + normalX * -r; + pos1Y = tf1._positionY + normalY * -r; + pos1Z = tf1._positionZ + normalZ * -r; + pos2X = tf2._positionX + boxToClosestPointX; + pos2Y = tf2._positionY + boxToClosestPointY; + pos2Z = tf2._positionZ + boxToClosestPointZ; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,r - dist,0); + } +} +oimo.collision.narrowphase.detector.SphereCapsuleDetector = class oimo_collision_narrowphase_detector_SphereCapsuleDetector extends oimo.collision.narrowphase.detector.Detector { + constructor(swapped) { + super(swapped); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + let c2 = geom2; + result.incremental = false; + let hh2 = c2._halfHeight; + let r1 = geom1._radius; + let r2 = c2._radius; + let axis2X; + let axis2Y; + let axis2Z; + axis2X = tf2._rotation01; + axis2Y = tf2._rotation11; + axis2Z = tf2._rotation21; + let cp1X; + let cp1Y; + let cp1Z; + cp1X = tf1._positionX; + cp1Y = tf1._positionY; + cp1Z = tf1._positionZ; + let p2X; + let p2Y; + let p2Z; + let q2X; + let q2Y; + let q2Z; + p2X = tf2._positionX + axis2X * -hh2; + p2Y = tf2._positionY + axis2Y * -hh2; + p2Z = tf2._positionZ + axis2Z * -hh2; + q2X = tf2._positionX + axis2X * hh2; + q2Y = tf2._positionY + axis2Y * hh2; + q2Z = tf2._positionZ + axis2Z * hh2; + let p12X; + let p12Y; + let p12Z; + p12X = cp1X - p2X; + p12Y = cp1Y - p2Y; + p12Z = cp1Z - p2Z; + let d2X; + let d2Y; + let d2Z; + d2X = q2X - p2X; + d2Y = q2Y - p2Y; + d2Z = q2Z - p2Z; + let d22 = hh2 * hh2 * 4; + let t = p12X * d2X + p12Y * d2Y + p12Z * d2Z; + if(t < 0) { + t = 0; + } else if(t > d22) { + t = 1; + } else { + t /= d22; + } + let cp2X; + let cp2Y; + let cp2Z; + cp2X = p2X + d2X * t; + cp2Y = p2Y + d2Y * t; + cp2Z = p2Z + d2Z * t; + let dX; + let dY; + let dZ; + dX = cp1X - cp2X; + dY = cp1Y - cp2Y; + dZ = cp1Z - cp2Z; + let len2 = dX * dX + dY * dY + dZ * dZ; + if(len2 >= (r1 + r2) * (r1 + r2)) { + return; + } + let len = Math.sqrt(len2); + let nX; + let nY; + let nZ; + if(len > 0) { + nX = dX * (1 / len); + nY = dY * (1 / len); + nZ = dZ * (1 / len); + } else { + nX = 1; + nY = 0; + nZ = 0; + } + this.setNormal(result,nX,nY,nZ); + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + pos1X = cp1X + nX * -r1; + pos1Y = cp1Y + nY * -r1; + pos1Z = cp1Z + nZ * -r1; + pos2X = cp2X + nX * r2; + pos2Y = cp2Y + nY * r2; + pos2Z = cp2Z + nZ * r2; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,r1 + r2 - len,0); + } +} +oimo.collision.narrowphase.detector.SphereSphereDetector = class oimo_collision_narrowphase_detector_SphereSphereDetector extends oimo.collision.narrowphase.detector.Detector { + constructor() { + super(false); + } + detectImpl(result,geom1,geom2,tf1,tf2,cachedData) { + result.incremental = false; + let dX; + let dY; + let dZ; + dX = tf1._positionX - tf2._positionX; + dY = tf1._positionY - tf2._positionY; + dZ = tf1._positionZ - tf2._positionZ; + let r1 = geom1._radius; + let r2 = geom2._radius; + let len2 = dX * dX + dY * dY + dZ * dZ; + if(len2 >= (r1 + r2) * (r1 + r2)) { + return; + } + let len = Math.sqrt(len2); + let nX; + let nY; + let nZ; + if(len > 0) { + nX = dX * (1 / len); + nY = dY * (1 / len); + nZ = dZ * (1 / len); + } else { + nX = 1; + nY = 0; + nZ = 0; + } + this.setNormal(result,nX,nY,nZ); + let pos1X; + let pos1Y; + let pos1Z; + let pos2X; + let pos2Y; + let pos2Z; + pos1X = tf1._positionX + nX * -r1; + pos1Y = tf1._positionY + nY * -r1; + pos1Z = tf1._positionZ + nZ * -r1; + pos2X = tf2._positionX + nX * r2; + pos2Y = tf2._positionY + nY * r2; + pos2Z = tf2._positionZ + nZ * r2; + this.addPoint(result,pos1X,pos1Y,pos1Z,pos2X,pos2Y,pos2Z,r1 + r2 - len,0); + } +} +if(!oimo.collision.narrowphase.detector.gjkepa) oimo.collision.narrowphase.detector.gjkepa = {}; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedron = class oimo_collision_narrowphase_detector_gjkepa_EpaPolyhedron { + constructor() { + this._vertices = new Array(oimo.common.Setting.maxEPAVertices); + this._center = new oimo.common.Vec3(); + this._numVertices = 0; + this._triangleList = null; + this._triangleListLast = null; + this._numTriangles = 0; + this._trianglePool = null; + this._vertexPool = null; + } + dumpHoleEdge(first) { + } + validate() { + let t = this._triangleList; + while(t != null) { + t._vertices[0]._tmpEdgeLoopOuterTriangle = null; + t._vertices[0]._tmpEdgeLoopNext = null; + if(t._adjacentPairIndex[0] == -1) { + this._status = 2; + return false; + } + if(t._adjacentTriangles[0] == null) { + this._status = 3; + return false; + } + t._vertices[1]._tmpEdgeLoopOuterTriangle = null; + t._vertices[1]._tmpEdgeLoopNext = null; + if(t._adjacentPairIndex[1] == -1) { + this._status = 2; + return false; + } + if(t._adjacentTriangles[1] == null) { + this._status = 3; + return false; + } + t._vertices[2]._tmpEdgeLoopOuterTriangle = null; + t._vertices[2]._tmpEdgeLoopNext = null; + if(t._adjacentPairIndex[2] == -1) { + this._status = 2; + return false; + } + if(t._adjacentTriangles[2] == null) { + this._status = 3; + return false; + } + t = t._next; + } + return true; + } + findEdgeLoop(id,base,from) { + if(base._tmpDfsId == id) { + return; + } + base._tmpDfsId = id; + let _this = base.tmp; + _this.x = from.x; + _this.y = from.y; + _this.z = from.z; + let v = base._vertices[0].v; + _this.x -= v.x; + _this.y -= v.y; + _this.z -= v.z; + let _this1 = base.tmp; + let v1 = base._normal; + base._tmpDfsVisible = _this1.x * v1.x + _this1.y * v1.y + _this1.z * v1.z > 0; + if(!base._tmpDfsVisible) { + this._status = 6; + return; + } + let _g = 0; + while(_g < 3) { + let i = _g++; + let t = base._adjacentTriangles[i]; + if(t == null) { + continue; + } + let _this = t.tmp; + _this.x = from.x; + _this.y = from.y; + _this.z = from.z; + let v = t._vertices[0].v; + _this.x -= v.x; + _this.y -= v.y; + _this.z -= v.z; + let _this1 = t.tmp; + let v1 = t._normal; + t._tmpDfsVisible = _this1.x * v1.x + _this1.y * v1.y + _this1.z * v1.z > 0; + if(t._tmpDfsVisible) { + this.findEdgeLoop(id,t,from); + } else { + let v1 = base._vertices[i]; + v1._tmpEdgeLoopNext = base._vertices[base._nextIndex[i]]; + v1._tmpEdgeLoopOuterTriangle = t; + } + } + let triangle = base._adjacentTriangles[0]; + if(triangle != null) { + let pairIndex = base._adjacentPairIndex[0]; + triangle._adjacentTriangles[pairIndex] = null; + triangle._adjacentPairIndex[pairIndex] = -1; + base._adjacentTriangles[0] = null; + base._adjacentPairIndex[0] = -1; + } + let triangle1 = base._adjacentTriangles[1]; + if(triangle1 != null) { + let pairIndex = base._adjacentPairIndex[1]; + triangle1._adjacentTriangles[pairIndex] = null; + triangle1._adjacentPairIndex[pairIndex] = -1; + base._adjacentTriangles[1] = null; + base._adjacentPairIndex[1] = -1; + } + let triangle2 = base._adjacentTriangles[2]; + if(triangle2 != null) { + let pairIndex = base._adjacentPairIndex[2]; + triangle2._adjacentTriangles[pairIndex] = null; + triangle2._adjacentPairIndex[pairIndex] = -1; + base._adjacentTriangles[2] = null; + base._adjacentPairIndex[2] = -1; + } + this._numTriangles--; + let prev = base._prev; + let next = base._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(base == this._triangleList) { + this._triangleList = this._triangleList._next; + } + if(base == this._triangleListLast) { + this._triangleListLast = this._triangleListLast._prev; + } + base._next = null; + base._prev = null; + base.removeReferences(); + base._next = this._trianglePool; + this._trianglePool = base; + } + _init(v1,v2,v3,v4) { + this._status = 0; + this._numVertices = 4; + this._vertices[0] = v1; + this._vertices[1] = v2; + this._vertices[2] = v3; + this._vertices[3] = v4; + let _this = this._center; + let v = v1.v; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let v5 = v2.v; + _this.x += v5.x; + _this.y += v5.y; + _this.z += v5.z; + let v6 = v3.v; + _this.x += v6.x; + _this.y += v6.y; + _this.z += v6.z; + let v7 = v4.v; + _this.x += v7.x; + _this.y += v7.y; + _this.z += v7.z; + _this.x *= 0.25; + _this.y *= 0.25; + _this.z *= 0.25; + let first = this._trianglePool; + if(first != null) { + this._trianglePool = first._next; + first._next = null; + } else { + first = new oimo.collision.narrowphase.detector.gjkepa.EpaTriangle(); + } + let t1 = first; + let first1 = this._trianglePool; + if(first1 != null) { + this._trianglePool = first1._next; + first1._next = null; + } else { + first1 = new oimo.collision.narrowphase.detector.gjkepa.EpaTriangle(); + } + let t2 = first1; + let first2 = this._trianglePool; + if(first2 != null) { + this._trianglePool = first2._next; + first2._next = null; + } else { + first2 = new oimo.collision.narrowphase.detector.gjkepa.EpaTriangle(); + } + let t3 = first2; + let first3 = this._trianglePool; + if(first3 != null) { + this._trianglePool = first3._next; + first3._next = null; + } else { + first3 = new oimo.collision.narrowphase.detector.gjkepa.EpaTriangle(); + } + let t4 = first3; + if(!t1.init(v1,v2,v3,this._center,true)) { + this._status = 1; + } + if(!t2.init(v1,v2,v4,this._center,true)) { + this._status = 1; + } + if(!t3.init(v1,v3,v4,this._center,true)) { + this._status = 1; + } + if(!t4.init(v2,v3,v4,this._center,true)) { + this._status = 1; + } + if(!t1.setAdjacentTriangle(t2)) { + this._status = 1; + } + if(!t1.setAdjacentTriangle(t3)) { + this._status = 1; + } + if(!t1.setAdjacentTriangle(t4)) { + this._status = 1; + } + if(!t2.setAdjacentTriangle(t3)) { + this._status = 1; + } + if(!t2.setAdjacentTriangle(t4)) { + this._status = 1; + } + if(!t3.setAdjacentTriangle(t4)) { + this._status = 1; + } + this._numTriangles++; + if(this._triangleList == null) { + this._triangleList = t1; + this._triangleListLast = t1; + } else { + this._triangleListLast._next = t1; + t1._prev = this._triangleListLast; + this._triangleListLast = t1; + } + this._numTriangles++; + if(this._triangleList == null) { + this._triangleList = t2; + this._triangleListLast = t2; + } else { + this._triangleListLast._next = t2; + t2._prev = this._triangleListLast; + this._triangleListLast = t2; + } + this._numTriangles++; + if(this._triangleList == null) { + this._triangleList = t3; + this._triangleListLast = t3; + } else { + this._triangleListLast._next = t3; + t3._prev = this._triangleListLast; + this._triangleListLast = t3; + } + this._numTriangles++; + if(this._triangleList == null) { + this._triangleList = t4; + this._triangleListLast = t4; + } else { + this._triangleListLast._next = t4; + t4._prev = this._triangleListLast; + this._triangleListLast = t4; + } + return this._status == 0; + } + _addVertex(vertex,base) { + this._vertices[this._numVertices++] = vertex; + let v1 = base._vertices[0]; + this.findEdgeLoop(this._numVertices,base,vertex.v); + if(this._status != 0) { + return false; + } + let v = v1; + let prevT = null; + let firstT = null; + while(true) { + if(v._tmpEdgeLoopNext == null) { + this._dumpAsObjModel(); + this._status = 4; + return false; + } + if(v._tmpEdgeLoopOuterTriangle == null) { + this._status = 5; + return false; + } + let first = this._trianglePool; + if(first != null) { + this._trianglePool = first._next; + first._next = null; + } else { + first = new oimo.collision.narrowphase.detector.gjkepa.EpaTriangle(); + } + let t = first; + if(firstT == null) { + firstT = t; + } + if(!t.init(v,v._tmpEdgeLoopNext,vertex,this._center,false)) { + this._status = 1; + } + if(this._status != 0) { + return false; + } + this._numTriangles++; + if(this._triangleList == null) { + this._triangleList = t; + this._triangleListLast = t; + } else { + this._triangleListLast._next = t; + t._prev = this._triangleListLast; + this._triangleListLast = t; + } + if(!t.setAdjacentTriangle(v._tmpEdgeLoopOuterTriangle)) { + this._status = 1; + } + if(prevT != null) { + if(!t.setAdjacentTriangle(prevT)) { + this._status = 1; + } + } + prevT = t; + v = v._tmpEdgeLoopNext; + if(!(v != v1)) { + break; + } + } + if(!prevT.setAdjacentTriangle(firstT)) { + this._status = 1; + } + if(this._status == 0) { + return this.validate(); + } else { + return false; + } + } + _dumpAsObjModel() { + } +} +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState = class oimo_collision_narrowphase_detector_gjkepa_EpaPolyhedronState { +} +oimo.collision.narrowphase.detector.gjkepa.EpaTriangle = class oimo_collision_narrowphase_detector_gjkepa_EpaTriangle { + constructor() { + this.id = ++oimo.collision.narrowphase.detector.gjkepa.EpaTriangle.count; + this._next = null; + this._prev = null; + this._normal = new oimo.common.Vec3(); + this._distanceSq = 0; + this._tmpDfsId = 0; + this._tmpDfsVisible = false; + this._vertices = new Array(3); + this._adjacentTriangles = new Array(3); + this._adjacentPairIndex = new Array(3); + this.tmp = new oimo.common.Vec3(); + this._nextIndex = new Array(3); + this._nextIndex[0] = 1; + this._nextIndex[1] = 2; + this._nextIndex[2] = 0; + } + init(vertex1,vertex2,vertex3,center,autoCheck) { + if(autoCheck == null) { + autoCheck = false; + } + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let vcX; + let vcY; + let vcZ; + let v = vertex1.v; + v1X = v.x; + v1Y = v.y; + v1Z = v.z; + let v1 = vertex2.v; + v2X = v1.x; + v2Y = v1.y; + v2Z = v1.z; + let v2 = vertex3.v; + v3X = v2.x; + v3Y = v2.y; + v3Z = v2.z; + vcX = center.x; + vcY = center.y; + vcZ = center.z; + let v12X; + let v12Y; + let v12Z; + let v13X; + let v13Y; + let v13Z; + let vc1X; + let vc1Y; + let vc1Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v13X = v3X - v1X; + v13Y = v3Y - v1Y; + v13Z = v3Z - v1Z; + vc1X = v1X - vcX; + vc1Y = v1Y - vcY; + vc1Z = v1Z - vcZ; + let inorX; + let inorY; + let inorZ; + inorX = v12Y * v13Z - v12Z * v13Y; + inorY = v12Z * v13X - v12X * v13Z; + inorZ = v12X * v13Y - v12Y * v13X; + let inverted = false; + if(vc1X * inorX + vc1Y * inorY + vc1Z * inorZ < 0) { + if(autoCheck) { + let tmp = vertex2; + vertex2 = vertex3; + vertex3 = tmp; + inorX *= -1; + inorY *= -1; + inorZ *= -1; + } else { + inverted = true; + } + } + this._vertices[0] = vertex1; + this._vertices[1] = vertex2; + this._vertices[2] = vertex3; + let v3 = this._normal; + v3.x = inorX; + v3.y = inorY; + v3.z = inorZ; + let vec1 = vertex1.v; + let vec2 = vertex2.v; + let vec3 = vertex3.v; + let out = this.tmp; + let v1X1; + let v1Y1; + let v1Z1; + let v2X1; + let v2Y1; + let v2Z1; + let v3X1; + let v3Y1; + let v3Z1; + let v12X1; + let v12Y1; + let v12Z1; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X1 = vec1.x; + v1Y1 = vec1.y; + v1Z1 = vec1.z; + v2X1 = vec2.x; + v2Y1 = vec2.y; + v2Z1 = vec2.z; + v3X1 = vec3.x; + v3Y1 = vec3.y; + v3Z1 = vec3.z; + v12X1 = v2X1 - v1X1; + v12Y1 = v2Y1 - v1Y1; + v12Z1 = v2Z1 - v1Z1; + v23X = v3X1 - v2X1; + v23Y = v3Y1 - v2Y1; + v23Z = v3Z1 - v2Z1; + v31X = v1X1 - v3X1; + v31Y = v1Y1 - v3Y1; + v31Z = v1Z1 - v3Z1; + let nX; + let nY; + let nZ; + nX = v12Y1 * v23Z - v12Z1 * v23Y; + nY = v12Z1 * v23X - v12X1 * v23Z; + nZ = v12X1 * v23Y - v12Y1 * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y1 * nZ - v12Z1 * nY; + n12Y = v12Z1 * nX - v12X1 * nZ; + n12Z = v12X1 * nY - v12Y1 * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X1 * n12X + v1Y1 * n12Y + v1Z1 * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + } + mind = out.x * out.x + out.y * out.y + out.z * out.z; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + if(v2X1 * n23X + v2Y1 * n23Y + v2Z1 * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if(v3X1 * n31X + v3Y1 * n31Y + v3Z1 * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if(mind > 0) { + out.x = minvX; + out.y = minvY; + out.z = minvZ; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X1 * nX + v1Y1 * nY + v1Z1 * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + out.x = minvX; + out.y = minvY; + out.z = minvZ; + } + let _this = this.tmp; + this._distanceSq = _this.x * _this.x + _this.y * _this.y + _this.z * _this.z; + this._adjacentTriangles[0] = null; + this._adjacentTriangles[1] = null; + this._adjacentTriangles[2] = null; + this._adjacentPairIndex[0] = -1; + this._adjacentPairIndex[1] = -1; + this._adjacentPairIndex[2] = -1; + return !inverted; + } + setAdjacentTriangle(triangle) { + let count = 0; + if(this._vertices[0] == triangle._vertices[this._nextIndex[0]] && this._vertices[this._nextIndex[0]] == triangle._vertices[0]) { + this._adjacentTriangles[0] = triangle; + this._adjacentPairIndex[0] = 0; + triangle._adjacentTriangles[0] = this; + triangle._adjacentPairIndex[0] = 0; + count = 1; + } + if(this._vertices[0] == triangle._vertices[this._nextIndex[1]] && this._vertices[this._nextIndex[0]] == triangle._vertices[1]) { + this._adjacentTriangles[0] = triangle; + this._adjacentPairIndex[0] = 1; + triangle._adjacentTriangles[1] = this; + triangle._adjacentPairIndex[1] = 0; + ++count; + } + if(this._vertices[0] == triangle._vertices[this._nextIndex[2]] && this._vertices[this._nextIndex[0]] == triangle._vertices[2]) { + this._adjacentTriangles[0] = triangle; + this._adjacentPairIndex[0] = 2; + triangle._adjacentTriangles[2] = this; + triangle._adjacentPairIndex[2] = 0; + ++count; + } + if(this._vertices[1] == triangle._vertices[this._nextIndex[0]] && this._vertices[this._nextIndex[1]] == triangle._vertices[0]) { + this._adjacentTriangles[1] = triangle; + this._adjacentPairIndex[1] = 0; + triangle._adjacentTriangles[0] = this; + triangle._adjacentPairIndex[0] = 1; + ++count; + } + if(this._vertices[1] == triangle._vertices[this._nextIndex[1]] && this._vertices[this._nextIndex[1]] == triangle._vertices[1]) { + this._adjacentTriangles[1] = triangle; + this._adjacentPairIndex[1] = 1; + triangle._adjacentTriangles[1] = this; + triangle._adjacentPairIndex[1] = 1; + ++count; + } + if(this._vertices[1] == triangle._vertices[this._nextIndex[2]] && this._vertices[this._nextIndex[1]] == triangle._vertices[2]) { + this._adjacentTriangles[1] = triangle; + this._adjacentPairIndex[1] = 2; + triangle._adjacentTriangles[2] = this; + triangle._adjacentPairIndex[2] = 1; + ++count; + } + if(this._vertices[2] == triangle._vertices[this._nextIndex[0]] && this._vertices[this._nextIndex[2]] == triangle._vertices[0]) { + this._adjacentTriangles[2] = triangle; + this._adjacentPairIndex[2] = 0; + triangle._adjacentTriangles[0] = this; + triangle._adjacentPairIndex[0] = 2; + ++count; + } + if(this._vertices[2] == triangle._vertices[this._nextIndex[1]] && this._vertices[this._nextIndex[2]] == triangle._vertices[1]) { + this._adjacentTriangles[2] = triangle; + this._adjacentPairIndex[2] = 1; + triangle._adjacentTriangles[1] = this; + triangle._adjacentPairIndex[1] = 2; + ++count; + } + if(this._vertices[2] == triangle._vertices[this._nextIndex[2]] && this._vertices[this._nextIndex[2]] == triangle._vertices[2]) { + this._adjacentTriangles[2] = triangle; + this._adjacentPairIndex[2] = 2; + triangle._adjacentTriangles[2] = this; + triangle._adjacentPairIndex[2] = 2; + ++count; + } + if(count != 1) { + return false; + } + return true; + } + removeAdjacentTriangles() { + let triangle = this._adjacentTriangles[0]; + if(triangle != null) { + let pairIndex = this._adjacentPairIndex[0]; + triangle._adjacentTriangles[pairIndex] = null; + triangle._adjacentPairIndex[pairIndex] = -1; + this._adjacentTriangles[0] = null; + this._adjacentPairIndex[0] = -1; + } + let triangle1 = this._adjacentTriangles[1]; + if(triangle1 != null) { + let pairIndex = this._adjacentPairIndex[1]; + triangle1._adjacentTriangles[pairIndex] = null; + triangle1._adjacentPairIndex[pairIndex] = -1; + this._adjacentTriangles[1] = null; + this._adjacentPairIndex[1] = -1; + } + let triangle2 = this._adjacentTriangles[2]; + if(triangle2 != null) { + let pairIndex = this._adjacentPairIndex[2]; + triangle2._adjacentTriangles[pairIndex] = null; + triangle2._adjacentPairIndex[pairIndex] = -1; + this._adjacentTriangles[2] = null; + this._adjacentPairIndex[2] = -1; + } + } + removeReferences() { + this._next = null; + this._prev = null; + this._tmpDfsId = 0; + this._tmpDfsVisible = false; + this._distanceSq = 0; + this._vertices[0] = null; + this._vertices[1] = null; + this._vertices[2] = null; + this._adjacentTriangles[0] = null; + this._adjacentTriangles[1] = null; + this._adjacentTriangles[2] = null; + this._adjacentPairIndex[0] = 0; + this._adjacentPairIndex[1] = 0; + this._adjacentPairIndex[2] = 0; + } + dump() { + } +} +oimo.collision.narrowphase.detector.gjkepa.EpaVertex = class oimo_collision_narrowphase_detector_gjkepa_EpaVertex { + constructor() { + this.randId = Math.random() * 100000 | 0; + this.v = new oimo.common.Vec3(); + this.w1 = new oimo.common.Vec3(); + this.w2 = new oimo.common.Vec3(); + } + init(v,w1,w2) { + let _this = this.v; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let _this1 = this.w1; + _this1.x = w1.x; + _this1.y = w1.y; + _this1.z = w1.z; + let _this2 = this.w2; + _this2.x = w2.x; + _this2.y = w2.y; + _this2.z = w2.z; + this._next = null; + this._tmpEdgeLoopNext = null; + this._tmpEdgeLoopOuterTriangle = null; + return this; + } + removeReferences() { + this._next = null; + this._tmpEdgeLoopNext = null; + this._tmpEdgeLoopOuterTriangle = null; + } +} +oimo.collision.narrowphase.detector.gjkepa.GjkCache = class oimo_collision_narrowphase_detector_gjkepa_GjkCache { + constructor() { + this.prevClosestDir = new oimo.common.Vec3(); + } + clear() { + this.prevClosestDir.zero(); + } +} +if(!oimo.common) oimo.common = {}; +oimo.common.Vec3 = class oimo_common_Vec3 { + constructor(x,y,z) { + if(z == null) { + z = 0; + } + if(y == null) { + y = 0; + } + if(x == null) { + x = 0; + } + this.x = x; + this.y = y; + this.z = z; + oimo.common.Vec3.numCreations++; + } + init(x,y,z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + zero() { + this.x = 0; + this.y = 0; + this.z = 0; + return this; + } + add(v) { + return new oimo.common.Vec3(this.x + v.x,this.y + v.y,this.z + v.z); + } + add3(vx,vy,vz) { + return new oimo.common.Vec3(this.x + vx,this.y + vy,this.z + vz); + } + addScaled(v,s) { + return new oimo.common.Vec3(this.x + v.x * s,this.y + v.y * s,this.z + v.z * s); + } + sub(v) { + return new oimo.common.Vec3(this.x - v.x,this.y - v.y,this.z - v.z); + } + sub3(vx,vy,vz) { + return new oimo.common.Vec3(this.x - vx,this.y - vy,this.z - vz); + } + scale(s) { + return new oimo.common.Vec3(this.x * s,this.y * s,this.z * s); + } + scale3(sx,sy,sz) { + return new oimo.common.Vec3(this.x * sx,this.y * sy,this.z * sz); + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + cross(v) { + return new oimo.common.Vec3(this.y * v.z - this.z * v.y,this.z * v.x - this.x * v.z,this.x * v.y - this.y * v.x); + } + addEq(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + add3Eq(vx,vy,vz) { + this.x += vx; + this.y += vy; + this.z += vz; + return this; + } + addScaledEq(v,s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + subEq(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + sub3Eq(vx,vy,vz) { + this.x -= vx; + this.y -= vy; + this.z -= vz; + return this; + } + scaleEq(s) { + this.x *= s; + this.y *= s; + this.z *= s; + return this; + } + scale3Eq(sx,sy,sz) { + this.x *= sx; + this.y *= sy; + this.z *= sz; + return this; + } + crossEq(v) { + let y = this.z * v.x - this.x * v.z; + let z = this.x * v.y - this.y * v.x; + this.x = this.y * v.z - this.z * v.y; + this.y = y; + this.z = z; + return this; + } + mulMat3(m) { + return new oimo.common.Vec3(this.x * m.e00 + this.y * m.e01 + this.z * m.e02,this.x * m.e10 + this.y * m.e11 + this.z * m.e12,this.x * m.e20 + this.y * m.e21 + this.z * m.e22); + } + mulMat4(m) { + return new oimo.common.Vec3(this.x * m.e00 + this.y * m.e01 + this.z * m.e02 + m.e03,this.x * m.e10 + this.y * m.e11 + this.z * m.e12 + m.e13,this.x * m.e20 + this.y * m.e21 + this.z * m.e22 + m.e23); + } + mulTransform(tf) { + let vX; + let vY; + let vZ; + vX = this.x; + vY = this.y; + vZ = this.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf._rotation00 * vX + tf._rotation01 * vY + tf._rotation02 * vZ; + __tmp__Y = tf._rotation10 * vX + tf._rotation11 * vY + tf._rotation12 * vZ; + __tmp__Z = tf._rotation20 * vX + tf._rotation21 * vY + tf._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + vX += tf._positionX; + vY += tf._positionY; + vZ += tf._positionZ; + let res = new oimo.common.Vec3(); + res.x = vX; + res.y = vY; + res.z = vZ; + return res; + } + mulMat3Eq(m) { + let y = this.x * m.e10 + this.y * m.e11 + this.z * m.e12; + let z = this.x * m.e20 + this.y * m.e21 + this.z * m.e22; + this.x = this.x * m.e00 + this.y * m.e01 + this.z * m.e02; + this.y = y; + this.z = z; + return this; + } + mulMat4Eq(m) { + let y = this.x * m.e10 + this.y * m.e11 + this.z * m.e12 + m.e13; + let z = this.x * m.e20 + this.y * m.e21 + this.z * m.e22 + m.e23; + this.x = this.x * m.e00 + this.y * m.e01 + this.z * m.e02 + m.e03; + this.y = y; + this.z = z; + return this; + } + mulTransformEq(tf) { + let vX; + let vY; + let vZ; + vX = this.x; + vY = this.y; + vZ = this.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf._rotation00 * vX + tf._rotation01 * vY + tf._rotation02 * vZ; + __tmp__Y = tf._rotation10 * vX + tf._rotation11 * vY + tf._rotation12 * vZ; + __tmp__Z = tf._rotation20 * vX + tf._rotation21 * vY + tf._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + vX += tf._positionX; + vY += tf._positionY; + vZ += tf._positionZ; + this.x = vX; + this.y = vY; + this.z = vZ; + return this; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + normalized() { + let invLen = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + return new oimo.common.Vec3(this.x * invLen,this.y * invLen,this.z * invLen); + } + normalize() { + let invLen = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + this.x *= invLen; + this.y *= invLen; + this.z *= invLen; + return this; + } + negate() { + return new oimo.common.Vec3(-this.x,-this.y,-this.z); + } + negateEq() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + copyFrom(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + clone() { + return new oimo.common.Vec3(this.x,this.y,this.z); + } + toString() { + return "Vec3[" + (this.x > 0 ? (this.x * 10000000 + 0.5 | 0) / 10000000 : (this.x * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.y > 0 ? (this.y * 10000000 + 0.5 | 0) / 10000000 : (this.y * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.z > 0 ? (this.z * 10000000 + 0.5 | 0) / 10000000 : (this.z * 10000000 - 0.5 | 0) / 10000000) + "]"; + } +} +oimo.common.Transform = class oimo_common_Transform { + constructor() { + this._positionX = 0; + this._positionY = 0; + this._positionZ = 0; + this._rotation00 = 1; + this._rotation01 = 0; + this._rotation02 = 0; + this._rotation10 = 0; + this._rotation11 = 1; + this._rotation12 = 0; + this._rotation20 = 0; + this._rotation21 = 0; + this._rotation22 = 1; + } + identity() { + this._positionX = 0; + this._positionY = 0; + this._positionZ = 0; + this._rotation00 = 1; + this._rotation01 = 0; + this._rotation02 = 0; + this._rotation10 = 0; + this._rotation11 = 1; + this._rotation12 = 0; + this._rotation20 = 0; + this._rotation21 = 0; + this._rotation22 = 1; + return this; + } + getPosition() { + let position = new oimo.common.Vec3(); + position.x = this._positionX; + position.y = this._positionY; + position.z = this._positionZ; + return position; + } + getPositionTo(position) { + position.x = this._positionX; + position.y = this._positionY; + position.z = this._positionZ; + } + setPosition(position) { + this._positionX = position.x; + this._positionY = position.y; + this._positionZ = position.z; + return this; + } + translate(translation) { + let diffX; + let diffY; + let diffZ; + diffX = translation.x; + diffY = translation.y; + diffZ = translation.z; + this._positionX += diffX; + this._positionY += diffY; + this._positionZ += diffZ; + } + getRotation() { + let rotation = new oimo.common.Mat3(); + rotation.e00 = this._rotation00; + rotation.e01 = this._rotation01; + rotation.e02 = this._rotation02; + rotation.e10 = this._rotation10; + rotation.e11 = this._rotation11; + rotation.e12 = this._rotation12; + rotation.e20 = this._rotation20; + rotation.e21 = this._rotation21; + rotation.e22 = this._rotation22; + return rotation; + } + getRotationTo(out) { + out.e00 = this._rotation00; + out.e01 = this._rotation01; + out.e02 = this._rotation02; + out.e10 = this._rotation10; + out.e11 = this._rotation11; + out.e12 = this._rotation12; + out.e20 = this._rotation20; + out.e21 = this._rotation21; + out.e22 = this._rotation22; + } + setRotation(rotation) { + this._rotation00 = rotation.e00; + this._rotation01 = rotation.e01; + this._rotation02 = rotation.e02; + this._rotation10 = rotation.e10; + this._rotation11 = rotation.e11; + this._rotation12 = rotation.e12; + this._rotation20 = rotation.e20; + this._rotation21 = rotation.e21; + this._rotation22 = rotation.e22; + return this; + } + setRotationXyz(eulerAngles) { + let xyzX; + let xyzY; + let xyzZ; + xyzX = eulerAngles.x; + xyzY = eulerAngles.y; + xyzZ = eulerAngles.z; + let sx = Math.sin(xyzX); + let sy = Math.sin(xyzY); + let sz = Math.sin(xyzZ); + let cx = Math.cos(xyzX); + let cy = Math.cos(xyzY); + let cz = Math.cos(xyzZ); + this._rotation00 = cy * cz; + this._rotation01 = -cy * sz; + this._rotation02 = sy; + this._rotation10 = cx * sz + cz * sx * sy; + this._rotation11 = cx * cz - sx * sy * sz; + this._rotation12 = -cy * sx; + this._rotation20 = sx * sz - cx * cz * sy; + this._rotation21 = cz * sx + cx * sy * sz; + this._rotation22 = cx * cy; + } + rotate(rotation) { + let rot00; + let rot01; + let rot02; + let rot10; + let rot11; + let rot12; + let rot20; + let rot21; + let rot22; + rot00 = rotation.e00; + rot01 = rotation.e01; + rot02 = rotation.e02; + rot10 = rotation.e10; + rot11 = rotation.e11; + rot12 = rotation.e12; + rot20 = rotation.e20; + rot21 = rotation.e21; + rot22 = rotation.e22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot00 * this._rotation00 + rot01 * this._rotation10 + rot02 * this._rotation20; + __tmp__01 = rot00 * this._rotation01 + rot01 * this._rotation11 + rot02 * this._rotation21; + __tmp__02 = rot00 * this._rotation02 + rot01 * this._rotation12 + rot02 * this._rotation22; + __tmp__10 = rot10 * this._rotation00 + rot11 * this._rotation10 + rot12 * this._rotation20; + __tmp__11 = rot10 * this._rotation01 + rot11 * this._rotation11 + rot12 * this._rotation21; + __tmp__12 = rot10 * this._rotation02 + rot11 * this._rotation12 + rot12 * this._rotation22; + __tmp__20 = rot20 * this._rotation00 + rot21 * this._rotation10 + rot22 * this._rotation20; + __tmp__21 = rot20 * this._rotation01 + rot21 * this._rotation11 + rot22 * this._rotation21; + __tmp__22 = rot20 * this._rotation02 + rot21 * this._rotation12 + rot22 * this._rotation22; + this._rotation00 = __tmp__00; + this._rotation01 = __tmp__01; + this._rotation02 = __tmp__02; + this._rotation10 = __tmp__10; + this._rotation11 = __tmp__11; + this._rotation12 = __tmp__12; + this._rotation20 = __tmp__20; + this._rotation21 = __tmp__21; + this._rotation22 = __tmp__22; + } + rotateXyz(eulerAngles) { + let xyzX; + let xyzY; + let xyzZ; + let rot00; + let rot01; + let rot02; + let rot10; + let rot11; + let rot12; + let rot20; + let rot21; + let rot22; + xyzX = eulerAngles.x; + xyzY = eulerAngles.y; + xyzZ = eulerAngles.z; + let sx = Math.sin(xyzX); + let sy = Math.sin(xyzY); + let sz = Math.sin(xyzZ); + let cx = Math.cos(xyzX); + let cy = Math.cos(xyzY); + let cz = Math.cos(xyzZ); + rot00 = cy * cz; + rot01 = -cy * sz; + rot02 = sy; + rot10 = cx * sz + cz * sx * sy; + rot11 = cx * cz - sx * sy * sz; + rot12 = -cy * sx; + rot20 = sx * sz - cx * cz * sy; + rot21 = cz * sx + cx * sy * sz; + rot22 = cx * cy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot00 * this._rotation00 + rot01 * this._rotation10 + rot02 * this._rotation20; + __tmp__01 = rot00 * this._rotation01 + rot01 * this._rotation11 + rot02 * this._rotation21; + __tmp__02 = rot00 * this._rotation02 + rot01 * this._rotation12 + rot02 * this._rotation22; + __tmp__10 = rot10 * this._rotation00 + rot11 * this._rotation10 + rot12 * this._rotation20; + __tmp__11 = rot10 * this._rotation01 + rot11 * this._rotation11 + rot12 * this._rotation21; + __tmp__12 = rot10 * this._rotation02 + rot11 * this._rotation12 + rot12 * this._rotation22; + __tmp__20 = rot20 * this._rotation00 + rot21 * this._rotation10 + rot22 * this._rotation20; + __tmp__21 = rot20 * this._rotation01 + rot21 * this._rotation11 + rot22 * this._rotation21; + __tmp__22 = rot20 * this._rotation02 + rot21 * this._rotation12 + rot22 * this._rotation22; + this._rotation00 = __tmp__00; + this._rotation01 = __tmp__01; + this._rotation02 = __tmp__02; + this._rotation10 = __tmp__10; + this._rotation11 = __tmp__11; + this._rotation12 = __tmp__12; + this._rotation20 = __tmp__20; + this._rotation21 = __tmp__21; + this._rotation22 = __tmp__22; + } + getOrientation() { + let q = new oimo.common.Quat(); + let iqX; + let iqY; + let iqZ; + let iqW; + let e00 = this._rotation00; + let e11 = this._rotation11; + let e22 = this._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + iqW = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation21 - this._rotation12) * s; + iqY = (this._rotation02 - this._rotation20) * s; + iqZ = (this._rotation10 - this._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + iqX = 0.5 * s; + s = 0.5 / s; + iqY = (this._rotation01 + this._rotation10) * s; + iqZ = (this._rotation02 + this._rotation20) * s; + iqW = (this._rotation21 - this._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation02 + this._rotation20) * s; + iqY = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation10 - this._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + iqY = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation01 + this._rotation10) * s; + iqZ = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation02 - this._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation02 + this._rotation20) * s; + iqY = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation10 - this._rotation01) * s; + } + q.x = iqX; + q.y = iqY; + q.z = iqZ; + q.w = iqW; + return q; + } + getOrientationTo(orientation) { + let iqX; + let iqY; + let iqZ; + let iqW; + let e00 = this._rotation00; + let e11 = this._rotation11; + let e22 = this._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + iqW = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation21 - this._rotation12) * s; + iqY = (this._rotation02 - this._rotation20) * s; + iqZ = (this._rotation10 - this._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + iqX = 0.5 * s; + s = 0.5 / s; + iqY = (this._rotation01 + this._rotation10) * s; + iqZ = (this._rotation02 + this._rotation20) * s; + iqW = (this._rotation21 - this._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation02 + this._rotation20) * s; + iqY = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation10 - this._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + iqY = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation01 + this._rotation10) * s; + iqZ = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation02 - this._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._rotation02 + this._rotation20) * s; + iqY = (this._rotation12 + this._rotation21) * s; + iqW = (this._rotation10 - this._rotation01) * s; + } + orientation.x = iqX; + orientation.y = iqY; + orientation.z = iqZ; + orientation.w = iqW; + } + setOrientation(quaternion) { + let qX; + let qY; + let qZ; + let qW; + qX = quaternion.x; + qY = quaternion.y; + qZ = quaternion.z; + qW = quaternion.w; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + this._rotation00 = 1 - yy - zz; + this._rotation01 = xy - wz; + this._rotation02 = xz + wy; + this._rotation10 = xy + wz; + this._rotation11 = 1 - xx - zz; + this._rotation12 = yz - wx; + this._rotation20 = xz - wy; + this._rotation21 = yz + wx; + this._rotation22 = 1 - xx - yy; + return this; + } + clone() { + let tf = new oimo.common.Transform(); + tf._positionX = this._positionX; + tf._positionY = this._positionY; + tf._positionZ = this._positionZ; + tf._rotation00 = this._rotation00; + tf._rotation01 = this._rotation01; + tf._rotation02 = this._rotation02; + tf._rotation10 = this._rotation10; + tf._rotation11 = this._rotation11; + tf._rotation12 = this._rotation12; + tf._rotation20 = this._rotation20; + tf._rotation21 = this._rotation21; + tf._rotation22 = this._rotation22; + return tf; + } + copyFrom(transform) { + this._positionX = transform._positionX; + this._positionY = transform._positionY; + this._positionZ = transform._positionZ; + this._rotation00 = transform._rotation00; + this._rotation01 = transform._rotation01; + this._rotation02 = transform._rotation02; + this._rotation10 = transform._rotation10; + this._rotation11 = transform._rotation11; + this._rotation12 = transform._rotation12; + this._rotation20 = transform._rotation20; + this._rotation21 = transform._rotation21; + this._rotation22 = transform._rotation22; + return this; + } +} +oimo.common.Setting = class oimo_common_Setting { +} +oimo.collision.narrowphase.detector.gjkepa.GjkEpa = class oimo_collision_narrowphase_detector_gjkepa_GjkEpa { + constructor() { + this.s = new Array(4); + this.w1 = new Array(4); + this.w2 = new Array(4); + this.baseDirs = new Array(3); + this.baseDirs[0] = new oimo.common.Vec3(1,0,0); + this.baseDirs[1] = new oimo.common.Vec3(0,1,0); + this.baseDirs[2] = new oimo.common.Vec3(0,0,1); + this.tl1 = new oimo.common.Vec3(); + this.tl2 = new oimo.common.Vec3(); + this.rayX = new oimo.common.Vec3(); + this.rayR = new oimo.common.Vec3(); + this.tempTransform = new oimo.common.Transform(); + this.s[0] = new oimo.common.Vec3(); + this.w1[0] = new oimo.common.Vec3(); + this.w2[0] = new oimo.common.Vec3(); + this.s[1] = new oimo.common.Vec3(); + this.w1[1] = new oimo.common.Vec3(); + this.w2[1] = new oimo.common.Vec3(); + this.s[2] = new oimo.common.Vec3(); + this.w1[2] = new oimo.common.Vec3(); + this.w2[2] = new oimo.common.Vec3(); + this.s[3] = new oimo.common.Vec3(); + this.w1[3] = new oimo.common.Vec3(); + this.w2[3] = new oimo.common.Vec3(); + this.dir = new oimo.common.Vec3(); + this.closest = new oimo.common.Vec3(); + this.closestPoint1 = new oimo.common.Vec3(); + this.closestPoint2 = new oimo.common.Vec3(); + this.polyhedron = new oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedron(); + } + computeClosestPointsImpl(c1,c2,tf1,tf2,cache,useEpa) { + this.c1 = c1; + this.c2 = c2; + this.tf1 = tf1; + this.tf2 = tf2; + let s = this.s; + let w1 = this.w1; + let w2 = this.w2; + let closest = this.closest; + let dir = this.dir; + if(cache != null) { + if(cache._gjkCache == null) { + cache._gjkCache = new oimo.collision.narrowphase.detector.gjkepa.GjkCache(); + } + this.loadCache(cache._gjkCache); + } else { + dir.zero(); + } + if(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z == 0) { + let firstDirX; + let firstDirY; + let firstDirZ; + firstDirX = tf2._positionX - tf1._positionX; + firstDirY = tf2._positionY - tf1._positionY; + firstDirZ = tf2._positionZ - tf1._positionZ; + dir.x = firstDirX; + dir.y = firstDirY; + dir.z = firstDirZ; + if(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z < 1e-6) { + dir.init(1,0,0); + } + } + this.simplexSize = 0; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this = this.s[this.simplexSize]; + let v = this.w1[this.simplexSize]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let v1 = this.w2[this.simplexSize]; + _this.x -= v1.x; + _this.y -= v1.y; + _this.z -= v1.z; + this.simplexSize = 1; + let count = 0; + while(count < 40) { + let v = 0; + switch(this.simplexSize) { + case 1: + let v1 = s[0]; + closest.x = v1.x; + closest.y = v1.y; + closest.z = v1.z; + v = 1; + break; + case 2: + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v2 = s[0]; + v1X = v2.x; + v1Y = v2.y; + v1Z = v2.z; + let v3 = s[1]; + v2X = v3.x; + v2Y = v3.y; + v2Z = v3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + v = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + v = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + v = 3; + } + break; + case 3: + let vec1 = s[0]; + let vec2 = s[1]; + let vec3 = s[2]; + let v1X1; + let v1Y1; + let v1Z1; + let v2X1; + let v2Y1; + let v2Z1; + let v3X; + let v3Y; + let v3Z; + let v12X1; + let v12Y1; + let v12Z1; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X1 = vec1.x; + v1Y1 = vec1.y; + v1Z1 = vec1.z; + v2X1 = vec2.x; + v2Y1 = vec2.y; + v2Z1 = vec2.z; + v3X = vec3.x; + v3Y = vec3.y; + v3Z = vec3.z; + v12X1 = v2X1 - v1X1; + v12Y1 = v2Y1 - v1Y1; + v12Z1 = v2Z1 - v1Z1; + v23X = v3X - v2X1; + v23Y = v3Y - v2Y1; + v23Z = v3Z - v2Z1; + v31X = v1X1 - v3X; + v31Y = v1Y1 - v3Y; + v31Z = v1Z1 - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y1 * v23Z - v12Z1 * v23Y; + nY = v12Z1 * v23X - v12X1 * v23Z; + nZ = v12X1 * v23Y - v12Y1 * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y1 * nZ - v12Z1 * nY; + n12Y = v12Z1 * nX - v12X1 * nZ; + n12Z = v12X1 * nY - v12Y1 * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X1 * n12X + v1Y1 * n12Y + v1Z1 * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X1 * n23X + v2Y1 * n23Y + v2Z1 * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + v = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X1 * nX + v1Y1 * nY + v1Z1 * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + v = 7; + } + break; + case 4: + let vec11 = s[0]; + let vec21 = s[1]; + let vec31 = s[2]; + let vec4 = s[3]; + let v1X2; + let v1Y2; + let v1Z2; + let v2X2; + let v2Y2; + let v2Z2; + let v3X1; + let v3Y1; + let v3Z1; + let v4X; + let v4Y; + let v4Z; + let v12X2; + let v12Y2; + let v12Z2; + let v13X; + let v13Y; + let v13Z; + let v14X; + let v14Y; + let v14Z; + let v23X1; + let v23Y1; + let v23Z1; + let v24X; + let v24Y; + let v24Z; + v1X2 = vec11.x; + v1Y2 = vec11.y; + v1Z2 = vec11.z; + v2X2 = vec21.x; + v2Y2 = vec21.y; + v2Z2 = vec21.z; + v3X1 = vec31.x; + v3Y1 = vec31.y; + v3Z1 = vec31.z; + v4X = vec4.x; + v4Y = vec4.y; + v4Z = vec4.z; + v12X2 = v2X2 - v1X2; + v12Y2 = v2Y2 - v1Y2; + v12Z2 = v2Z2 - v1Z2; + v13X = v3X1 - v1X2; + v13Y = v3Y1 - v1Y2; + v13Z = v3Z1 - v1Z2; + v14X = v4X - v1X2; + v14Y = v4Y - v1Y2; + v14Z = v4Z - v1Z2; + v23X1 = v3X1 - v2X2; + v23Y1 = v3Y1 - v2Y2; + v23Z1 = v3Z1 - v2Z2; + v24X = v4X - v2X2; + v24Y = v4Y - v2Y2; + v24Z = v4Z - v2Z2; + let n123X; + let n123Y; + let n123Z; + let n134X; + let n134Y; + let n134Z; + let n142X; + let n142Y; + let n142Z; + let n243X; + let n243Y; + let n243Z; + n123X = v12Y2 * v13Z - v12Z2 * v13Y; + n123Y = v12Z2 * v13X - v12X2 * v13Z; + n123Z = v12X2 * v13Y - v12Y2 * v13X; + n134X = v13Y * v14Z - v13Z * v14Y; + n134Y = v13Z * v14X - v13X * v14Z; + n134Z = v13X * v14Y - v13Y * v14X; + n142X = v14Y * v12Z2 - v14Z * v12Y2; + n142Y = v14Z * v12X2 - v14X * v12Z2; + n142Z = v14X * v12Y2 - v14Y * v12X2; + n243X = v24Y * v23Z1 - v24Z * v23Y1; + n243Y = v24Z * v23X1 - v24X * v23Z1; + n243Z = v24X * v23Y1 - v24Y * v23X1; + let sign = v12X2 * n243X + v12Y2 * n243Y + v12Z2 * n243Z > 0 ? 1 : -1; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if((v1X2 * n123X + v1Y2 * n123Y + v1Z2 * n123Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + v3X = vec31.x; + v3Y = vec31.y; + v3Z = vec31.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + mini1 = b; + mind1 = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + if((v1X2 * n134X + v1Y2 * n134Y + v1Z2 * n134Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec31.x; + v1Y = vec31.y; + v1Z = vec31.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 6) << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if((v1X2 * n142X + v1Y2 * n142Y + v1Z2 * n142Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 3 | (b & 4) << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if((v2X2 * n243X + v2Y2 * n243Y + v2Z2 * n243Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec31.x; + v1Y = vec31.y; + v1Z = vec31.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if(mind1 > 0) { + closest.x = minvX1; + closest.y = minvY1; + closest.z = minvZ1; + v = mini1; + } else { + closest.zero(); + v = 15; + } + break; + } + if(closest.x * closest.x + closest.y * closest.y + closest.z * closest.z < 1e-008) { + if(!useEpa) { + this.distance = 0; + return 0; + } + switch(this.simplexSize) { + case 1: + this.pointToTetrahedron(); + break; + case 2: + this.lineToTetrahedron(); + break; + case 3: + this.triangleToTetrahedron(); + break; + } + if(this.simplexSize == 4) { + let epaState = this.computeDepth(c1,c2,tf1,tf2,s,w1,w2); + if(epaState != 0) { + this.distance = 0; + return epaState; + } + this.distance = -this.depth; + return 0; + } + this.distance = 0; + return 1; + } + this.shrinkSimplex(v); + dir.x = closest.x; + dir.y = closest.y; + dir.z = closest.z; + dir.x = -dir.x; + dir.y = -dir.y; + dir.z = -dir.z; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this = this.s[this.simplexSize]; + let v4 = this.w1[this.simplexSize]; + _this.x = v4.x; + _this.y = v4.y; + _this.z = v4.z; + let v5 = this.w2[this.simplexSize]; + _this.x -= v5.x; + _this.y -= v5.y; + _this.z -= v5.z; + if(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z < 1e-008) { + throw new Error("!?"); + } + let _this1 = s[this.simplexSize]; + if(_this1.x * dir.x + _this1.y * dir.y + _this1.z * dir.z - (closest.x * dir.x + closest.y * dir.y + closest.z * dir.z) < 1e-008) { + this.interpolateClosestPoints(); + this.distance = Math.sqrt(closest.x * closest.x + closest.y * closest.y + closest.z * closest.z); + if(cache != null && cache._gjkCache != null) { + this.saveCache(cache._gjkCache); + } + return 0; + } + this.simplexSize++; + ++count; + } + return 2; + } + convexCastImpl(c1,c2,tf1,tf2,tl1,tl2,hit) { + this.c1 = c1; + this.c2 = c2; + this.tf1 = tf1; + this.tf2 = tf2; + let s = this.s; + let closest = this.closest; + let dir = this.dir; + let firstDirX; + let firstDirY; + let firstDirZ; + firstDirX = tf2._positionX - tf1._positionX; + firstDirY = tf2._positionY - tf1._positionY; + firstDirZ = tf2._positionZ - tf1._positionZ; + dir.x = firstDirX; + dir.y = firstDirY; + dir.z = firstDirZ; + if(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z < 1e-6) { + dir.init(1,0,0); + } + this.simplexSize = 0; + if(this.c1 != null) { + this.computeWitnessPoint1(true); + } else { + let v = this.w1[this.simplexSize]; + v.x = this.tf1._positionX; + v.y = this.tf1._positionY; + v.z = this.tf1._positionZ; + } + this.computeWitnessPoint2(true); + let _this = this.s[this.simplexSize]; + let v = this.w1[this.simplexSize]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let v1 = this.w2[this.simplexSize]; + _this.x -= v1.x; + _this.y -= v1.y; + _this.z -= v1.z; + this.simplexSize = 1; + let count = 0; + let lambda = 0.0; + let rayX = this.rayX; + let rayR = this.rayR; + rayX.zero(); + rayR.x = tl2.x; + rayR.y = tl2.y; + rayR.z = tl2.z; + rayR.x -= tl1.x; + rayR.y -= tl1.y; + rayR.z -= tl1.z; + while(count < 40) { + let v = 0; + switch(this.simplexSize) { + case 1: + let v1 = s[0]; + closest.x = v1.x; + closest.y = v1.y; + closest.z = v1.z; + v = 1; + break; + case 2: + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v2 = s[0]; + v1X = v2.x; + v1Y = v2.y; + v1Z = v2.z; + let v3 = s[1]; + v2X = v3.x; + v2Y = v3.y; + v2Z = v3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + v = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + v = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + v = 3; + } + break; + case 3: + let vec1 = s[0]; + let vec2 = s[1]; + let vec3 = s[2]; + let v1X1; + let v1Y1; + let v1Z1; + let v2X1; + let v2Y1; + let v2Z1; + let v3X; + let v3Y; + let v3Z; + let v12X1; + let v12Y1; + let v12Z1; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X1 = vec1.x; + v1Y1 = vec1.y; + v1Z1 = vec1.z; + v2X1 = vec2.x; + v2Y1 = vec2.y; + v2Z1 = vec2.z; + v3X = vec3.x; + v3Y = vec3.y; + v3Z = vec3.z; + v12X1 = v2X1 - v1X1; + v12Y1 = v2Y1 - v1Y1; + v12Z1 = v2Z1 - v1Z1; + v23X = v3X - v2X1; + v23Y = v3Y - v2Y1; + v23Z = v3Z - v2Z1; + v31X = v1X1 - v3X; + v31Y = v1Y1 - v3Y; + v31Z = v1Z1 - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y1 * v23Z - v12Z1 * v23Y; + nY = v12Z1 * v23X - v12X1 * v23Z; + nZ = v12X1 * v23Y - v12Y1 * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y1 * nZ - v12Z1 * nY; + n12Y = v12Z1 * nX - v12X1 * nZ; + n12Z = v12X1 * nY - v12Y1 * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X1 * n12X + v1Y1 * n12Y + v1Z1 * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X1 * n23X + v2Y1 * n23Y + v2Z1 * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + v = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X1 * nX + v1Y1 * nY + v1Z1 * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + v = 7; + } + break; + case 4: + let vec11 = s[0]; + let vec21 = s[1]; + let vec31 = s[2]; + let vec4 = s[3]; + let v1X2; + let v1Y2; + let v1Z2; + let v2X2; + let v2Y2; + let v2Z2; + let v3X1; + let v3Y1; + let v3Z1; + let v4X; + let v4Y; + let v4Z; + let v12X2; + let v12Y2; + let v12Z2; + let v13X; + let v13Y; + let v13Z; + let v14X; + let v14Y; + let v14Z; + let v23X1; + let v23Y1; + let v23Z1; + let v24X; + let v24Y; + let v24Z; + v1X2 = vec11.x; + v1Y2 = vec11.y; + v1Z2 = vec11.z; + v2X2 = vec21.x; + v2Y2 = vec21.y; + v2Z2 = vec21.z; + v3X1 = vec31.x; + v3Y1 = vec31.y; + v3Z1 = vec31.z; + v4X = vec4.x; + v4Y = vec4.y; + v4Z = vec4.z; + v12X2 = v2X2 - v1X2; + v12Y2 = v2Y2 - v1Y2; + v12Z2 = v2Z2 - v1Z2; + v13X = v3X1 - v1X2; + v13Y = v3Y1 - v1Y2; + v13Z = v3Z1 - v1Z2; + v14X = v4X - v1X2; + v14Y = v4Y - v1Y2; + v14Z = v4Z - v1Z2; + v23X1 = v3X1 - v2X2; + v23Y1 = v3Y1 - v2Y2; + v23Z1 = v3Z1 - v2Z2; + v24X = v4X - v2X2; + v24Y = v4Y - v2Y2; + v24Z = v4Z - v2Z2; + let n123X; + let n123Y; + let n123Z; + let n134X; + let n134Y; + let n134Z; + let n142X; + let n142Y; + let n142Z; + let n243X; + let n243Y; + let n243Z; + n123X = v12Y2 * v13Z - v12Z2 * v13Y; + n123Y = v12Z2 * v13X - v12X2 * v13Z; + n123Z = v12X2 * v13Y - v12Y2 * v13X; + n134X = v13Y * v14Z - v13Z * v14Y; + n134Y = v13Z * v14X - v13X * v14Z; + n134Z = v13X * v14Y - v13Y * v14X; + n142X = v14Y * v12Z2 - v14Z * v12Y2; + n142Y = v14Z * v12X2 - v14X * v12Z2; + n142Z = v14X * v12Y2 - v14Y * v12X2; + n243X = v24Y * v23Z1 - v24Z * v23Y1; + n243Y = v24Z * v23X1 - v24X * v23Z1; + n243Z = v24X * v23Y1 - v24Y * v23X1; + let sign = v12X2 * n243X + v12Y2 * n243Y + v12Z2 * n243Z > 0 ? 1 : -1; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if((v1X2 * n123X + v1Y2 * n123Y + v1Z2 * n123Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + v3X = vec31.x; + v3Y = vec31.y; + v3Z = vec31.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + mini1 = b; + mind1 = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + if((v1X2 * n134X + v1Y2 * n134Y + v1Z2 * n134Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec31.x; + v1Y = vec31.y; + v1Z = vec31.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 6) << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if((v1X2 * n142X + v1Y2 * n142Y + v1Z2 * n142Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec21.x; + v2Y = vec21.y; + v2Z = vec21.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec11.x; + v1Y = vec11.y; + v1Z = vec11.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 3 | (b & 4) << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if((v2X2 * n243X + v2Y2 * n243Y + v2Z2 * n243Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec31.x; + v2Y = vec31.y; + v2Z = vec31.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + mini = b; + mind = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec31.x; + v1Y = vec31.y; + v1Z = vec31.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec21.x; + v1Y = vec21.y; + v1Z = vec21.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + closest.x = v1X; + closest.y = v1Y; + closest.z = v1Z; + b = 1; + } else if(t > 1) { + closest.x = v2X; + closest.y = v2Y; + closest.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + closest.x = pX; + closest.y = pY; + closest.z = pZ; + b = 3; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = closest.x; + minvY = closest.y; + minvZ = closest.z; + } + } + let b; + if(mind > 0) { + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = mini; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + closest.x = minvX; + closest.y = minvY; + closest.z = minvZ; + b = 7; + } + let d = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = closest.x; + minvY1 = closest.y; + minvZ1 = closest.z; + } + } + if(mind1 > 0) { + closest.x = minvX1; + closest.y = minvY1; + closest.z = minvZ1; + v = mini1; + } else { + closest.zero(); + v = 15; + } + break; + } + this.shrinkSimplex(v); + if(closest.x * closest.x + closest.y * closest.y + closest.z * closest.z < 1e-008) { + if(lambda == 0 || this.simplexSize == 4) { + hit.fraction = lambda; + return false; + } + this.interpolateClosestPoints(); + hit.fraction = lambda; + let _this = hit.normal; + _this.x = dir.x; + _this.y = dir.y; + _this.z = dir.z; + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + let _this1 = hit.position; + let v = this.closestPoint1; + _this1.x = v.x; + _this1.y = v.y; + _this1.z = v.z; + _this1.x += tl1.x * lambda; + _this1.y += tl1.y * lambda; + _this1.z += tl1.z * lambda; + return true; + } + dir.x = closest.x; + dir.y = closest.y; + dir.z = closest.z; + dir.x = -dir.x; + dir.y = -dir.y; + dir.z = -dir.z; + if(this.c1 != null) { + this.computeWitnessPoint1(true); + } else { + let v = this.w1[this.simplexSize]; + v.x = this.tf1._positionX; + v.y = this.tf1._positionY; + v.z = this.tf1._positionZ; + } + this.computeWitnessPoint2(true); + let _this = this.s[this.simplexSize]; + let v4 = this.w1[this.simplexSize]; + _this.x = v4.x; + _this.y = v4.y; + _this.z = v4.z; + let v5 = this.w2[this.simplexSize]; + _this.x -= v5.x; + _this.y -= v5.y; + _this.z -= v5.z; + let _this1 = s[this.simplexSize]; + _this1.x -= rayX.x; + _this1.y -= rayX.y; + _this1.z -= rayX.z; + if(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z < 1e-008) { + throw new Error("!?"); + } + let p = s[this.simplexSize]; + let pn = p.x * dir.x + p.y * dir.y + p.z * dir.z; + if(pn < 0) { + if(rayR.x * dir.x + rayR.y * dir.y + rayR.z * dir.z >= 0) { + return false; + } + let dLambda = pn / (rayR.x * dir.x + rayR.y * dir.y + rayR.z * dir.z); + lambda += dLambda; + if(lambda >= 1) { + return false; + } + rayX.x += rayR.x * dLambda; + rayX.y += rayR.y * dLambda; + rayX.z += rayR.z * dLambda; + let _g = 0; + let _g1 = this.simplexSize + 1; + while(_g < _g1) { + let _this = s[_g++]; + let s1 = -dLambda; + _this.x += rayR.x * s1; + _this.y += rayR.y * s1; + _this.z += rayR.z * s1; + } + } + let duplicate = false; + let _g = 0; + let _g1 = this.simplexSize; + while(_g < _g1) { + let i = _g++; + let dx = s[i].x - s[this.simplexSize].x; + let dy = s[i].y - s[this.simplexSize].y; + let dz = s[i].z - s[this.simplexSize].z; + if(dx * dx + dy * dy + dz * dz < 1e-008) { + duplicate = true; + break; + } + } + if(!duplicate) { + this.simplexSize++; + } + ++count; + } + return false; + } + interpolateClosestPoints() { + switch(this.simplexSize) { + case 1: + let _this = this.closestPoint1; + let v = this.w1[0]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let _this1 = this.closestPoint2; + let v1 = this.w2[0]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + break; + case 2: + let cX; + let cY; + let cZ; + let v2 = this.closest; + cX = v2.x; + cY = v2.y; + cZ = v2.z; + let s0X; + let s0Y; + let s0Z; + let w10X; + let w10Y; + let w10Z; + let w20X; + let w20Y; + let w20Z; + let s1X; + let s1Y; + let s1Z; + let w11X; + let w11Y; + let w11Z; + let w21X; + let w21Y; + let w21Z; + let v3 = this.s[0]; + s0X = v3.x; + s0Y = v3.y; + s0Z = v3.z; + let v4 = this.w1[0]; + w10X = v4.x; + w10Y = v4.y; + w10Z = v4.z; + let v5 = this.w2[0]; + w20X = v5.x; + w20Y = v5.y; + w20Z = v5.z; + let v6 = this.s[1]; + s1X = v6.x; + s1Y = v6.y; + s1Z = v6.z; + let v7 = this.w1[1]; + w11X = v7.x; + w11Y = v7.y; + w11Z = v7.z; + let v8 = this.w2[1]; + w21X = v8.x; + w21Y = v8.y; + w21Z = v8.z; + let s01X; + let s01Y; + let s01Z; + s01X = s1X - s0X; + s01Y = s1Y - s0Y; + s01Z = s1Z - s0Z; + let invDet = s01X * s01X + s01Y * s01Y + s01Z * s01Z; + if(invDet != 0) { + invDet = 1 / invDet; + } + let s0cX; + let s0cY; + let s0cZ; + s0cX = cX - s0X; + s0cY = cY - s0Y; + s0cZ = cZ - s0Z; + let t = (s0cX * s01X + s0cY * s01Y + s0cZ * s01Z) * invDet; + let diffX; + let diffY; + let diffZ; + let cp1X; + let cp1Y; + let cp1Z; + let cp2X; + let cp2Y; + let cp2Z; + diffX = w11X - w10X; + diffY = w11Y - w10Y; + diffZ = w11Z - w10Z; + cp1X = w10X + diffX * t; + cp1Y = w10Y + diffY * t; + cp1Z = w10Z + diffZ * t; + diffX = w21X - w20X; + diffY = w21Y - w20Y; + diffZ = w21Z - w20Z; + cp2X = w20X + diffX * t; + cp2Y = w20Y + diffY * t; + cp2Z = w20Z + diffZ * t; + let v9 = this.closestPoint1; + v9.x = cp1X; + v9.y = cp1Y; + v9.z = cp1Z; + let v10 = this.closestPoint2; + v10.x = cp2X; + v10.y = cp2Y; + v10.z = cp2Z; + break; + case 3: + let cX1; + let cY1; + let cZ1; + let v11 = this.closest; + cX1 = v11.x; + cY1 = v11.y; + cZ1 = v11.z; + let s0X1; + let s0Y1; + let s0Z1; + let w10X1; + let w10Y1; + let w10Z1; + let w20X1; + let w20Y1; + let w20Z1; + let s1X1; + let s1Y1; + let s1Z1; + let w11X1; + let w11Y1; + let w11Z1; + let w21X1; + let w21Y1; + let w21Z1; + let s2X; + let s2Y; + let s2Z; + let w12X; + let w12Y; + let w12Z; + let w22X; + let w22Y; + let w22Z; + let v12 = this.s[0]; + s0X1 = v12.x; + s0Y1 = v12.y; + s0Z1 = v12.z; + let v13 = this.w1[0]; + w10X1 = v13.x; + w10Y1 = v13.y; + w10Z1 = v13.z; + let v14 = this.w2[0]; + w20X1 = v14.x; + w20Y1 = v14.y; + w20Z1 = v14.z; + let v15 = this.s[1]; + s1X1 = v15.x; + s1Y1 = v15.y; + s1Z1 = v15.z; + let v16 = this.w1[1]; + w11X1 = v16.x; + w11Y1 = v16.y; + w11Z1 = v16.z; + let v17 = this.w2[1]; + w21X1 = v17.x; + w21Y1 = v17.y; + w21Z1 = v17.z; + let v18 = this.s[2]; + s2X = v18.x; + s2Y = v18.y; + s2Z = v18.z; + let v19 = this.w1[2]; + w12X = v19.x; + w12Y = v19.y; + w12Z = v19.z; + let v20 = this.w2[2]; + w22X = v20.x; + w22Y = v20.y; + w22Z = v20.z; + let s01X1; + let s01Y1; + let s01Z1; + let s02X; + let s02Y; + let s02Z; + let s0cX1; + let s0cY1; + let s0cZ1; + s01X1 = s1X1 - s0X1; + s01Y1 = s1Y1 - s0Y1; + s01Z1 = s1Z1 - s0Z1; + s02X = s2X - s0X1; + s02Y = s2Y - s0Y1; + s02Z = s2Z - s0Z1; + s0cX1 = cX1 - s0X1; + s0cY1 = cY1 - s0Y1; + s0cZ1 = cZ1 - s0Z1; + let d11 = s01X1 * s01X1 + s01Y1 * s01Y1 + s01Z1 * s01Z1; + let d12 = s01X1 * s02X + s01Y1 * s02Y + s01Z1 * s02Z; + let d22 = s02X * s02X + s02Y * s02Y + s02Z * s02Z; + let d1c = s01X1 * s0cX1 + s01Y1 * s0cY1 + s01Z1 * s0cZ1; + let d2c = s02X * s0cX1 + s02Y * s0cY1 + s02Z * s0cZ1; + let invDet1 = d11 * d22 - d12 * d12; + if(invDet1 != 0) { + invDet1 = 1 / invDet1; + } + let s = (d1c * d22 - d2c * d12) * invDet1; + let t1 = (-d1c * d12 + d2c * d11) * invDet1; + let diffX1; + let diffY1; + let diffZ1; + let cp1X1; + let cp1Y1; + let cp1Z1; + let cp2X1; + let cp2Y1; + let cp2Z1; + diffX1 = w11X1 - w10X1; + diffY1 = w11Y1 - w10Y1; + diffZ1 = w11Z1 - w10Z1; + cp1X1 = w10X1 + diffX1 * s; + cp1Y1 = w10Y1 + diffY1 * s; + cp1Z1 = w10Z1 + diffZ1 * s; + diffX1 = w12X - w10X1; + diffY1 = w12Y - w10Y1; + diffZ1 = w12Z - w10Z1; + cp1X1 += diffX1 * t1; + cp1Y1 += diffY1 * t1; + cp1Z1 += diffZ1 * t1; + diffX1 = w21X1 - w20X1; + diffY1 = w21Y1 - w20Y1; + diffZ1 = w21Z1 - w20Z1; + cp2X1 = w20X1 + diffX1 * s; + cp2Y1 = w20Y1 + diffY1 * s; + cp2Z1 = w20Z1 + diffZ1 * s; + diffX1 = w22X - w20X1; + diffY1 = w22Y - w20Y1; + diffZ1 = w22Z - w20Z1; + cp2X1 += diffX1 * t1; + cp2Y1 += diffY1 * t1; + cp2Z1 += diffZ1 * t1; + let v21 = this.closestPoint1; + v21.x = cp1X1; + v21.y = cp1Y1; + v21.z = cp1Z1; + let v22 = this.closestPoint2; + v22.x = cp2X1; + v22.y = cp2Y1; + v22.z = cp2Z1; + break; + default: + throw new Error("!?"); + } + } + loadCache(gjkCache) { + let _this = this.dir; + let v = gjkCache.prevClosestDir; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + } + saveCache(gjkCache) { + let _this = gjkCache.prevClosestDir; + let v = this.closest; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + _this.x = -_this.x; + _this.y = -_this.y; + _this.z = -_this.z; + } + shrinkSimplex(vertexBits) { + this.simplexSize = vertexBits; + this.simplexSize = (this.simplexSize & 5) + (this.simplexSize >> 1 & 5); + this.simplexSize = (this.simplexSize & 3) + (this.simplexSize >> 2 & 3); + switch(vertexBits) { + case 2: + let _this = this.s[0]; + let v = this.s[1]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let _this1 = this.w1[0]; + let v1 = this.w1[1]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + let _this2 = this.w2[0]; + let v2 = this.w2[1]; + _this2.x = v2.x; + _this2.y = v2.y; + _this2.z = v2.z; + break; + case 4: + let _this3 = this.s[0]; + let v3 = this.s[2]; + _this3.x = v3.x; + _this3.y = v3.y; + _this3.z = v3.z; + let _this4 = this.w1[0]; + let v4 = this.w1[2]; + _this4.x = v4.x; + _this4.y = v4.y; + _this4.z = v4.z; + let _this5 = this.w2[0]; + let v5 = this.w2[2]; + _this5.x = v5.x; + _this5.y = v5.y; + _this5.z = v5.z; + break; + case 5: + let _this6 = this.s[1]; + let v6 = this.s[2]; + _this6.x = v6.x; + _this6.y = v6.y; + _this6.z = v6.z; + let _this7 = this.w1[1]; + let v7 = this.w1[2]; + _this7.x = v7.x; + _this7.y = v7.y; + _this7.z = v7.z; + let _this8 = this.w2[1]; + let v8 = this.w2[2]; + _this8.x = v8.x; + _this8.y = v8.y; + _this8.z = v8.z; + break; + case 6: + let _this9 = this.s[0]; + let v9 = this.s[2]; + _this9.x = v9.x; + _this9.y = v9.y; + _this9.z = v9.z; + let _this10 = this.w1[0]; + let v10 = this.w1[2]; + _this10.x = v10.x; + _this10.y = v10.y; + _this10.z = v10.z; + let _this11 = this.w2[0]; + let v11 = this.w2[2]; + _this11.x = v11.x; + _this11.y = v11.y; + _this11.z = v11.z; + break; + case 8: + let _this12 = this.s[0]; + let v12 = this.s[3]; + _this12.x = v12.x; + _this12.y = v12.y; + _this12.z = v12.z; + let _this13 = this.w1[0]; + let v13 = this.w1[3]; + _this13.x = v13.x; + _this13.y = v13.y; + _this13.z = v13.z; + let _this14 = this.w2[0]; + let v14 = this.w2[3]; + _this14.x = v14.x; + _this14.y = v14.y; + _this14.z = v14.z; + break; + case 9: + let _this15 = this.s[1]; + let v15 = this.s[3]; + _this15.x = v15.x; + _this15.y = v15.y; + _this15.z = v15.z; + let _this16 = this.w1[1]; + let v16 = this.w1[3]; + _this16.x = v16.x; + _this16.y = v16.y; + _this16.z = v16.z; + let _this17 = this.w2[1]; + let v17 = this.w2[3]; + _this17.x = v17.x; + _this17.y = v17.y; + _this17.z = v17.z; + break; + case 10: + let _this18 = this.s[0]; + let v18 = this.s[3]; + _this18.x = v18.x; + _this18.y = v18.y; + _this18.z = v18.z; + let _this19 = this.w1[0]; + let v19 = this.w1[3]; + _this19.x = v19.x; + _this19.y = v19.y; + _this19.z = v19.z; + let _this20 = this.w2[0]; + let v20 = this.w2[3]; + _this20.x = v20.x; + _this20.y = v20.y; + _this20.z = v20.z; + break; + case 11: + let _this21 = this.s[2]; + let v21 = this.s[3]; + _this21.x = v21.x; + _this21.y = v21.y; + _this21.z = v21.z; + let _this22 = this.w1[2]; + let v22 = this.w1[3]; + _this22.x = v22.x; + _this22.y = v22.y; + _this22.z = v22.z; + let _this23 = this.w2[2]; + let v23 = this.w2[3]; + _this23.x = v23.x; + _this23.y = v23.y; + _this23.z = v23.z; + break; + case 12: + let _this24 = this.s[0]; + let v24 = this.s[2]; + _this24.x = v24.x; + _this24.y = v24.y; + _this24.z = v24.z; + let _this25 = this.w1[0]; + let v25 = this.w1[2]; + _this25.x = v25.x; + _this25.y = v25.y; + _this25.z = v25.z; + let _this26 = this.w2[0]; + let v26 = this.w2[2]; + _this26.x = v26.x; + _this26.y = v26.y; + _this26.z = v26.z; + let _this27 = this.s[1]; + let v27 = this.s[3]; + _this27.x = v27.x; + _this27.y = v27.y; + _this27.z = v27.z; + let _this28 = this.w1[1]; + let v28 = this.w1[3]; + _this28.x = v28.x; + _this28.y = v28.y; + _this28.z = v28.z; + let _this29 = this.w2[1]; + let v29 = this.w2[3]; + _this29.x = v29.x; + _this29.y = v29.y; + _this29.z = v29.z; + break; + case 13: + let _this30 = this.s[1]; + let v30 = this.s[3]; + _this30.x = v30.x; + _this30.y = v30.y; + _this30.z = v30.z; + let _this31 = this.w1[1]; + let v31 = this.w1[3]; + _this31.x = v31.x; + _this31.y = v31.y; + _this31.z = v31.z; + let _this32 = this.w2[1]; + let v32 = this.w2[3]; + _this32.x = v32.x; + _this32.y = v32.y; + _this32.z = v32.z; + break; + case 14: + let _this33 = this.s[0]; + let v33 = this.s[3]; + _this33.x = v33.x; + _this33.y = v33.y; + _this33.z = v33.z; + let _this34 = this.w1[0]; + let v34 = this.w1[3]; + _this34.x = v34.x; + _this34.y = v34.y; + _this34.z = v34.z; + let _this35 = this.w2[0]; + let v35 = this.w2[3]; + _this35.x = v35.x; + _this35.y = v35.y; + _this35.z = v35.z; + break; + } + } + computeWitnessPoint1(addMargin) { + let tmpX; + let tmpY; + let tmpZ; + let idirX; + let idirY; + let idirZ; + let v = this.dir; + idirX = v.x; + idirY = v.y; + idirZ = v.z; + let ldir1X; + let ldir1Y; + let ldir1Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this.tf1._rotation00 * idirX + this.tf1._rotation10 * idirY + this.tf1._rotation20 * idirZ; + __tmp__Y = this.tf1._rotation01 * idirX + this.tf1._rotation11 * idirY + this.tf1._rotation21 * idirZ; + __tmp__Z = this.tf1._rotation02 * idirX + this.tf1._rotation12 * idirY + this.tf1._rotation22 * idirZ; + ldir1X = __tmp__X; + ldir1Y = __tmp__Y; + ldir1Z = __tmp__Z; + let iw1X; + let iw1Y; + let iw1Z; + let v1 = this.dir; + v1.x = ldir1X; + v1.y = ldir1Y; + v1.z = ldir1Z; + this.c1.computeLocalSupportingVertex(this.dir,this.w1[this.simplexSize]); + if(addMargin) { + let _this = this.dir; + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + let _this1 = this.w1[this.simplexSize]; + let v = this.dir; + let s = this.c1._gjkMargin; + _this1.x += v.x * s; + _this1.y += v.y * s; + _this1.z += v.z * s; + } + let v2 = this.w1[this.simplexSize]; + tmpX = v2.x; + tmpY = v2.y; + tmpZ = v2.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = this.tf1._rotation00 * tmpX + this.tf1._rotation01 * tmpY + this.tf1._rotation02 * tmpZ; + __tmp__Y1 = this.tf1._rotation10 * tmpX + this.tf1._rotation11 * tmpY + this.tf1._rotation12 * tmpZ; + __tmp__Z1 = this.tf1._rotation20 * tmpX + this.tf1._rotation21 * tmpY + this.tf1._rotation22 * tmpZ; + iw1X = __tmp__X1; + iw1Y = __tmp__Y1; + iw1Z = __tmp__Z1; + iw1X += this.tf1._positionX; + iw1Y += this.tf1._positionY; + iw1Z += this.tf1._positionZ; + let v3 = this.w1[this.simplexSize]; + v3.x = iw1X; + v3.y = iw1Y; + v3.z = iw1Z; + let v4 = this.dir; + v4.x = idirX; + v4.y = idirY; + v4.z = idirZ; + } + computeWitnessPoint2(addMargin) { + let tmpX; + let tmpY; + let tmpZ; + let idirX; + let idirY; + let idirZ; + let v = this.dir; + idirX = v.x; + idirY = v.y; + idirZ = v.z; + let ldir2X; + let ldir2Y; + let ldir2Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this.tf2._rotation00 * idirX + this.tf2._rotation10 * idirY + this.tf2._rotation20 * idirZ; + __tmp__Y = this.tf2._rotation01 * idirX + this.tf2._rotation11 * idirY + this.tf2._rotation21 * idirZ; + __tmp__Z = this.tf2._rotation02 * idirX + this.tf2._rotation12 * idirY + this.tf2._rotation22 * idirZ; + ldir2X = __tmp__X; + ldir2Y = __tmp__Y; + ldir2Z = __tmp__Z; + ldir2X = -ldir2X; + ldir2Y = -ldir2Y; + ldir2Z = -ldir2Z; + let iw2X; + let iw2Y; + let iw2Z; + let v1 = this.dir; + v1.x = ldir2X; + v1.y = ldir2Y; + v1.z = ldir2Z; + this.c2.computeLocalSupportingVertex(this.dir,this.w2[this.simplexSize]); + if(addMargin) { + let _this = this.dir; + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + let _this1 = this.w2[this.simplexSize]; + let v = this.dir; + let s = this.c2._gjkMargin; + _this1.x += v.x * s; + _this1.y += v.y * s; + _this1.z += v.z * s; + } + let v2 = this.w2[this.simplexSize]; + tmpX = v2.x; + tmpY = v2.y; + tmpZ = v2.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = this.tf2._rotation00 * tmpX + this.tf2._rotation01 * tmpY + this.tf2._rotation02 * tmpZ; + __tmp__Y1 = this.tf2._rotation10 * tmpX + this.tf2._rotation11 * tmpY + this.tf2._rotation12 * tmpZ; + __tmp__Z1 = this.tf2._rotation20 * tmpX + this.tf2._rotation21 * tmpY + this.tf2._rotation22 * tmpZ; + iw2X = __tmp__X1; + iw2Y = __tmp__Y1; + iw2Z = __tmp__Z1; + iw2X += this.tf2._positionX; + iw2Y += this.tf2._positionY; + iw2Z += this.tf2._positionZ; + let v3 = this.w2[this.simplexSize]; + v3.x = iw2X; + v3.y = iw2Y; + v3.z = iw2Z; + let v4 = this.dir; + v4.x = idirX; + v4.y = idirY; + v4.z = idirZ; + } + pointToTetrahedron() { + let _g = 0; + while(_g < 3) { + let _this = this.dir; + let v = this.baseDirs[_g++]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this1 = this.s[this.simplexSize]; + let v1 = this.w1[this.simplexSize]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + let v2 = this.w2[this.simplexSize]; + _this1.x -= v2.x; + _this1.y -= v2.y; + _this1.z -= v2.z; + this.simplexSize++; + this.lineToTetrahedron(); + if(this.simplexSize == 4) { + break; + } + this.simplexSize--; + let _this2 = this.dir; + _this2.x = -_this2.x; + _this2.y = -_this2.y; + _this2.z = -_this2.z; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this3 = this.s[this.simplexSize]; + let v3 = this.w1[this.simplexSize]; + _this3.x = v3.x; + _this3.y = v3.y; + _this3.z = v3.z; + let v4 = this.w2[this.simplexSize]; + _this3.x -= v4.x; + _this3.y -= v4.y; + _this3.z -= v4.z; + this.simplexSize++; + this.lineToTetrahedron(); + if(this.simplexSize == 4) { + break; + } + this.simplexSize--; + } + } + lineToTetrahedron() { + let oldDirX; + let oldDirY; + let oldDirZ; + let v = this.dir; + oldDirX = v.x; + oldDirY = v.y; + oldDirZ = v.z; + let s0X; + let s0Y; + let s0Z; + let s1X; + let s1Y; + let s1Z; + let lineDirX; + let lineDirY; + let lineDirZ; + let v1 = this.s[0]; + s0X = v1.x; + s0Y = v1.y; + s0Z = v1.z; + let v2 = this.s[1]; + s1X = v2.x; + s1Y = v2.y; + s1Z = v2.z; + lineDirX = s0X - s1X; + lineDirY = s0Y - s1Y; + lineDirZ = s0Z - s1Z; + let _g = 0; + while(_g < 3) { + let baseDirX; + let baseDirY; + let baseDirZ; + let v = this.baseDirs[_g++]; + baseDirX = v.x; + baseDirY = v.y; + baseDirZ = v.z; + let newDirX; + let newDirY; + let newDirZ; + newDirX = lineDirY * baseDirZ - lineDirZ * baseDirY; + newDirY = lineDirZ * baseDirX - lineDirX * baseDirZ; + newDirZ = lineDirX * baseDirY - lineDirY * baseDirX; + let v1 = this.dir; + v1.x = newDirX; + v1.y = newDirY; + v1.z = newDirZ; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this = this.s[this.simplexSize]; + let v2 = this.w1[this.simplexSize]; + _this.x = v2.x; + _this.y = v2.y; + _this.z = v2.z; + let v3 = this.w2[this.simplexSize]; + _this.x -= v3.x; + _this.y -= v3.y; + _this.z -= v3.z; + this.simplexSize++; + this.triangleToTetrahedron(); + if(this.simplexSize == 4) { + break; + } + this.simplexSize--; + let _this1 = this.dir; + _this1.x = -_this1.x; + _this1.y = -_this1.y; + _this1.z = -_this1.z; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this2 = this.s[this.simplexSize]; + let v4 = this.w1[this.simplexSize]; + _this2.x = v4.x; + _this2.y = v4.y; + _this2.z = v4.z; + let v5 = this.w2[this.simplexSize]; + _this2.x -= v5.x; + _this2.y -= v5.y; + _this2.z -= v5.z; + this.simplexSize++; + this.triangleToTetrahedron(); + if(this.simplexSize == 4) { + break; + } + this.simplexSize--; + } + let v3 = this.dir; + v3.x = oldDirX; + v3.y = oldDirY; + v3.z = oldDirZ; + } + triangleToTetrahedron() { + let oldDirX; + let oldDirY; + let oldDirZ; + let v = this.dir; + oldDirX = v.x; + oldDirY = v.y; + oldDirZ = v.z; + while(true) { + let s0X; + let s0Y; + let s0Z; + let s1X; + let s1Y; + let s1Z; + let s2X; + let s2Y; + let s2Z; + let s01X; + let s01Y; + let s01Z; + let s02X; + let s02Y; + let s02Z; + let v = this.s[0]; + s0X = v.x; + s0Y = v.y; + s0Z = v.z; + let v1 = this.s[1]; + s1X = v1.x; + s1Y = v1.y; + s1Z = v1.z; + let v2 = this.s[2]; + s2X = v2.x; + s2Y = v2.y; + s2Z = v2.z; + s01X = s1X - s0X; + s01Y = s1Y - s0Y; + s01Z = s1Z - s0Z; + s02X = s2X - s0X; + s02Y = s2Y - s0Y; + s02Z = s2Z - s0Z; + let nX; + let nY; + let nZ; + nX = s01Y * s02Z - s01Z * s02Y; + nY = s01Z * s02X - s01X * s02Z; + nZ = s01X * s02Y - s01Y * s02X; + let v3 = this.dir; + v3.x = nX; + v3.y = nY; + v3.z = nZ; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this = this.s[this.simplexSize]; + let v4 = this.w1[this.simplexSize]; + _this.x = v4.x; + _this.y = v4.y; + _this.z = v4.z; + let v5 = this.w2[this.simplexSize]; + _this.x -= v5.x; + _this.y -= v5.y; + _this.z -= v5.z; + this.simplexSize++; + if(this.isValidTetrahedron()) { + break; + } + this.simplexSize--; + let _this1 = this.dir; + _this1.x = -_this1.x; + _this1.y = -_this1.y; + _this1.z = -_this1.z; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this2 = this.s[this.simplexSize]; + let v6 = this.w1[this.simplexSize]; + _this2.x = v6.x; + _this2.y = v6.y; + _this2.z = v6.z; + let v7 = this.w2[this.simplexSize]; + _this2.x -= v7.x; + _this2.y -= v7.y; + _this2.z -= v7.z; + this.simplexSize++; + if(this.isValidTetrahedron()) { + break; + } + this.simplexSize--; + break; + } + let v1 = this.dir; + v1.x = oldDirX; + v1.y = oldDirY; + v1.z = oldDirZ; + } + isValidTetrahedron() { + let e10 = this.s[2].x - this.s[0].x; + let e11 = this.s[2].y - this.s[0].y; + let e12 = this.s[2].z - this.s[0].z; + let e20 = this.s[3].x - this.s[0].x; + let e21 = this.s[3].y - this.s[0].y; + let e22 = this.s[3].z - this.s[0].z; + let det = (this.s[1].x - this.s[0].x) * (e11 * e22 - e12 * e21) - (this.s[1].y - this.s[0].y) * (e10 * e22 - e12 * e20) + (this.s[1].z - this.s[0].z) * (e10 * e21 - e11 * e20); + if(!(det > 1e-12)) { + return det < -1e-12; + } else { + return true; + } + } + computeDepth(convex1,convex2,tf1,tf2,initialPolyhedron,initialPolyhedron1,initialPolyhedron2) { + let _this = this.polyhedron; + while(_this._numTriangles > 0) { + let t = _this._triangleList; + _this._numTriangles--; + let prev = t._prev; + let next = t._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(t == _this._triangleList) { + _this._triangleList = _this._triangleList._next; + } + if(t == _this._triangleListLast) { + _this._triangleListLast = _this._triangleListLast._prev; + } + t._next = null; + t._prev = null; + t.removeReferences(); + t._next = _this._trianglePool; + _this._trianglePool = t; + } + while(_this._numVertices > 0) { + let v = _this._vertices[--_this._numVertices]; + v.removeReferences(); + v._next = _this._vertexPool; + _this._vertexPool = v; + } + let tmp = this.polyhedron; + let _this1 = this.polyhedron; + let first = _this1._vertexPool; + if(first != null) { + _this1._vertexPool = first._next; + first._next = null; + } else { + first = new oimo.collision.narrowphase.detector.gjkepa.EpaVertex(); + } + let tmp1 = first.init(initialPolyhedron[0],initialPolyhedron1[0],initialPolyhedron2[0]); + let _this2 = this.polyhedron; + let first1 = _this2._vertexPool; + if(first1 != null) { + _this2._vertexPool = first1._next; + first1._next = null; + } else { + first1 = new oimo.collision.narrowphase.detector.gjkepa.EpaVertex(); + } + let tmp2 = first1.init(initialPolyhedron[1],initialPolyhedron1[1],initialPolyhedron2[1]); + let _this3 = this.polyhedron; + let first2 = _this3._vertexPool; + if(first2 != null) { + _this3._vertexPool = first2._next; + first2._next = null; + } else { + first2 = new oimo.collision.narrowphase.detector.gjkepa.EpaVertex(); + } + let tmp3 = first2.init(initialPolyhedron[2],initialPolyhedron1[2],initialPolyhedron2[2]); + let _this4 = this.polyhedron; + let first3 = _this4._vertexPool; + if(first3 != null) { + _this4._vertexPool = first3._next; + first3._next = null; + } else { + first3 = new oimo.collision.narrowphase.detector.gjkepa.EpaVertex(); + } + if(!tmp._init(tmp1,tmp2,tmp3,first3.init(initialPolyhedron[3],initialPolyhedron1[3],initialPolyhedron2[3]))) { + return oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_FAILED_TO_INIT; + } + this.simplexSize = 0; + let supportingVertex = this.s[0]; + let witness1 = this.w1[0]; + let witness2 = this.w2[0]; + let count = 0; + while(count < 40) { + let f = this.polyhedron._triangleList; + let mind = 1e65536; + let minf = null; + while(f != null) { + if(f._distanceSq < mind) { + mind = f._distanceSq; + minf = f; + } + f = f._next; + } + let face = minf; + let _this = this.dir; + let v = face._normal; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + this.computeWitnessPoint1(false); + this.computeWitnessPoint2(false); + let _this1 = this.s[this.simplexSize]; + let v1 = this.w1[this.simplexSize]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + let v2 = this.w2[this.simplexSize]; + _this1.x -= v2.x; + _this1.y -= v2.y; + _this1.z -= v2.z; + let v0 = face._vertices[0]; + let v11 = face._vertices[1]; + let v21 = face._vertices[2]; + let _this2 = v0.v; + let v3 = this.dir; + let v4 = this.dir; + if(supportingVertex.x * v4.x + supportingVertex.y * v4.y + supportingVertex.z * v4.z - (_this2.x * v3.x + _this2.y * v3.y + _this2.z * v3.z) < 1e-6 || count == 39) { + let _this = this.closest; + let v = this.dir; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let _this1 = this.dir; + let v1 = v0.v; + let _this2 = this.dir; + let s = (_this1.x * v1.x + _this1.y * v1.y + _this1.z * v1.z) / (_this2.x * _this2.x + _this2.y * _this2.y + _this2.z * _this2.z); + _this.x *= s; + _this.y *= s; + _this.z *= s; + let cX; + let cY; + let cZ; + let v2 = this.closest; + cX = v2.x; + cY = v2.y; + cZ = v2.z; + let s0X; + let s0Y; + let s0Z; + let w10X; + let w10Y; + let w10Z; + let w20X; + let w20Y; + let w20Z; + let s1X; + let s1Y; + let s1Z; + let w11X; + let w11Y; + let w11Z; + let w21X; + let w21Y; + let w21Z; + let s2X; + let s2Y; + let s2Z; + let w12X; + let w12Y; + let w12Z; + let w22X; + let w22Y; + let w22Z; + let v3 = v0.v; + s0X = v3.x; + s0Y = v3.y; + s0Z = v3.z; + let v4 = v0.w1; + w10X = v4.x; + w10Y = v4.y; + w10Z = v4.z; + let v5 = v0.w2; + w20X = v5.x; + w20Y = v5.y; + w20Z = v5.z; + let v6 = v11.v; + s1X = v6.x; + s1Y = v6.y; + s1Z = v6.z; + let v7 = v11.w1; + w11X = v7.x; + w11Y = v7.y; + w11Z = v7.z; + let v8 = v11.w2; + w21X = v8.x; + w21Y = v8.y; + w21Z = v8.z; + let v9 = v21.v; + s2X = v9.x; + s2Y = v9.y; + s2Z = v9.z; + let v10 = v21.w1; + w12X = v10.x; + w12Y = v10.y; + w12Z = v10.z; + let v12 = v21.w2; + w22X = v12.x; + w22Y = v12.y; + w22Z = v12.z; + let s01X; + let s01Y; + let s01Z; + let s02X; + let s02Y; + let s02Z; + let s0cX; + let s0cY; + let s0cZ; + s01X = s1X - s0X; + s01Y = s1Y - s0Y; + s01Z = s1Z - s0Z; + s02X = s2X - s0X; + s02Y = s2Y - s0Y; + s02Z = s2Z - s0Z; + s0cX = cX - s0X; + s0cY = cY - s0Y; + s0cZ = cZ - s0Z; + let d11 = s01X * s01X + s01Y * s01Y + s01Z * s01Z; + let d12 = s01X * s02X + s01Y * s02Y + s01Z * s02Z; + let d22 = s02X * s02X + s02Y * s02Y + s02Z * s02Z; + let d1c = s01X * s0cX + s01Y * s0cY + s01Z * s0cZ; + let d2c = s02X * s0cX + s02Y * s0cY + s02Z * s0cZ; + let invDet = d11 * d22 - d12 * d12; + if(invDet != 0) { + invDet = 1 / invDet; + } + let s1 = (d1c * d22 - d2c * d12) * invDet; + let t = (-d1c * d12 + d2c * d11) * invDet; + let diffX; + let diffY; + let diffZ; + let cp1X; + let cp1Y; + let cp1Z; + let cp2X; + let cp2Y; + let cp2Z; + diffX = w11X - w10X; + diffY = w11Y - w10Y; + diffZ = w11Z - w10Z; + cp1X = w10X + diffX * s1; + cp1Y = w10Y + diffY * s1; + cp1Z = w10Z + diffZ * s1; + diffX = w12X - w10X; + diffY = w12Y - w10Y; + diffZ = w12Z - w10Z; + cp1X += diffX * t; + cp1Y += diffY * t; + cp1Z += diffZ * t; + diffX = w21X - w20X; + diffY = w21Y - w20Y; + diffZ = w21Z - w20Z; + cp2X = w20X + diffX * s1; + cp2Y = w20Y + diffY * s1; + cp2Z = w20Z + diffZ * s1; + diffX = w22X - w20X; + diffY = w22Y - w20Y; + diffZ = w22Z - w20Z; + cp2X += diffX * t; + cp2Y += diffY * t; + cp2Z += diffZ * t; + let v13 = this.closestPoint1; + v13.x = cp1X; + v13.y = cp1Y; + v13.z = cp1Z; + let v14 = this.closestPoint2; + v14.x = cp2X; + v14.y = cp2Y; + v14.z = cp2Z; + let _this3 = this.closest; + this.depth = Math.sqrt(_this3.x * _this3.x + _this3.y * _this3.y + _this3.z * _this3.z); + return oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.SUCCEEDED; + } + let _this3 = this.polyhedron; + let first = _this3._vertexPool; + if(first != null) { + _this3._vertexPool = first._next; + first._next = null; + } else { + first = new oimo.collision.narrowphase.detector.gjkepa.EpaVertex(); + } + let epaVertex = first.init(supportingVertex,witness1,witness2); + if(!this.polyhedron._addVertex(epaVertex,face)) { + return oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_FAILED_TO_ADD_VERTEX; + } + ++count; + } + return oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_DID_NOT_CONVERGE; + } + computeClosestPoints(c1,c2,tf1,tf2,cache) { + return this.computeClosestPointsImpl(c1,c2,tf1,tf2,cache,true); + } + computeDistance(c1,c2,tf1,tf2,cache) { + return this.computeClosestPointsImpl(c1,c2,tf1,tf2,cache,false); + } + convexCast(c1,c2,tf1,tf2,tl1,tl2,hit) { + return this.convexCastImpl(c1,c2,tf1,tf2,tl1,tl2,hit); + } + rayCast(c,tf,begin,end,hit) { + let tf1 = this.tempTransform; + tf1._positionX = begin.x; + tf1._positionY = begin.y; + tf1._positionZ = begin.z; + let tl1 = this.tl1; + let tl2 = this.tl2; + tl1.x = end.x; + tl1.y = end.y; + tl1.z = end.z; + tl1.x -= begin.x; + tl1.y -= begin.y; + tl1.z -= begin.z; + tl2.zero(); + return this.convexCastImpl(null,c,tf1,tf,tl1,tl2,hit); + } + static getInstance() { + return oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance; + } +} +oimo.collision.narrowphase.detector.gjkepa.GjkEpaLog = class oimo_collision_narrowphase_detector_gjkepa_GjkEpaLog { +} +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState = class oimo_collision_narrowphase_detector_gjkepa_GjkEpaResultState { +} +oimo.collision.narrowphase.detector.gjkepa.SimplexUtil = class oimo_collision_narrowphase_detector_gjkepa_SimplexUtil { + static projectOrigin2(vec1,vec2,out) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + return 1; + } + if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + return 2; + } + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + return 3; + } + static projectOrigin3(vec1,vec2,vec3,out) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + v3X = vec3.x; + v3Y = vec3.y; + v3Z = vec3.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + mini = b; + mind = out.x * out.x + out.y * out.y + out.z * out.z; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 2) << 1; + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if(mind > 0) { + out.x = minvX; + out.y = minvY; + out.z = minvZ; + return mini; + } + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX = nX * l2; + minvY = nY * l2; + minvZ = nZ * l2; + out.x = minvX; + out.y = minvY; + out.z = minvZ; + return 7; + } + static projectOrigin4(vec1,vec2,vec3,vec4,out) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v4X; + let v4Y; + let v4Z; + let v12X; + let v12Y; + let v12Z; + let v13X; + let v13Y; + let v13Z; + let v14X; + let v14Y; + let v14Z; + let v23X; + let v23Y; + let v23Z; + let v24X; + let v24Y; + let v24Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + v3X = vec3.x; + v3Y = vec3.y; + v3Z = vec3.z; + v4X = vec4.x; + v4Y = vec4.y; + v4Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v13X = v3X - v1X; + v13Y = v3Y - v1Y; + v13Z = v3Z - v1Z; + v14X = v4X - v1X; + v14Y = v4Y - v1Y; + v14Z = v4Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v24X = v4X - v2X; + v24Y = v4Y - v2Y; + v24Z = v4Z - v2Z; + let n123X; + let n123Y; + let n123Z; + let n134X; + let n134Y; + let n134Z; + let n142X; + let n142Y; + let n142Z; + let n243X; + let n243Y; + let n243Z; + n123X = v12Y * v13Z - v12Z * v13Y; + n123Y = v12Z * v13X - v12X * v13Z; + n123Z = v12X * v13Y - v12Y * v13X; + n134X = v13Y * v14Z - v13Z * v14Y; + n134Y = v13Z * v14X - v13X * v14Z; + n134Z = v13X * v14Y - v13Y * v14X; + n142X = v14Y * v12Z - v14Z * v12Y; + n142Y = v14Z * v12X - v14X * v12Z; + n142Z = v14X * v12Y - v14Y * v12X; + n243X = v24Y * v23Z - v24Z * v23Y; + n243Y = v24Z * v23X - v24X * v23Z; + n243Z = v24X * v23Y - v24Y * v23X; + let sign = v12X * n243X + v12Y * n243Y + v12Z * n243Z > 0 ? 1 : -1; + let mind = -1; + let minvX; + let minvY; + let minvZ; + let mini = 0; + minvX = 0; + minvY = 0; + minvZ = 0; + if((v1X * n123X + v1Y * n123Y + v1Z * n123Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + v3X = vec3.x; + v3Y = vec3.y; + v3Z = vec3.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + mini1 = b; + mind1 = out.x * out.x + out.y * out.y + out.z * out.z; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 2) << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + let b; + if(mind1 > 0) { + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = mini1; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX1 = nX * l2; + minvY1 = nY * l2; + minvZ1 = nZ * l2; + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = 7; + } + mini = b; + mind = out.x * out.x + out.y * out.y + out.z * out.z; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + if((v1X * n134X + v1Y * n134Y + v1Z * n134Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + mini1 = b; + mind1 = out.x * out.x + out.y * out.y + out.z * out.z; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec3.x; + v1Y = vec3.y; + v1Z = vec3.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 2) << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + let b; + if(mind1 > 0) { + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = mini1; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX1 = nX * l2; + minvY1 = nY * l2; + minvZ1 = nZ * l2; + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = 7; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mini = b & 1 | (b & 6) << 1; + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if((v1X * n142X + v1Y * n142Y + v1Z * n142Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec2.x; + v2Y = vec2.y; + v2Z = vec2.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + mini1 = b; + mind1 = out.x * out.x + out.y * out.y + out.z * out.z; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec1.x; + v1Y = vec1.y; + v1Z = vec1.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 2) << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + let b; + if(mind1 > 0) { + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = mini1; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX1 = nX * l2; + minvY1 = nY * l2; + minvZ1 = nZ * l2; + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = 7; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mini = b & 3 | (b & 4) << 1; + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if((v2X * n243X + v2Y * n243Y + v2Z * n243Z) * sign < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + let v3X; + let v3Y; + let v3Z; + let v12X; + let v12Y; + let v12Z; + let v23X; + let v23Y; + let v23Z; + let v31X; + let v31Y; + let v31Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + v3X = vec4.x; + v3Y = vec4.y; + v3Z = vec4.z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + v23X = v3X - v2X; + v23Y = v3Y - v2Y; + v23Z = v3Z - v2Z; + v31X = v1X - v3X; + v31Y = v1Y - v3Y; + v31Z = v1Z - v3Z; + let nX; + let nY; + let nZ; + nX = v12Y * v23Z - v12Z * v23Y; + nY = v12Z * v23X - v12X * v23Z; + nZ = v12X * v23Y - v12Y * v23X; + let n12X; + let n12Y; + let n12Z; + let n23X; + let n23Y; + let n23Z; + let n31X; + let n31Y; + let n31Z; + n12X = v12Y * nZ - v12Z * nY; + n12Y = v12Z * nX - v12X * nZ; + n12Z = v12X * nY - v12Y * nX; + n23X = v23Y * nZ - v23Z * nY; + n23Y = v23Z * nX - v23X * nZ; + n23Z = v23X * nY - v23Y * nX; + n31X = v31Y * nZ - v31Z * nY; + n31Y = v31Z * nX - v31X * nZ; + n31Z = v31X * nY - v31Y * nX; + let mind1 = -1; + let minvX1; + let minvY1; + let minvZ1; + let mini1 = 0; + minvX1 = 0; + minvY1 = 0; + minvZ1 = 0; + if(v1X * n12X + v1Y * n12Y + v1Z * n12Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec3.x; + v2Y = vec3.y; + v2Z = vec3.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + mini1 = b; + mind1 = out.x * out.x + out.y * out.y + out.z * out.z; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + if(v2X * n23X + v2Y * n23Y + v2Z * n23Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec3.x; + v1Y = vec3.y; + v1Z = vec3.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + if(v3X * n31X + v3Y * n31Y + v3Z * n31Z < 0) { + let v1X; + let v1Y; + let v1Z; + let v2X; + let v2Y; + let v2Z; + v1X = vec2.x; + v1Y = vec2.y; + v1Z = vec2.z; + v2X = vec4.x; + v2Y = vec4.y; + v2Z = vec4.z; + let v12X; + let v12Y; + let v12Z; + v12X = v2X - v1X; + v12Y = v2Y - v1Y; + v12Z = v2Z - v1Z; + let t = v12X * v1X + v12Y * v1Y + v12Z * v1Z; + t = -t / (v12X * v12X + v12Y * v12Y + v12Z * v12Z); + let b; + if(t < 0) { + out.x = v1X; + out.y = v1Y; + out.z = v1Z; + b = 1; + } else if(t > 1) { + out.x = v2X; + out.y = v2Y; + out.z = v2Z; + b = 2; + } else { + let pX; + let pY; + let pZ; + pX = v1X + v12X * t; + pY = v1Y + v12Y * t; + pZ = v1Z + v12Z * t; + out.x = pX; + out.y = pY; + out.z = pZ; + b = 3; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind1 < 0 || d < mind1) { + mini1 = b & 1 | (b & 2) << 1; + mind1 = d; + minvX1 = out.x; + minvY1 = out.y; + minvZ1 = out.z; + } + } + let b; + if(mind1 > 0) { + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = mini1; + } else { + let l = nX * nX + nY * nY + nZ * nZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + nX *= l; + nY *= l; + nZ *= l; + let l2 = nX * nX + nY * nY + nZ * nZ; + l2 = (v1X * nX + v1Y * nY + v1Z * nZ) / l2; + minvX1 = nX * l2; + minvY1 = nY * l2; + minvZ1 = nZ * l2; + out.x = minvX1; + out.y = minvY1; + out.z = minvZ1; + b = 7; + } + let d = out.x * out.x + out.y * out.y + out.z * out.z; + if(mind < 0 || d < mind) { + mini = b << 1; + mind = d; + minvX = out.x; + minvY = out.y; + minvZ = out.z; + } + } + if(mind > 0) { + out.x = minvX; + out.y = minvY; + out.z = minvZ; + return mini; + } + out.zero(); + return 15; + } +} +oimo.common.Mat3 = class oimo_common_Mat3 { + constructor(e00,e01,e02,e10,e11,e12,e20,e21,e22) { + if(e22 == null) { + e22 = 1; + } + if(e21 == null) { + e21 = 0; + } + if(e20 == null) { + e20 = 0; + } + if(e12 == null) { + e12 = 0; + } + if(e11 == null) { + e11 = 1; + } + if(e10 == null) { + e10 = 0; + } + if(e02 == null) { + e02 = 0; + } + if(e01 == null) { + e01 = 0; + } + if(e00 == null) { + e00 = 1; + } + this.e00 = e00; + this.e01 = e01; + this.e02 = e02; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + oimo.common.Mat3.numCreations++; + } + init(e00,e01,e02,e10,e11,e12,e20,e21,e22) { + this.e00 = e00; + this.e01 = e01; + this.e02 = e02; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + return this; + } + identity() { + this.e00 = 1; + this.e01 = 0; + this.e02 = 0; + this.e10 = 0; + this.e11 = 1; + this.e12 = 0; + this.e20 = 0; + this.e21 = 0; + this.e22 = 1; + return this; + } + add(m) { + return new oimo.common.Mat3(this.e00 + m.e00,this.e01 + m.e01,this.e02 + m.e02,this.e10 + m.e10,this.e11 + m.e11,this.e12 + m.e12,this.e20 + m.e20,this.e21 + m.e21,this.e22 + m.e22); + } + sub(m) { + return new oimo.common.Mat3(this.e00 - m.e00,this.e01 - m.e01,this.e02 - m.e02,this.e10 - m.e10,this.e11 - m.e11,this.e12 - m.e12,this.e20 - m.e20,this.e21 - m.e21,this.e22 - m.e22); + } + scale(s) { + return new oimo.common.Mat3(this.e00 * s,this.e01 * s,this.e02 * s,this.e10 * s,this.e11 * s,this.e12 * s,this.e20 * s,this.e21 * s,this.e22 * s); + } + mul(m) { + return new oimo.common.Mat3(this.e00 * m.e00 + this.e01 * m.e10 + this.e02 * m.e20,this.e00 * m.e01 + this.e01 * m.e11 + this.e02 * m.e21,this.e00 * m.e02 + this.e01 * m.e12 + this.e02 * m.e22,this.e10 * m.e00 + this.e11 * m.e10 + this.e12 * m.e20,this.e10 * m.e01 + this.e11 * m.e11 + this.e12 * m.e21,this.e10 * m.e02 + this.e11 * m.e12 + this.e12 * m.e22,this.e20 * m.e00 + this.e21 * m.e10 + this.e22 * m.e20,this.e20 * m.e01 + this.e21 * m.e11 + this.e22 * m.e21,this.e20 * m.e02 + this.e21 * m.e12 + this.e22 * m.e22); + } + addEq(m) { + this.e00 += m.e00; + this.e01 += m.e01; + this.e02 += m.e02; + this.e10 += m.e10; + this.e11 += m.e11; + this.e12 += m.e12; + this.e20 += m.e20; + this.e21 += m.e21; + this.e22 += m.e22; + return this; + } + subEq(m) { + this.e00 -= m.e00; + this.e01 -= m.e01; + this.e02 -= m.e02; + this.e10 -= m.e10; + this.e11 -= m.e11; + this.e12 -= m.e12; + this.e20 -= m.e20; + this.e21 -= m.e21; + this.e22 -= m.e22; + return this; + } + scaleEq(s) { + this.e00 *= s; + this.e01 *= s; + this.e02 *= s; + this.e10 *= s; + this.e11 *= s; + this.e12 *= s; + this.e20 *= s; + this.e21 *= s; + this.e22 *= s; + return this; + } + mulEq(m) { + let e01 = this.e00 * m.e01 + this.e01 * m.e11 + this.e02 * m.e21; + let e02 = this.e00 * m.e02 + this.e01 * m.e12 + this.e02 * m.e22; + let e10 = this.e10 * m.e00 + this.e11 * m.e10 + this.e12 * m.e20; + let e11 = this.e10 * m.e01 + this.e11 * m.e11 + this.e12 * m.e21; + let e12 = this.e10 * m.e02 + this.e11 * m.e12 + this.e12 * m.e22; + let e20 = this.e20 * m.e00 + this.e21 * m.e10 + this.e22 * m.e20; + let e21 = this.e20 * m.e01 + this.e21 * m.e11 + this.e22 * m.e21; + let e22 = this.e20 * m.e02 + this.e21 * m.e12 + this.e22 * m.e22; + this.e00 = this.e00 * m.e00 + this.e01 * m.e10 + this.e02 * m.e20; + this.e01 = e01; + this.e02 = e02; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + return this; + } + prependScale(sx,sy,sz) { + return new oimo.common.Mat3(this.e00 * sx,this.e01 * sx,this.e02 * sx,this.e10 * sy,this.e11 * sy,this.e12 * sy,this.e20 * sz,this.e21 * sz,this.e22 * sz); + } + appendScale(sx,sy,sz) { + return new oimo.common.Mat3(this.e00 * sx,this.e01 * sy,this.e02 * sz,this.e10 * sx,this.e11 * sy,this.e12 * sz,this.e20 * sx,this.e21 * sy,this.e22 * sz); + } + prependRotation(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + return new oimo.common.Mat3(r00 * this.e00 + r01 * this.e10 + r02 * this.e20,r00 * this.e01 + r01 * this.e11 + r02 * this.e21,r00 * this.e02 + r01 * this.e12 + r02 * this.e22,r10 * this.e00 + r11 * this.e10 + r12 * this.e20,r10 * this.e01 + r11 * this.e11 + r12 * this.e21,r10 * this.e02 + r11 * this.e12 + r12 * this.e22,r20 * this.e00 + r21 * this.e10 + r22 * this.e20,r20 * this.e01 + r21 * this.e11 + r22 * this.e21,r20 * this.e02 + r21 * this.e12 + r22 * this.e22); + } + appendRotation(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + return new oimo.common.Mat3(this.e00 * r00 + this.e01 * r10 + this.e02 * r20,this.e00 * r01 + this.e01 * r11 + this.e02 * r21,this.e00 * r02 + this.e01 * r12 + this.e02 * r22,this.e10 * r00 + this.e11 * r10 + this.e12 * r20,this.e10 * r01 + this.e11 * r11 + this.e12 * r21,this.e10 * r02 + this.e11 * r12 + this.e12 * r22,this.e20 * r00 + this.e21 * r10 + this.e22 * r20,this.e20 * r01 + this.e21 * r11 + this.e22 * r21,this.e20 * r02 + this.e21 * r12 + this.e22 * r22); + } + prependScaleEq(sx,sy,sz) { + this.e00 *= sx; + this.e01 *= sx; + this.e02 *= sx; + this.e10 *= sy; + this.e11 *= sy; + this.e12 *= sy; + this.e20 *= sz; + this.e21 *= sz; + this.e22 *= sz; + return this; + } + appendScaleEq(sx,sy,sz) { + this.e00 *= sx; + this.e01 *= sy; + this.e02 *= sz; + this.e10 *= sx; + this.e11 *= sy; + this.e12 *= sz; + this.e20 *= sx; + this.e21 *= sy; + this.e22 *= sz; + return this; + } + prependRotationEq(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + let e10 = r10 * this.e00 + r11 * this.e10 + r12 * this.e20; + let e11 = r10 * this.e01 + r11 * this.e11 + r12 * this.e21; + let e12 = r10 * this.e02 + r11 * this.e12 + r12 * this.e22; + let e20 = r20 * this.e00 + r21 * this.e10 + r22 * this.e20; + let e21 = r20 * this.e01 + r21 * this.e11 + r22 * this.e21; + let e22 = r20 * this.e02 + r21 * this.e12 + r22 * this.e22; + this.e00 = r00 * this.e00 + r01 * this.e10 + r02 * this.e20; + this.e01 = r00 * this.e01 + r01 * this.e11 + r02 * this.e21; + this.e02 = r00 * this.e02 + r01 * this.e12 + r02 * this.e22; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + return this; + } + appendRotationEq(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + let e01 = this.e00 * r01 + this.e01 * r11 + this.e02 * r21; + let e02 = this.e00 * r02 + this.e01 * r12 + this.e02 * r22; + let e11 = this.e10 * r01 + this.e11 * r11 + this.e12 * r21; + let e12 = this.e10 * r02 + this.e11 * r12 + this.e12 * r22; + let e21 = this.e20 * r01 + this.e21 * r11 + this.e22 * r21; + let e22 = this.e20 * r02 + this.e21 * r12 + this.e22 * r22; + this.e00 = this.e00 * r00 + this.e01 * r10 + this.e02 * r20; + this.e01 = e01; + this.e02 = e02; + this.e10 = this.e10 * r00 + this.e11 * r10 + this.e12 * r20; + this.e11 = e11; + this.e12 = e12; + this.e20 = this.e20 * r00 + this.e21 * r10 + this.e22 * r20; + this.e21 = e21; + this.e22 = e22; + return this; + } + transpose() { + return new oimo.common.Mat3(this.e00,this.e10,this.e20,this.e01,this.e11,this.e21,this.e02,this.e12,this.e22); + } + transposeEq() { + let e10 = this.e01; + let e20 = this.e02; + let e21 = this.e12; + + this.e01 = this.e10; + this.e02 = this.e20; + this.e10 = e10; + + this.e12 = this.e21; + this.e20 = e20; + this.e21 = e21; + + return this; + } + determinant() { + return this.e00 * (this.e11 * this.e22 - this.e12 * this.e21) - this.e01 * (this.e10 * this.e22 - this.e12 * this.e20) + this.e02 * (this.e10 * this.e21 - this.e11 * this.e20); + } + trace() { + return this.e00 + this.e11 + this.e22; + } + inverse() { + let d00 = this.e11 * this.e22 - this.e12 * this.e21; + let d01 = this.e10 * this.e22 - this.e12 * this.e20; + let d02 = this.e10 * this.e21 - this.e11 * this.e20; + let invDet = this.e00 * d00 - this.e01 * d01 + this.e02 * d02; + if(invDet != 0) { + invDet = 1 / invDet; + } + return new oimo.common.Mat3(d00 * invDet,-(this.e01 * this.e22 - this.e02 * this.e21) * invDet,(this.e01 * this.e12 - this.e02 * this.e11) * invDet,-d01 * invDet,(this.e00 * this.e22 - this.e02 * this.e20) * invDet,-(this.e00 * this.e12 - this.e02 * this.e10) * invDet,d02 * invDet,-(this.e00 * this.e21 - this.e01 * this.e20) * invDet,(this.e00 * this.e11 - this.e01 * this.e10) * invDet); + } + inverseEq() { + let d00 = this.e11 * this.e22 - this.e12 * this.e21; + let d01 = this.e10 * this.e22 - this.e12 * this.e20; + let d02 = this.e10 * this.e21 - this.e11 * this.e20; + let invDet = this.e00 * d00 - this.e01 * d01 + this.e02 * d02; + if(invDet != 0) { + invDet = 1 / invDet; + } + let t02 = (this.e01 * this.e12 - this.e02 * this.e11) * invDet; + let t11 = (this.e00 * this.e22 - this.e02 * this.e20) * invDet; + let t12 = -(this.e00 * this.e12 - this.e02 * this.e10) * invDet; + let t21 = -(this.e00 * this.e21 - this.e01 * this.e20) * invDet; + let t22 = (this.e00 * this.e11 - this.e01 * this.e10) * invDet; + this.e00 = d00 * invDet; + this.e01 = -(this.e01 * this.e22 - this.e02 * this.e21) * invDet; + this.e02 = t02; + this.e10 = -d01 * invDet; + this.e11 = t11; + this.e12 = t12; + this.e20 = d02 * invDet; + this.e21 = t21; + this.e22 = t22; + return this; + } + toArray(columnMajor) { + if(columnMajor == null) { + columnMajor = false; + } + if(columnMajor) { + return [this.e00,this.e10,this.e20,this.e01,this.e11,this.e21,this.e02,this.e12,this.e22]; + } else { + return [this.e00,this.e01,this.e02,this.e10,this.e11,this.e12,this.e20,this.e21,this.e22]; + } + } + copyFrom(m) { + this.e00 = m.e00; + this.e01 = m.e01; + this.e02 = m.e02; + this.e10 = m.e10; + this.e11 = m.e11; + this.e12 = m.e12; + this.e20 = m.e20; + this.e21 = m.e21; + this.e22 = m.e22; + return this; + } + clone() { + return new oimo.common.Mat3(this.e00,this.e01,this.e02,this.e10,this.e11,this.e12,this.e20,this.e21,this.e22); + } + fromQuat(q) { + let x = q.x; + let y = q.y; + let z = q.z; + let w = q.w; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + this.e00 = 1 - yy - zz; + this.e01 = xy - wz; + this.e02 = xz + wy; + this.e10 = xy + wz; + this.e11 = 1 - xx - zz; + this.e12 = yz - wx; + this.e20 = xz - wy; + this.e21 = yz + wx; + this.e22 = 1 - xx - yy; + return this; + } + toQuat() { + let _this = new oimo.common.Quat(); + let e00 = this.e00; + let e11 = this.e11; + let e22 = this.e22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + _this.w = 0.5 * s; + s = 0.5 / s; + _this.x = (this.e21 - this.e12) * s; + _this.y = (this.e02 - this.e20) * s; + _this.z = (this.e10 - this.e01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + _this.x = 0.5 * s; + s = 0.5 / s; + _this.y = (this.e01 + this.e10) * s; + _this.z = (this.e02 + this.e20) * s; + _this.w = (this.e21 - this.e12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + _this.z = 0.5 * s; + s = 0.5 / s; + _this.x = (this.e02 + this.e20) * s; + _this.y = (this.e12 + this.e21) * s; + _this.w = (this.e10 - this.e01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + _this.y = 0.5 * s; + s = 0.5 / s; + _this.x = (this.e01 + this.e10) * s; + _this.z = (this.e12 + this.e21) * s; + _this.w = (this.e02 - this.e20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + _this.z = 0.5 * s; + s = 0.5 / s; + _this.x = (this.e02 + this.e20) * s; + _this.y = (this.e12 + this.e21) * s; + _this.w = (this.e10 - this.e01) * s; + } + return _this; + } + fromEulerXyz(eulerAngles) { + let sx = Math.sin(eulerAngles.x); + let sy = Math.sin(eulerAngles.y); + let sz = Math.sin(eulerAngles.z); + let cx = Math.cos(eulerAngles.x); + let cy = Math.cos(eulerAngles.y); + let cz = Math.cos(eulerAngles.z); + this.e00 = cy * cz; + this.e01 = -cy * sz; + this.e02 = sy; + this.e10 = cx * sz + cz * sx * sy; + this.e11 = cx * cz - sx * sy * sz; + this.e12 = -cy * sx; + this.e20 = sx * sz - cx * cz * sy; + this.e21 = cz * sx + cx * sy * sz; + this.e22 = cx * cy; + return this; + } + toEulerXyz() { + let sy = this.e02; + if(sy <= -1) { + let xSubZ = Math.atan2(this.e21,this.e11); + return new oimo.common.Vec3(xSubZ * 0.5,-1.570796326794895,-xSubZ * 0.5); + } + if(sy >= 1) { + let xAddZ = Math.atan2(this.e21,this.e11); + return new oimo.common.Vec3(xAddZ * 0.5,1.570796326794895,xAddZ * 0.5); + } + return new oimo.common.Vec3(Math.atan2(-this.e12,this.e22),Math.asin(sy),Math.atan2(-this.e01,this.e00)); + } + getRow(index) { + if(index == 0) { + return new oimo.common.Vec3(this.e00,this.e01,this.e02); + } else if(index == 1) { + return new oimo.common.Vec3(this.e10,this.e11,this.e12); + } else if(index == 2) { + return new oimo.common.Vec3(this.e20,this.e21,this.e22); + } else { + return null; + } + } + getCol(index) { + if(index == 0) { + return new oimo.common.Vec3(this.e00,this.e10,this.e20); + } else if(index == 1) { + return new oimo.common.Vec3(this.e01,this.e11,this.e21); + } else if(index == 2) { + return new oimo.common.Vec3(this.e02,this.e12,this.e22); + } else { + return null; + } + } + getRowTo(index,dst) { + if(index == 0) { + dst.init(this.e00,this.e01,this.e02); + } else if(index == 1) { + dst.init(this.e10,this.e11,this.e12); + } else if(index == 2) { + dst.init(this.e20,this.e21,this.e22); + } else { + dst.zero(); + } + } + getColTo(index,dst) { + if(index == 0) { + dst.init(this.e00,this.e10,this.e20); + } else if(index == 1) { + dst.init(this.e01,this.e11,this.e21); + } else if(index == 2) { + dst.init(this.e02,this.e12,this.e22); + } else { + dst.zero(); + } + } + fromRows(row0,row1,row2) { + this.e00 = row0.x; + this.e01 = row0.y; + this.e02 = row0.z; + this.e10 = row1.x; + this.e11 = row1.y; + this.e12 = row1.z; + this.e20 = row2.x; + this.e21 = row2.y; + this.e22 = row2.z; + return this; + } + fromCols(col0,col1,col2) { + this.e00 = col0.x; + this.e01 = col1.x; + this.e02 = col2.x; + this.e10 = col0.y; + this.e11 = col1.y; + this.e12 = col2.y; + this.e20 = col0.z; + this.e21 = col1.z; + this.e22 = col2.z; + return this; + } + toString() { + return "Mat3[" + (this.e00 > 0 ? (this.e00 * 10000000 + 0.5 | 0) / 10000000 : (this.e00 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e01 > 0 ? (this.e01 * 10000000 + 0.5 | 0) / 10000000 : (this.e01 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e02 > 0 ? (this.e02 * 10000000 + 0.5 | 0) / 10000000 : (this.e02 * 10000000 - 0.5 | 0) / 10000000) + ",\n" + " " + (this.e10 > 0 ? (this.e10 * 10000000 + 0.5 | 0) / 10000000 : (this.e10 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e11 > 0 ? (this.e11 * 10000000 + 0.5 | 0) / 10000000 : (this.e11 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e12 > 0 ? (this.e12 * 10000000 + 0.5 | 0) / 10000000 : (this.e12 * 10000000 - 0.5 | 0) / 10000000) + ",\n" + " " + (this.e20 > 0 ? (this.e20 * 10000000 + 0.5 | 0) / 10000000 : (this.e20 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e21 > 0 ? (this.e21 * 10000000 + 0.5 | 0) / 10000000 : (this.e21 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e22 > 0 ? (this.e22 * 10000000 + 0.5 | 0) / 10000000 : (this.e22 * 10000000 - 0.5 | 0) / 10000000) + "]"; + } +} +oimo.common.Mat4 = class oimo_common_Mat4 { + constructor(e00,e01,e02,e03,e10,e11,e12,e13,e20,e21,e22,e23,e30,e31,e32,e33) { + if(e33 == null) { + e33 = 1; + } + if(e32 == null) { + e32 = 0; + } + if(e31 == null) { + e31 = 0; + } + if(e30 == null) { + e30 = 0; + } + if(e23 == null) { + e23 = 0; + } + if(e22 == null) { + e22 = 1; + } + if(e21 == null) { + e21 = 0; + } + if(e20 == null) { + e20 = 0; + } + if(e13 == null) { + e13 = 0; + } + if(e12 == null) { + e12 = 0; + } + if(e11 == null) { + e11 = 1; + } + if(e10 == null) { + e10 = 0; + } + if(e03 == null) { + e03 = 0; + } + if(e02 == null) { + e02 = 0; + } + if(e01 == null) { + e01 = 0; + } + if(e00 == null) { + e00 = 1; + } + this.e00 = e00; + this.e01 = e01; + this.e02 = e02; + this.e03 = e03; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e13 = e13; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + this.e23 = e23; + this.e30 = e30; + this.e31 = e31; + this.e32 = e32; + this.e33 = e33; + oimo.common.Mat4.numCreations++; + } + init(e00,e01,e02,e03,e10,e11,e12,e13,e20,e21,e22,e23,e30,e31,e32,e33) { + this.e00 = e00; + this.e01 = e01; + this.e02 = e02; + this.e03 = e03; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e13 = e13; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + this.e23 = e23; + this.e30 = e30; + this.e31 = e31; + this.e32 = e32; + this.e33 = e33; + return this; + } + identity() { + this.e00 = 1; + this.e01 = 0; + this.e02 = 0; + this.e03 = 0; + this.e10 = 0; + this.e11 = 1; + this.e12 = 0; + this.e13 = 0; + this.e20 = 0; + this.e21 = 0; + this.e22 = 1; + this.e23 = 0; + this.e30 = 0; + this.e31 = 0; + this.e32 = 0; + this.e33 = 1; + return this; + } + add(m) { + return new oimo.common.Mat4(this.e00 + m.e00,this.e01 + m.e01,this.e02 + m.e02,this.e03 + m.e03,this.e10 + m.e10,this.e11 + m.e11,this.e12 + m.e12,this.e13 + m.e13,this.e20 + m.e20,this.e21 + m.e21,this.e22 + m.e22,this.e23 + m.e23,this.e30 + m.e30,this.e31 + m.e31,this.e32 + m.e32,this.e33 + m.e33); + } + sub(m) { + return new oimo.common.Mat4(this.e00 - m.e00,this.e01 - m.e01,this.e02 - m.e02,this.e03 - m.e03,this.e10 - m.e10,this.e11 - m.e11,this.e12 - m.e12,this.e13 - m.e13,this.e20 - m.e20,this.e21 - m.e21,this.e22 - m.e22,this.e23 - m.e23,this.e30 - m.e30,this.e31 - m.e31,this.e32 - m.e32,this.e33 - m.e33); + } + scale(s) { + return new oimo.common.Mat4(this.e00 * s,this.e01 * s,this.e02 * s,this.e03 * s,this.e10 * s,this.e11 * s,this.e12 * s,this.e13 * s,this.e20 * s,this.e21 * s,this.e22 * s,this.e23 * s,this.e30 * s,this.e31 * s,this.e32 * s,this.e33 * s); + } + mul(m) { + return new oimo.common.Mat4(this.e00 * m.e00 + this.e01 * m.e10 + this.e02 * m.e20 + this.e03 * m.e30,this.e00 * m.e01 + this.e01 * m.e11 + this.e02 * m.e21 + this.e03 * m.e31,this.e00 * m.e02 + this.e01 * m.e12 + this.e02 * m.e22 + this.e03 * m.e32,this.e00 * m.e03 + this.e01 * m.e13 + this.e02 * m.e23 + this.e03 * m.e33,this.e10 * m.e00 + this.e11 * m.e10 + this.e12 * m.e20 + this.e13 * m.e30,this.e10 * m.e01 + this.e11 * m.e11 + this.e12 * m.e21 + this.e13 * m.e31,this.e10 * m.e02 + this.e11 * m.e12 + this.e12 * m.e22 + this.e13 * m.e32,this.e10 * m.e03 + this.e11 * m.e13 + this.e12 * m.e23 + this.e13 * m.e33,this.e20 * m.e00 + this.e21 * m.e10 + this.e22 * m.e20 + this.e23 * m.e30,this.e20 * m.e01 + this.e21 * m.e11 + this.e22 * m.e21 + this.e23 * m.e31,this.e20 * m.e02 + this.e21 * m.e12 + this.e22 * m.e22 + this.e23 * m.e32,this.e20 * m.e03 + this.e21 * m.e13 + this.e22 * m.e23 + this.e23 * m.e33,this.e30 * m.e00 + this.e31 * m.e10 + this.e32 * m.e20 + this.e33 * m.e30,this.e30 * m.e01 + this.e31 * m.e11 + this.e32 * m.e21 + this.e33 * m.e31,this.e30 * m.e02 + this.e31 * m.e12 + this.e32 * m.e22 + this.e33 * m.e32,this.e30 * m.e03 + this.e31 * m.e13 + this.e32 * m.e23 + this.e33 * m.e33); + } + addEq(m) { + this.e00 += m.e00; + this.e01 += m.e01; + this.e02 += m.e02; + this.e03 += m.e03; + this.e10 += m.e10; + this.e11 += m.e11; + this.e12 += m.e12; + this.e13 += m.e13; + this.e20 += m.e20; + this.e21 += m.e21; + this.e22 += m.e22; + this.e23 += m.e23; + this.e30 += m.e30; + this.e31 += m.e31; + this.e32 += m.e32; + this.e33 += m.e33; + return this; + } + subEq(m) { + this.e00 -= m.e00; + this.e01 -= m.e01; + this.e02 -= m.e02; + this.e03 -= m.e03; + this.e10 -= m.e10; + this.e11 -= m.e11; + this.e12 -= m.e12; + this.e13 -= m.e13; + this.e20 -= m.e20; + this.e21 -= m.e21; + this.e22 -= m.e22; + this.e23 -= m.e23; + this.e30 -= m.e30; + this.e31 -= m.e31; + this.e32 -= m.e32; + this.e33 -= m.e33; + return this; + } + scaleEq(s) { + this.e00 *= s; + this.e01 *= s; + this.e02 *= s; + this.e03 *= s; + this.e10 *= s; + this.e11 *= s; + this.e12 *= s; + this.e13 *= s; + this.e20 *= s; + this.e21 *= s; + this.e22 *= s; + this.e23 *= s; + this.e30 *= s; + this.e31 *= s; + this.e32 *= s; + this.e33 *= s; + return this; + } + mulEq(m) { + let e01 = this.e00 * m.e01 + this.e01 * m.e11 + this.e02 * m.e21 + this.e03 * m.e31; + let e02 = this.e00 * m.e02 + this.e01 * m.e12 + this.e02 * m.e22 + this.e03 * m.e32; + let e03 = this.e00 * m.e03 + this.e01 * m.e13 + this.e02 * m.e23 + this.e03 * m.e33; + let e10 = this.e10 * m.e00 + this.e11 * m.e10 + this.e12 * m.e20 + this.e13 * m.e30; + let e11 = this.e10 * m.e01 + this.e11 * m.e11 + this.e12 * m.e21 + this.e13 * m.e31; + let e12 = this.e10 * m.e02 + this.e11 * m.e12 + this.e12 * m.e22 + this.e13 * m.e32; + let e13 = this.e10 * m.e03 + this.e11 * m.e13 + this.e12 * m.e23 + this.e13 * m.e33; + let e20 = this.e20 * m.e00 + this.e21 * m.e10 + this.e22 * m.e20 + this.e23 * m.e30; + let e21 = this.e20 * m.e01 + this.e21 * m.e11 + this.e22 * m.e21 + this.e23 * m.e31; + let e22 = this.e20 * m.e02 + this.e21 * m.e12 + this.e22 * m.e22 + this.e23 * m.e32; + let e23 = this.e20 * m.e03 + this.e21 * m.e13 + this.e22 * m.e23 + this.e23 * m.e33; + let e30 = this.e30 * m.e00 + this.e31 * m.e10 + this.e32 * m.e20 + this.e33 * m.e30; + let e31 = this.e30 * m.e01 + this.e31 * m.e11 + this.e32 * m.e21 + this.e33 * m.e31; + let e32 = this.e30 * m.e02 + this.e31 * m.e12 + this.e32 * m.e22 + this.e33 * m.e32; + let e33 = this.e30 * m.e03 + this.e31 * m.e13 + this.e32 * m.e23 + this.e33 * m.e33; + this.e00 = this.e00 * m.e00 + this.e01 * m.e10 + this.e02 * m.e20 + this.e03 * m.e30; + this.e01 = e01; + this.e02 = e02; + this.e03 = e03; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e13 = e13; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + this.e23 = e23; + this.e30 = e30; + this.e31 = e31; + this.e32 = e32; + this.e33 = e33; + return this; + } + prependScale(sx,sy,sz) { + return new oimo.common.Mat4(this.e00 * sx,this.e01 * sx,this.e02 * sx,this.e03 * sx,this.e10 * sy,this.e11 * sy,this.e12 * sy,this.e13 * sy,this.e20 * sz,this.e21 * sz,this.e22 * sz,this.e23 * sz,this.e30,this.e31,this.e32,this.e33); + } + appendScale(sx,sy,sz) { + return new oimo.common.Mat4(this.e00 * sx,this.e01 * sy,this.e02 * sz,this.e03,this.e10 * sx,this.e11 * sy,this.e12 * sz,this.e13,this.e20 * sx,this.e21 * sy,this.e22 * sz,this.e23,this.e30 * sx,this.e31 * sy,this.e32 * sz,this.e33); + } + prependRotation(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + return new oimo.common.Mat4(r00 * this.e00 + r01 * this.e10 + r02 * this.e20,r00 * this.e01 + r01 * this.e11 + r02 * this.e21,r00 * this.e02 + r01 * this.e12 + r02 * this.e22,r00 * this.e03 + r01 * this.e13 + r02 * this.e23,r10 * this.e00 + r11 * this.e10 + r12 * this.e20,r10 * this.e01 + r11 * this.e11 + r12 * this.e21,r10 * this.e02 + r11 * this.e12 + r12 * this.e22,r10 * this.e03 + r11 * this.e13 + r12 * this.e23,r20 * this.e00 + r21 * this.e10 + r22 * this.e20,r20 * this.e01 + r21 * this.e11 + r22 * this.e21,r20 * this.e02 + r21 * this.e12 + r22 * this.e22,r20 * this.e03 + r21 * this.e13 + r22 * this.e23,this.e30,this.e31,this.e32,this.e33); + } + appendRotation(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + return new oimo.common.Mat4(this.e00 * r00 + this.e01 * r10 + this.e02 * r20,this.e00 * r01 + this.e01 * r11 + this.e02 * r21,this.e00 * r02 + this.e01 * r12 + this.e02 * r22,this.e03,this.e10 * r00 + this.e11 * r10 + this.e12 * r20,this.e10 * r01 + this.e11 * r11 + this.e12 * r21,this.e10 * r02 + this.e11 * r12 + this.e12 * r22,this.e13,this.e20 * r00 + this.e21 * r10 + this.e22 * r20,this.e20 * r01 + this.e21 * r11 + this.e22 * r21,this.e20 * r02 + this.e21 * r12 + this.e22 * r22,this.e23,this.e30 * r00 + this.e31 * r10 + this.e32 * r20,this.e30 * r01 + this.e31 * r11 + this.e32 * r21,this.e30 * r02 + this.e31 * r12 + this.e32 * r22,this.e33); + } + prependTranslation(tx,ty,tz) { + return new oimo.common.Mat4(this.e00 + tx * this.e30,this.e01 + tx * this.e31,this.e02 + tx * this.e32,this.e03 + tx * this.e33,this.e10 + ty * this.e30,this.e11 + ty * this.e31,this.e12 + ty * this.e32,this.e13 + ty * this.e33,this.e20 + tz * this.e30,this.e21 + tz * this.e31,this.e22 + tz * this.e32,this.e23 + tz * this.e33,this.e30,this.e31,this.e32,this.e33); + } + appendTranslation(tx,ty,tz) { + return new oimo.common.Mat4(this.e00,this.e01,this.e02,this.e00 * tx + this.e01 * ty + this.e02 * tz + this.e03,this.e10,this.e11,this.e12,this.e10 * tx + this.e11 * ty + this.e12 * tz + this.e13,this.e20,this.e21,this.e22,this.e20 * tx + this.e21 * ty + this.e22 * tz + this.e23,this.e30,this.e31,this.e32,this.e30 * tx + this.e31 * ty + this.e32 * tz + this.e33); + } + prependScaleEq(sx,sy,sz) { + this.e00 *= sx; + this.e01 *= sx; + this.e02 *= sx; + this.e03 *= sx; + this.e10 *= sy; + this.e11 *= sy; + this.e12 *= sy; + this.e13 *= sy; + this.e20 *= sz; + this.e21 *= sz; + this.e22 *= sz; + this.e23 *= sz; + + + + + return this; + } + appendScaleEq(sx,sy,sz) { + this.e00 *= sx; + this.e01 *= sy; + this.e02 *= sz; + + this.e10 *= sx; + this.e11 *= sy; + this.e12 *= sz; + + this.e20 *= sx; + this.e21 *= sy; + this.e22 *= sz; + + this.e30 *= sx; + this.e31 *= sy; + this.e32 *= sz; + + return this; + } + prependRotationEq(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + let e10 = r10 * this.e00 + r11 * this.e10 + r12 * this.e20; + let e11 = r10 * this.e01 + r11 * this.e11 + r12 * this.e21; + let e12 = r10 * this.e02 + r11 * this.e12 + r12 * this.e22; + let e13 = r10 * this.e03 + r11 * this.e13 + r12 * this.e23; + let e20 = r20 * this.e00 + r21 * this.e10 + r22 * this.e20; + let e21 = r20 * this.e01 + r21 * this.e11 + r22 * this.e21; + let e22 = r20 * this.e02 + r21 * this.e12 + r22 * this.e22; + let e23 = r20 * this.e03 + r21 * this.e13 + r22 * this.e23; + this.e00 = r00 * this.e00 + r01 * this.e10 + r02 * this.e20; + this.e01 = r00 * this.e01 + r01 * this.e11 + r02 * this.e21; + this.e02 = r00 * this.e02 + r01 * this.e12 + r02 * this.e22; + this.e03 = r00 * this.e03 + r01 * this.e13 + r02 * this.e23; + this.e10 = e10; + this.e11 = e11; + this.e12 = e12; + this.e13 = e13; + this.e20 = e20; + this.e21 = e21; + this.e22 = e22; + this.e23 = e23; + + + + + return this; + } + appendRotationEq(rad,axisX,axisY,axisZ) { + let s = Math.sin(rad); + let c = Math.cos(rad); + let c1 = 1 - c; + let r00 = axisX * axisX * c1 + c; + let r01 = axisX * axisY * c1 - axisZ * s; + let r02 = axisX * axisZ * c1 + axisY * s; + let r10 = axisY * axisX * c1 + axisZ * s; + let r11 = axisY * axisY * c1 + c; + let r12 = axisY * axisZ * c1 - axisX * s; + let r20 = axisZ * axisX * c1 - axisY * s; + let r21 = axisZ * axisY * c1 + axisX * s; + let r22 = axisZ * axisZ * c1 + c; + let e01 = this.e00 * r01 + this.e01 * r11 + this.e02 * r21; + let e02 = this.e00 * r02 + this.e01 * r12 + this.e02 * r22; + let e11 = this.e10 * r01 + this.e11 * r11 + this.e12 * r21; + let e12 = this.e10 * r02 + this.e11 * r12 + this.e12 * r22; + let e21 = this.e20 * r01 + this.e21 * r11 + this.e22 * r21; + let e22 = this.e20 * r02 + this.e21 * r12 + this.e22 * r22; + let e31 = this.e30 * r01 + this.e31 * r11 + this.e32 * r21; + let e32 = this.e30 * r02 + this.e31 * r12 + this.e32 * r22; + this.e00 = this.e00 * r00 + this.e01 * r10 + this.e02 * r20; + this.e01 = e01; + this.e02 = e02; + + this.e10 = this.e10 * r00 + this.e11 * r10 + this.e12 * r20; + this.e11 = e11; + this.e12 = e12; + + this.e20 = this.e20 * r00 + this.e21 * r10 + this.e22 * r20; + this.e21 = e21; + this.e22 = e22; + + this.e30 = this.e30 * r00 + this.e31 * r10 + this.e32 * r20; + this.e31 = e31; + this.e32 = e32; + + return this; + } + prependTranslationEq(tx,ty,tz) { + this.e00 += tx * this.e30; + this.e01 += tx * this.e31; + this.e02 += tx * this.e32; + this.e03 += tx * this.e33; + this.e10 += ty * this.e30; + this.e11 += ty * this.e31; + this.e12 += ty * this.e32; + this.e13 += ty * this.e33; + this.e20 += tz * this.e30; + this.e21 += tz * this.e31; + this.e22 += tz * this.e32; + this.e23 += tz * this.e33; + + + + + return this; + } + appendTranslationEq(tx,ty,tz) { + let e03 = this.e00 * tx + this.e01 * ty + this.e02 * tz + this.e03; + let e13 = this.e10 * tx + this.e11 * ty + this.e12 * tz + this.e13; + let e23 = this.e20 * tx + this.e21 * ty + this.e22 * tz + this.e23; + let e33 = this.e30 * tx + this.e31 * ty + this.e32 * tz + this.e33; + + + + + this.e03 = e03; + + + + + this.e13 = e13; + + + + + this.e23 = e23; + + + + + this.e33 = e33; + return this; + } + transpose() { + return new oimo.common.Mat4(this.e00,this.e10,this.e20,this.e30,this.e01,this.e11,this.e21,this.e31,this.e02,this.e12,this.e22,this.e32,this.e03,this.e13,this.e23,this.e33); + } + transposeEq() { + let e10 = this.e01; + let e20 = this.e02; + let e21 = this.e12; + let e30 = this.e03; + let e31 = this.e13; + let e32 = this.e23; + + this.e01 = this.e10; + this.e02 = this.e20; + this.e03 = this.e30; + this.e10 = e10; + + this.e12 = this.e21; + this.e13 = this.e31; + this.e20 = e20; + this.e21 = e21; + + this.e23 = this.e32; + this.e30 = e30; + this.e31 = e31; + this.e32 = e32; + + return this; + } + determinant() { + let d23_01 = this.e20 * this.e31 - this.e21 * this.e30; + let d23_02 = this.e20 * this.e32 - this.e22 * this.e30; + let d23_03 = this.e20 * this.e33 - this.e23 * this.e30; + let d23_12 = this.e21 * this.e32 - this.e22 * this.e31; + let d23_13 = this.e21 * this.e33 - this.e23 * this.e31; + let d23_23 = this.e22 * this.e33 - this.e23 * this.e32; + return this.e00 * (this.e11 * d23_23 - this.e12 * d23_13 + this.e13 * d23_12) - this.e01 * (this.e10 * d23_23 - this.e12 * d23_03 + this.e13 * d23_02) + this.e02 * (this.e10 * d23_13 - this.e11 * d23_03 + this.e13 * d23_01) - this.e03 * (this.e10 * d23_12 - this.e11 * d23_02 + this.e12 * d23_01); + } + trace() { + return this.e00 + this.e11 + this.e22 + this.e33; + } + inverse() { + let d01_01 = this.e00 * this.e11 - this.e01 * this.e10; + let d01_02 = this.e00 * this.e12 - this.e02 * this.e10; + let d01_03 = this.e00 * this.e13 - this.e03 * this.e10; + let d01_12 = this.e01 * this.e12 - this.e02 * this.e11; + let d01_13 = this.e01 * this.e13 - this.e03 * this.e11; + let d01_23 = this.e02 * this.e13 - this.e03 * this.e12; + let d23_01 = this.e20 * this.e31 - this.e21 * this.e30; + let d23_02 = this.e20 * this.e32 - this.e22 * this.e30; + let d23_03 = this.e20 * this.e33 - this.e23 * this.e30; + let d23_12 = this.e21 * this.e32 - this.e22 * this.e31; + let d23_13 = this.e21 * this.e33 - this.e23 * this.e31; + let d23_23 = this.e22 * this.e33 - this.e23 * this.e32; + let d00 = this.e11 * d23_23 - this.e12 * d23_13 + this.e13 * d23_12; + let d01 = this.e10 * d23_23 - this.e12 * d23_03 + this.e13 * d23_02; + let d02 = this.e10 * d23_13 - this.e11 * d23_03 + this.e13 * d23_01; + let d03 = this.e10 * d23_12 - this.e11 * d23_02 + this.e12 * d23_01; + let invDet = this.e00 * d00 - this.e01 * d01 + this.e02 * d02 - this.e03 * d03; + if(invDet != 0) { + invDet = 1 / invDet; + } + return new oimo.common.Mat4(d00 * invDet,-(this.e01 * d23_23 - this.e02 * d23_13 + this.e03 * d23_12) * invDet,(this.e31 * d01_23 - this.e32 * d01_13 + this.e33 * d01_12) * invDet,-(this.e21 * d01_23 - this.e22 * d01_13 + this.e23 * d01_12) * invDet,-d01 * invDet,(this.e00 * d23_23 - this.e02 * d23_03 + this.e03 * d23_02) * invDet,-(this.e30 * d01_23 - this.e32 * d01_03 + this.e33 * d01_02) * invDet,(this.e20 * d01_23 - this.e22 * d01_03 + this.e23 * d01_02) * invDet,d02 * invDet,-(this.e00 * d23_13 - this.e01 * d23_03 + this.e03 * d23_01) * invDet,(this.e30 * d01_13 - this.e31 * d01_03 + this.e33 * d01_01) * invDet,-(this.e20 * d01_13 - this.e21 * d01_03 + this.e23 * d01_01) * invDet,-d03 * invDet,(this.e00 * d23_12 - this.e01 * d23_02 + this.e02 * d23_01) * invDet,-(this.e30 * d01_12 - this.e31 * d01_02 + this.e32 * d01_01) * invDet,(this.e20 * d01_12 - this.e21 * d01_02 + this.e22 * d01_01) * invDet); + } + inverseEq() { + let d01_01 = this.e00 * this.e11 - this.e01 * this.e10; + let d01_02 = this.e00 * this.e12 - this.e02 * this.e10; + let d01_03 = this.e00 * this.e13 - this.e03 * this.e10; + let d01_12 = this.e01 * this.e12 - this.e02 * this.e11; + let d01_13 = this.e01 * this.e13 - this.e03 * this.e11; + let d01_23 = this.e02 * this.e13 - this.e03 * this.e12; + let d23_01 = this.e20 * this.e31 - this.e21 * this.e30; + let d23_02 = this.e20 * this.e32 - this.e22 * this.e30; + let d23_03 = this.e20 * this.e33 - this.e23 * this.e30; + let d23_12 = this.e21 * this.e32 - this.e22 * this.e31; + let d23_13 = this.e21 * this.e33 - this.e23 * this.e31; + let d23_23 = this.e22 * this.e33 - this.e23 * this.e32; + let d00 = this.e11 * d23_23 - this.e12 * d23_13 + this.e13 * d23_12; + let d01 = this.e10 * d23_23 - this.e12 * d23_03 + this.e13 * d23_02; + let d02 = this.e10 * d23_13 - this.e11 * d23_03 + this.e13 * d23_01; + let d03 = this.e10 * d23_12 - this.e11 * d23_02 + this.e12 * d23_01; + let invDet = this.e00 * d00 - this.e01 * d01 + this.e02 * d02 - this.e03 * d03; + if(invDet != 0) { + invDet = 1 / invDet; + } + let t11 = (this.e00 * d23_23 - this.e02 * d23_03 + this.e03 * d23_02) * invDet; + let t21 = -(this.e00 * d23_13 - this.e01 * d23_03 + this.e03 * d23_01) * invDet; + let t23 = -(this.e20 * d01_13 - this.e21 * d01_03 + this.e23 * d01_01) * invDet; + let t31 = (this.e00 * d23_12 - this.e01 * d23_02 + this.e02 * d23_01) * invDet; + let t32 = -(this.e30 * d01_12 - this.e31 * d01_02 + this.e32 * d01_01) * invDet; + let t33 = (this.e20 * d01_12 - this.e21 * d01_02 + this.e22 * d01_01) * invDet; + this.e00 = d00 * invDet; + this.e01 = -(this.e01 * d23_23 - this.e02 * d23_13 + this.e03 * d23_12) * invDet; + this.e02 = (this.e31 * d01_23 - this.e32 * d01_13 + this.e33 * d01_12) * invDet; + this.e03 = -(this.e21 * d01_23 - this.e22 * d01_13 + this.e23 * d01_12) * invDet; + this.e10 = -d01 * invDet; + this.e11 = t11; + this.e12 = -(this.e30 * d01_23 - this.e32 * d01_03 + this.e33 * d01_02) * invDet; + this.e13 = (this.e20 * d01_23 - this.e22 * d01_03 + this.e23 * d01_02) * invDet; + this.e20 = d02 * invDet; + this.e21 = t21; + this.e22 = (this.e30 * d01_13 - this.e31 * d01_03 + this.e33 * d01_01) * invDet; + this.e23 = t23; + this.e30 = -d03 * invDet; + this.e31 = t31; + this.e32 = t32; + this.e33 = t33; + return this; + } + lookAt(eyeX,eyeY,eyeZ,atX,atY,atZ,upX,upY,upZ) { + let zx = eyeX - atX; + let zy = eyeY - atY; + let zz = eyeZ - atZ; + let tmp = 1 / Math.sqrt(zx * zx + zy * zy + zz * zz); + zx *= tmp; + zy *= tmp; + zz *= tmp; + let xx = upY * zz - upZ * zy; + let xy = upZ * zx - upX * zz; + let xz = upX * zy - upY * zx; + tmp = 1 / Math.sqrt(xx * xx + xy * xy + xz * xz); + xx *= tmp; + xy *= tmp; + xz *= tmp; + let yx = zy * xz - zz * xy; + let yy = zz * xx - zx * xz; + let yz = zx * xy - zy * xx; + this.e00 = xx; + this.e01 = xy; + this.e02 = xz; + this.e03 = -(xx * eyeX + xy * eyeY + xz * eyeZ); + this.e10 = yx; + this.e11 = yy; + this.e12 = yz; + this.e13 = -(yx * eyeX + yy * eyeY + yz * eyeZ); + this.e20 = zx; + this.e21 = zy; + this.e22 = zz; + this.e23 = -(zx * eyeX + zy * eyeY + zz * eyeZ); + this.e30 = 0; + this.e31 = 0; + this.e32 = 0; + this.e33 = 1; + return this; + } + perspective(fovY,aspect,near,far) { + let h = 1 / Math.tan(fovY * 0.5); + let fnf = far / (near - far); + this.e00 = h / aspect; + this.e01 = 0; + this.e02 = 0; + this.e03 = 0; + this.e10 = 0; + this.e11 = h; + this.e12 = 0; + this.e13 = 0; + this.e20 = 0; + this.e21 = 0; + this.e22 = fnf; + this.e23 = near * fnf; + this.e30 = 0; + this.e31 = 0; + this.e32 = -1; + this.e33 = 0; + return this; + } + ortho(width,height,near,far) { + let nf = 1 / (near - far); + this.e00 = 2 / width; + this.e01 = 0; + this.e02 = 0; + this.e03 = 0; + this.e10 = 0; + this.e11 = 2 / height; + this.e12 = 0; + this.e13 = 0; + this.e20 = 0; + this.e21 = 0; + this.e22 = nf; + this.e23 = near * nf; + this.e30 = 0; + this.e31 = 0; + this.e32 = 0; + this.e33 = 1; + return this; + } + toArray(columnMajor) { + if(columnMajor == null) { + columnMajor = false; + } + if(columnMajor) { + return [this.e00,this.e10,this.e20,this.e30,this.e01,this.e11,this.e21,this.e31,this.e02,this.e12,this.e22,this.e32,this.e03,this.e13,this.e23,this.e33]; + } else { + return [this.e00,this.e01,this.e02,this.e03,this.e10,this.e11,this.e12,this.e13,this.e20,this.e21,this.e22,this.e23,this.e30,this.e31,this.e32,this.e33]; + } + } + copyFrom(m) { + this.e00 = m.e00; + this.e01 = m.e01; + this.e02 = m.e02; + this.e03 = m.e03; + this.e10 = m.e10; + this.e11 = m.e11; + this.e12 = m.e12; + this.e13 = m.e13; + this.e20 = m.e20; + this.e21 = m.e21; + this.e22 = m.e22; + this.e23 = m.e23; + this.e30 = m.e30; + this.e31 = m.e31; + this.e32 = m.e32; + this.e33 = m.e33; + return this; + } + fromMat3(m) { + this.e00 = m.e00; + this.e01 = m.e01; + this.e02 = m.e02; + this.e03 = 0; + this.e10 = m.e10; + this.e11 = m.e11; + this.e12 = m.e12; + this.e13 = 0; + this.e20 = m.e20; + this.e21 = m.e21; + this.e22 = m.e22; + this.e23 = 0; + this.e30 = 0; + this.e31 = 0; + this.e32 = 0; + this.e33 = 1; + return this; + } + fromTransform(transform) { + this.e00 = transform._rotation00; + this.e01 = transform._rotation01; + this.e02 = transform._rotation02; + this.e10 = transform._rotation10; + this.e11 = transform._rotation11; + this.e12 = transform._rotation12; + this.e20 = transform._rotation20; + this.e21 = transform._rotation21; + this.e22 = transform._rotation22; + this.e03 = transform._positionX; + this.e13 = transform._positionY; + this.e23 = transform._positionZ; + this.e30 = 0; + this.e31 = 0; + this.e32 = 0; + this.e33 = 1; + return this; + } + clone() { + return new oimo.common.Mat4(this.e00,this.e01,this.e02,this.e03,this.e10,this.e11,this.e12,this.e13,this.e20,this.e21,this.e22,this.e23,this.e30,this.e31,this.e32,this.e33); + } + toString() { + return "Mat4[" + (this.e00 > 0 ? (this.e00 * 10000000 + 0.5 | 0) / 10000000 : (this.e00 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e01 > 0 ? (this.e01 * 10000000 + 0.5 | 0) / 10000000 : (this.e01 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e02 > 0 ? (this.e02 * 10000000 + 0.5 | 0) / 10000000 : (this.e02 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e03 > 0 ? (this.e03 * 10000000 + 0.5 | 0) / 10000000 : (this.e03 * 10000000 - 0.5 | 0) / 10000000) + ",\n" + " " + (this.e10 > 0 ? (this.e10 * 10000000 + 0.5 | 0) / 10000000 : (this.e10 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e11 > 0 ? (this.e11 * 10000000 + 0.5 | 0) / 10000000 : (this.e11 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e12 > 0 ? (this.e12 * 10000000 + 0.5 | 0) / 10000000 : (this.e12 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e13 > 0 ? (this.e13 * 10000000 + 0.5 | 0) / 10000000 : (this.e13 * 10000000 - 0.5 | 0) / 10000000) + ",\n" + " " + (this.e20 > 0 ? (this.e20 * 10000000 + 0.5 | 0) / 10000000 : (this.e20 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e21 > 0 ? (this.e21 * 10000000 + 0.5 | 0) / 10000000 : (this.e21 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e22 > 0 ? (this.e22 * 10000000 + 0.5 | 0) / 10000000 : (this.e22 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e23 > 0 ? (this.e23 * 10000000 + 0.5 | 0) / 10000000 : (this.e23 * 10000000 - 0.5 | 0) / 10000000) + ",\n" + " " + (this.e30 > 0 ? (this.e30 * 10000000 + 0.5 | 0) / 10000000 : (this.e30 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e31 > 0 ? (this.e31 * 10000000 + 0.5 | 0) / 10000000 : (this.e31 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e32 > 0 ? (this.e32 * 10000000 + 0.5 | 0) / 10000000 : (this.e32 * 10000000 - 0.5 | 0) / 10000000) + ", " + (this.e33 > 0 ? (this.e33 * 10000000 + 0.5 | 0) / 10000000 : (this.e33 * 10000000 - 0.5 | 0) / 10000000) + "]"; + } +} +oimo.common.MathUtil = class oimo_common_MathUtil { + static abs(x) { + if(x > 0) { + return x; + } else { + return -x; + } + } + static sin(x) { + return Math.sin(x); + } + static cos(x) { + return Math.cos(x); + } + static tan(x) { + return Math.tan(x); + } + static asin(x) { + return Math.asin(x); + } + static acos(x) { + return Math.acos(x); + } + static atan(x) { + return Math.atan(x); + } + static safeAsin(x) { + if(x <= -1) { + return -1.570796326794895; + } + if(x >= 1) { + return 1.570796326794895; + } + return Math.asin(x); + } + static safeAcos(x) { + if(x <= -1) { + return 3.14159265358979; + } + if(x >= 1) { + return 0; + } + return Math.acos(x); + } + static atan2(y,x) { + return Math.atan2(y,x); + } + static sqrt(x) { + return Math.sqrt(x); + } + static clamp(x,min,max) { + if(x < min) { + return min; + } else if(x > max) { + return max; + } else { + return x; + } + } + static rand() { + return Math.random(); + } + static randIn(min,max) { + return min + Math.random() * (max - min); + } + static randVec3In(min,max) { + return new oimo.common.Vec3(min + Math.random() * (max - min),min + Math.random() * (max - min),min + Math.random() * (max - min)); + } + static randVec3() { + return new oimo.common.Vec3(-1 + Math.random() * 2,-1 + Math.random() * 2,-1 + Math.random() * 2); + } +} +oimo.common.Pool = class oimo_common_Pool { + constructor() { + this.stackVec3 = new Array(256); + this.sizeVec3 = 0; + this.stackMat3 = new Array(256); + this.sizeMat3 = 0; + this.stackMat4 = new Array(256); + this.sizeMat4 = 0; + this.stackQuat = new Array(256); + this.sizeQuat = 0; + } + vec3() { + if(this.sizeVec3 == 0) { + return new oimo.common.Vec3(); + } else { + return this.stackVec3[--this.sizeVec3]; + } + } + mat3() { + if(this.sizeMat3 == 0) { + return new oimo.common.Mat3(); + } else { + return this.stackMat3[--this.sizeMat3]; + } + } + mat4() { + if(this.sizeMat4 == 0) { + return new oimo.common.Mat4(); + } else { + return this.stackMat4[--this.sizeMat4]; + } + } + quat() { + if(this.sizeQuat == 0) { + return new oimo.common.Quat(); + } else { + return this.stackQuat[--this.sizeQuat]; + } + } + dispose(vec3,mat3,mat4,quat) { + if(vec3 != null) { + vec3.zero(); + if(this.sizeVec3 == this.stackVec3.length) { + let newArray = new Array(this.sizeVec3 << 1); + let _g = 0; + let _g1 = this.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackVec3[i]; + this.stackVec3[i] = null; + } + this.stackVec3 = newArray; + } + this.stackVec3[this.sizeVec3++] = vec3; + } + if(mat3 != null) { + mat3.e00 = 1; + mat3.e01 = 0; + mat3.e02 = 0; + mat3.e10 = 0; + mat3.e11 = 1; + mat3.e12 = 0; + mat3.e20 = 0; + mat3.e21 = 0; + mat3.e22 = 1; + if(this.sizeMat3 == this.stackMat3.length) { + let newArray = new Array(this.sizeMat3 << 1); + let _g = 0; + let _g1 = this.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackMat3[i]; + this.stackMat3[i] = null; + } + this.stackMat3 = newArray; + } + this.stackMat3[this.sizeMat3++] = mat3; + } + if(mat4 != null) { + mat4.e00 = 1; + mat4.e01 = 0; + mat4.e02 = 0; + mat4.e03 = 0; + mat4.e10 = 0; + mat4.e11 = 1; + mat4.e12 = 0; + mat4.e13 = 0; + mat4.e20 = 0; + mat4.e21 = 0; + mat4.e22 = 1; + mat4.e23 = 0; + mat4.e30 = 0; + mat4.e31 = 0; + mat4.e32 = 0; + mat4.e33 = 1; + if(this.sizeMat4 == this.stackMat4.length) { + let newArray = new Array(this.sizeMat4 << 1); + let _g = 0; + let _g1 = this.sizeMat4; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackMat4[i]; + this.stackMat4[i] = null; + } + this.stackMat4 = newArray; + } + this.stackMat4[this.sizeMat4++] = mat4; + } + if(quat != null) { + quat.x = 0; + quat.y = 0; + quat.z = 0; + quat.w = 1; + if(this.sizeQuat == this.stackQuat.length) { + let newArray = new Array(this.sizeQuat << 1); + let _g = 0; + let _g1 = this.sizeQuat; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackQuat[i]; + this.stackQuat[i] = null; + } + this.stackQuat = newArray; + } + this.stackQuat[this.sizeQuat++] = quat; + } + } + disposeVec3(v) { + v.zero(); + if(this.sizeVec3 == this.stackVec3.length) { + let newArray = new Array(this.sizeVec3 << 1); + let _g = 0; + let _g1 = this.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackVec3[i]; + this.stackVec3[i] = null; + } + this.stackVec3 = newArray; + } + this.stackVec3[this.sizeVec3++] = v; + } + disposeMat3(m) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(this.sizeMat3 == this.stackMat3.length) { + let newArray = new Array(this.sizeMat3 << 1); + let _g = 0; + let _g1 = this.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackMat3[i]; + this.stackMat3[i] = null; + } + this.stackMat3 = newArray; + } + this.stackMat3[this.sizeMat3++] = m; + } + disposeMat4(m) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e03 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e13 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + m.e23 = 0; + m.e30 = 0; + m.e31 = 0; + m.e32 = 0; + m.e33 = 1; + if(this.sizeMat4 == this.stackMat4.length) { + let newArray = new Array(this.sizeMat4 << 1); + let _g = 0; + let _g1 = this.sizeMat4; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackMat4[i]; + this.stackMat4[i] = null; + } + this.stackMat4 = newArray; + } + this.stackMat4[this.sizeMat4++] = m; + } + disposeQuat(q) { + q.x = 0; + q.y = 0; + q.z = 0; + q.w = 1; + if(this.sizeQuat == this.stackQuat.length) { + let newArray = new Array(this.sizeQuat << 1); + let _g = 0; + let _g1 = this.sizeQuat; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.stackQuat[i]; + this.stackQuat[i] = null; + } + this.stackQuat = newArray; + } + this.stackQuat[this.sizeQuat++] = q; + } +} +oimo.common.Quat = class oimo_common_Quat { + constructor(x,y,z,w) { + if(w == null) { + w = 1; + } + if(z == null) { + z = 0; + } + if(y == null) { + y = 0; + } + if(x == null) { + x = 0; + } + this.x = x; + this.y = y; + this.z = z; + this.w = w; + oimo.common.Quat.numCreations++; + } + identity() { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 1; + return this; + } + init(x,y,z,w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + add(q) { + return new oimo.common.Quat(this.x + q.x,this.y + q.y,this.z + q.z,this.w + q.w); + } + sub(q) { + return new oimo.common.Quat(this.x - q.x,this.y - q.y,this.z - q.z,this.w - q.w); + } + scale(s) { + return new oimo.common.Quat(this.x * s,this.y * s,this.z * s,this.w * s); + } + addEq(q) { + this.x += q.x; + this.y += q.y; + this.z += q.z; + this.w += q.w; + return this; + } + subEq(q) { + this.x -= q.x; + this.y -= q.y; + this.z -= q.z; + this.w -= q.w; + return this; + } + scaleEq(s) { + this.x *= s; + this.y *= s; + this.z *= s; + this.w *= s; + return this; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + dot(q) { + return this.x * q.x + this.y * q.y + this.z * q.z + this.w * q.w; + } + normalized() { + let invLen = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + if(invLen > 0) { + invLen = 1 / invLen; + } + return new oimo.common.Quat(this.x * invLen,this.y * invLen,this.z * invLen,this.w * invLen); + } + normalize() { + let invLen = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + if(invLen > 0) { + invLen = 1 / invLen; + } + this.x *= invLen; + this.y *= invLen; + this.z *= invLen; + this.w *= invLen; + return this; + } + setArc(v1,v2) { + let x1 = v1.x; + let y1 = v1.y; + let z1 = v1.z; + let x2 = v2.x; + let y2 = v2.y; + let z2 = v2.z; + let d = x1 * x2 + y1 * y2 + z1 * z2; + this.w = Math.sqrt((1 + d) * 0.5); + if(this.w == 0) { + x2 = x1 * x1; + y2 = y1 * y1; + z2 = z1 * z1; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + this.x = 0; + this.y = z1 * d; + this.z = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this.z = 0; + this.x = y1 * d; + this.y = -x1 * d; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + this.y = 0; + this.z = x1 * d; + this.x = -z1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this.z = 0; + this.x = y1 * d; + this.y = -x1 * d; + } + return this; + } + d = 0.5 / this.w; + this.x = (y1 * z2 - z1 * y2) * d; + this.y = (z1 * x2 - x1 * z2) * d; + this.z = (x1 * y2 - y1 * x2) * d; + return this; + } + slerp(q,t) { + let qx; + let qy; + let qz; + let qw; + let d = this.x * q.x + this.y * q.y + this.z * q.z + this.w * q.w; + if(d < 0) { + d = -d; + qx = -q.x; + qy = -q.y; + qz = -q.z; + qw = -q.w; + } else { + qx = q.x; + qy = q.y; + qz = q.z; + qw = q.w; + } + if(d > 0.999999) { + let _this = new oimo.common.Quat(this.x + (qx - this.x) * t,this.y + (qy - this.y) * t,this.z + (qz - this.z) * t,this.w + (qw - this.w) * t); + let invLen = Math.sqrt(_this.x * _this.x + _this.y * _this.y + _this.z * _this.z + _this.w * _this.w); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this.x *= invLen; + _this.y *= invLen; + _this.z *= invLen; + _this.w *= invLen; + return _this; + } + let theta = t * Math.acos(d); + qx -= this.x * d; + qy -= this.y * d; + qz -= this.z * d; + qw -= this.w * d; + let invLen = 1 / Math.sqrt(qx * qx + qy * qy + qz * qz + qw * qw); + qx *= invLen; + qy *= invLen; + qz *= invLen; + qw *= invLen; + let sin = Math.sin(theta); + let cos = Math.cos(theta); + return new oimo.common.Quat(this.x * cos + qx * sin,this.y * cos + qy * sin,this.z * cos + qz * sin,this.w * cos + qw * sin); + } + copyFrom(q) { + this.x = q.x; + this.y = q.y; + this.z = q.z; + this.w = q.w; + return this; + } + clone() { + return new oimo.common.Quat(this.x,this.y,this.z,this.w); + } + fromMat3(m) { + let e00 = m.e00; + let e11 = m.e11; + let e22 = m.e22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + this.w = 0.5 * s; + s = 0.5 / s; + this.x = (m.e21 - m.e12) * s; + this.y = (m.e02 - m.e20) * s; + this.z = (m.e10 - m.e01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + this.x = 0.5 * s; + s = 0.5 / s; + this.y = (m.e01 + m.e10) * s; + this.z = (m.e02 + m.e20) * s; + this.w = (m.e21 - m.e12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + this.z = 0.5 * s; + s = 0.5 / s; + this.x = (m.e02 + m.e20) * s; + this.y = (m.e12 + m.e21) * s; + this.w = (m.e10 - m.e01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + this.y = 0.5 * s; + s = 0.5 / s; + this.x = (m.e01 + m.e10) * s; + this.z = (m.e12 + m.e21) * s; + this.w = (m.e02 - m.e20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + this.z = 0.5 * s; + s = 0.5 / s; + this.x = (m.e02 + m.e20) * s; + this.y = (m.e12 + m.e21) * s; + this.w = (m.e10 - m.e01) * s; + } + return this; + } + toMat3() { + let _this = new oimo.common.Mat3(); + let x = this.x; + let y = this.y; + let z = this.z; + let w = this.w; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + _this.e00 = 1 - yy - zz; + _this.e01 = xy - wz; + _this.e02 = xz + wy; + _this.e10 = xy + wz; + _this.e11 = 1 - xx - zz; + _this.e12 = yz - wx; + _this.e20 = xz - wy; + _this.e21 = yz + wx; + _this.e22 = 1 - xx - yy; + return _this; + } + toString() { + return "Quat[" + (this.x > 0 ? (this.x * 10000000 + 0.5 | 0) / 10000000 : (this.x * 10000000 - 0.5 | 0) / 10000000) + " i,\n" + " " + (this.y > 0 ? (this.y * 10000000 + 0.5 | 0) / 10000000 : (this.y * 10000000 - 0.5 | 0) / 10000000) + " j,\n" + " " + (this.z > 0 ? (this.z * 10000000 + 0.5 | 0) / 10000000 : (this.z * 10000000 - 0.5 | 0) / 10000000) + " k,\n" + " " + (this.w > 0 ? (this.w * 10000000 + 0.5 | 0) / 10000000 : (this.w * 10000000 - 0.5 | 0) / 10000000) + "]"; + } +} +if(!oimo.dynamics) oimo.dynamics = {}; +oimo.dynamics.Contact = class oimo_dynamics_Contact { + constructor() { + this._next = null; + this._prev = null; + this._link1 = new oimo.dynamics.ContactLink(); + this._link2 = new oimo.dynamics.ContactLink(); + this._s1 = null; + this._s2 = null; + this._b1 = null; + this._b2 = null; + this._detector = null; + this._cachedDetectorData = new oimo.collision.narrowphase.detector.CachedDetectorData(); + this._detectorResult = new oimo.collision.narrowphase.DetectorResult(); + this._latest = false; + this._shouldBeSkipped = false; + this._manifold = new oimo.dynamics.constraint.contact.Manifold(); + this._updater = new oimo.dynamics.constraint.contact.ManifoldUpdater(this._manifold); + this._contactConstraint = new oimo.dynamics.constraint.contact.ContactConstraint(this._manifold); + this._touching = false; + } + _updateManifold() { + if(this._detector == null) { + return; + } + let ptouching = this._touching; + let result = this._detectorResult; + this._detector.detect(result,this._s1._geom,this._s2._geom,this._s1._transform,this._s2._transform,this._cachedDetectorData); + this._touching = result.numPoints > 0; + if(this._touching) { + this._manifold._buildBasis(result.normal); + if(result.getMaxDepth() > oimo.common.Setting.contactUseAlternativePositionCorrectionAlgorithmDepthThreshold) { + this._contactConstraint._positionCorrectionAlgorithm = oimo.common.Setting.alternativeContactPositionCorrectionAlgorithm; + } else { + this._contactConstraint._positionCorrectionAlgorithm = oimo.common.Setting.defaultContactPositionCorrectionAlgorithm; + } + if(result.incremental) { + this._updater.incrementalUpdate(result,this._b1._transform,this._b2._transform); + } else { + this._updater.totalUpdate(result,this._b1._transform,this._b2._transform); + } + } else { + this._manifold._clear(); + } + if(this._touching && !ptouching) { + let cc1 = this._s1._contactCallback; + let cc2 = this._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.beginContact(this); + } + if(cc2 != null) { + cc2.beginContact(this); + } + } + if(!this._touching && ptouching) { + let cc1 = this._s1._contactCallback; + let cc2 = this._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.endContact(this); + } + if(cc2 != null) { + cc2.endContact(this); + } + } + if(this._touching) { + let cc1 = this._s1._contactCallback; + let cc2 = this._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.preSolve(this); + } + if(cc2 != null) { + cc2.preSolve(this); + } + } + } + _postSolve() { + let cc1 = this._s1._contactCallback; + let cc2 = this._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.postSolve(this); + } + if(cc2 != null) { + cc2.postSolve(this); + } + } + getShape1() { + return this._s1; + } + getShape2() { + return this._s2; + } + isTouching() { + return this._touching; + } + getManifold() { + return this._manifold; + } + getContactConstraint() { + return this._contactConstraint; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.ContactLink = class oimo_dynamics_ContactLink { + constructor() { + this._prev = null; + this._next = null; + this._contact = null; + this._other = null; + } + getContact() { + return this._contact; + } + getOther() { + return this._other; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.ContactManager = class oimo_dynamics_ContactManager { + constructor(broadPhase) { + this._broadPhase = broadPhase; + this._collisionMatrix = new oimo.collision.narrowphase.CollisionMatrix(); + this._numContacts = 0; + } + createContacts() { + let pp = this._broadPhase._proxyPairList; + while(pp != null) { + let n = pp._next; + while(true) { + let s1; + let s2; + if(pp._p1._id < pp._p2._id) { + s1 = pp._p1.userData; + s2 = pp._p2.userData; + } else { + s1 = pp._p2.userData; + s2 = pp._p1.userData; + } + if(!this.shouldCollide(s1,s2)) { + break; + } + let b1 = s1._rigidBody; + let b2 = s2._rigidBody; + let l; + if(b1._numContactLinks < b2._numContactLinks) { + l = b1._contactLinkList; + } else { + l = b2._contactLinkList; + } + let id1 = s1._id; + let id2 = s2._id; + let found = false; + while(l != null) { + let c = l._contact; + if(c._s1._id == id1 && c._s2._id == id2) { + c._latest = true; + found = true; + break; + } + l = l._next; + } + if(!found) { + let first = this._contactPool; + if(first != null) { + this._contactPool = first._next; + first._next = null; + } else { + first = new oimo.dynamics.Contact(); + } + let c = first; + if(this._contactList == null) { + this._contactList = c; + this._contactListLast = c; + } else { + this._contactListLast._next = c; + c._prev = this._contactListLast; + this._contactListLast = c; + } + c._latest = true; + let detector = this._collisionMatrix.detectors[s1._geom._type][s2._geom._type]; + c._s1 = s1; + c._s2 = s2; + c._b1 = s1._rigidBody; + c._b2 = s2._rigidBody; + c._touching = false; + if(c._b1._contactLinkList == null) { + c._b1._contactLinkList = c._link1; + c._b1._contactLinkListLast = c._link1; + } else { + c._b1._contactLinkListLast._next = c._link1; + c._link1._prev = c._b1._contactLinkListLast; + c._b1._contactLinkListLast = c._link1; + } + if(c._b2._contactLinkList == null) { + c._b2._contactLinkList = c._link2; + c._b2._contactLinkListLast = c._link2; + } else { + c._b2._contactLinkListLast._next = c._link2; + c._link2._prev = c._b2._contactLinkListLast; + c._b2._contactLinkListLast = c._link2; + } + c._b1._numContactLinks++; + c._b2._numContactLinks++; + c._link1._other = c._b2; + c._link2._other = c._b1; + c._link1._contact = c; + c._link2._contact = c; + c._detector = detector; + let _this = c._contactConstraint; + _this._s1 = s1; + _this._s2 = s2; + _this._b1 = _this._s1._rigidBody; + _this._b2 = _this._s2._rigidBody; + _this._tf1 = _this._b1._transform; + _this._tf2 = _this._b2._transform; + this._numContacts++; + } + break; + } + pp = n; + } + } + destroyOutdatedContacts() { + let incremental = this._broadPhase._incremental; + let c = this._contactList; + while(c != null) { + let n = c._next; + while(true) { + if(c._latest) { + c._latest = false; + c._shouldBeSkipped = false; + break; + } + if(!incremental) { + let prev = c._prev; + let next = c._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(c == this._contactList) { + this._contactList = this._contactList._next; + } + if(c == this._contactListLast) { + this._contactListLast = this._contactListLast._prev; + } + c._next = null; + c._prev = null; + if(c._touching) { + let cc1 = c._s1._contactCallback; + let cc2 = c._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.endContact(c); + } + if(cc2 != null) { + cc2.endContact(c); + } + } + let prev1 = c._link1._prev; + let next1 = c._link1._next; + if(prev1 != null) { + prev1._next = next1; + } + if(next1 != null) { + next1._prev = prev1; + } + if(c._link1 == c._b1._contactLinkList) { + c._b1._contactLinkList = c._b1._contactLinkList._next; + } + if(c._link1 == c._b1._contactLinkListLast) { + c._b1._contactLinkListLast = c._b1._contactLinkListLast._prev; + } + c._link1._next = null; + c._link1._prev = null; + let prev2 = c._link2._prev; + let next2 = c._link2._next; + if(prev2 != null) { + prev2._next = next2; + } + if(next2 != null) { + next2._prev = prev2; + } + if(c._link2 == c._b2._contactLinkList) { + c._b2._contactLinkList = c._b2._contactLinkList._next; + } + if(c._link2 == c._b2._contactLinkListLast) { + c._b2._contactLinkListLast = c._b2._contactLinkListLast._prev; + } + c._link2._next = null; + c._link2._prev = null; + c._b1._numContactLinks--; + c._b2._numContactLinks--; + c._link1._other = null; + c._link2._other = null; + c._link1._contact = null; + c._link2._contact = null; + c._s1 = null; + c._s2 = null; + c._b1 = null; + c._b2 = null; + c._touching = false; + c._cachedDetectorData._clear(); + c._manifold._clear(); + c._detector = null; + let _this = c._contactConstraint; + _this._s1 = null; + _this._s2 = null; + _this._b1 = null; + _this._b2 = null; + _this._tf1 = null; + _this._tf2 = null; + c._next = this._contactPool; + this._contactPool = c; + this._numContacts--; + break; + } + let s1 = c._s1; + let s2 = c._s2; + let r1 = s1._rigidBody; + let r2 = s2._rigidBody; + if(!(!r1._sleeping && r1._type != 1) && !(!r2._sleeping && r2._type != 1)) { + c._shouldBeSkipped = true; + break; + } + let aabb1 = s1._aabb; + let aabb2 = s2._aabb; + let proxy1 = s1._proxy; + let proxy2 = s2._proxy; + if(!(proxy1._aabbMinX < proxy2._aabbMaxX && proxy1._aabbMaxX > proxy2._aabbMinX && proxy1._aabbMinY < proxy2._aabbMaxY && proxy1._aabbMaxY > proxy2._aabbMinY && proxy1._aabbMinZ < proxy2._aabbMaxZ && proxy1._aabbMaxZ > proxy2._aabbMinZ) || !this.shouldCollide(s1,s2)) { + let prev = c._prev; + let next = c._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(c == this._contactList) { + this._contactList = this._contactList._next; + } + if(c == this._contactListLast) { + this._contactListLast = this._contactListLast._prev; + } + c._next = null; + c._prev = null; + if(c._touching) { + let cc1 = c._s1._contactCallback; + let cc2 = c._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.endContact(c); + } + if(cc2 != null) { + cc2.endContact(c); + } + } + let prev1 = c._link1._prev; + let next1 = c._link1._next; + if(prev1 != null) { + prev1._next = next1; + } + if(next1 != null) { + next1._prev = prev1; + } + if(c._link1 == c._b1._contactLinkList) { + c._b1._contactLinkList = c._b1._contactLinkList._next; + } + if(c._link1 == c._b1._contactLinkListLast) { + c._b1._contactLinkListLast = c._b1._contactLinkListLast._prev; + } + c._link1._next = null; + c._link1._prev = null; + let prev2 = c._link2._prev; + let next2 = c._link2._next; + if(prev2 != null) { + prev2._next = next2; + } + if(next2 != null) { + next2._prev = prev2; + } + if(c._link2 == c._b2._contactLinkList) { + c._b2._contactLinkList = c._b2._contactLinkList._next; + } + if(c._link2 == c._b2._contactLinkListLast) { + c._b2._contactLinkListLast = c._b2._contactLinkListLast._prev; + } + c._link2._next = null; + c._link2._prev = null; + c._b1._numContactLinks--; + c._b2._numContactLinks--; + c._link1._other = null; + c._link2._other = null; + c._link1._contact = null; + c._link2._contact = null; + c._s1 = null; + c._s2 = null; + c._b1 = null; + c._b2 = null; + c._touching = false; + c._cachedDetectorData._clear(); + c._manifold._clear(); + c._detector = null; + let _this = c._contactConstraint; + _this._s1 = null; + _this._s2 = null; + _this._b1 = null; + _this._b2 = null; + _this._tf1 = null; + _this._tf2 = null; + c._next = this._contactPool; + this._contactPool = c; + this._numContacts--; + break; + } + c._shouldBeSkipped = !(aabb1._minX < aabb2._maxX && aabb1._maxX > aabb2._minX && aabb1._minY < aabb2._maxY && aabb1._maxY > aabb2._minY && aabb1._minZ < aabb2._maxZ && aabb1._maxZ > aabb2._minZ); + break; + } + c = n; + } + } + shouldCollide(s1,s2) { + let r1 = s1._rigidBody; + let r2 = s2._rigidBody; + if(r1 == r2) { + return false; + } + if(r1._type != 0 && r2._type != 0) { + return false; + } + if((s1._collisionGroup & s2._collisionMask) == 0 || (s2._collisionGroup & s1._collisionMask) == 0) { + return false; + } + let jl; + let other; + if(r1._numJointLinks < r2._numJointLinks) { + jl = r1._jointLinkList; + other = r2; + } else { + jl = r2._jointLinkList; + other = r1; + } + while(jl != null) { + if(jl._other == other && !jl._joint._allowCollision) { + return false; + } + jl = jl._next; + } + return true; + } + _updateContacts() { + this._broadPhase.collectPairs(); + this.createContacts(); + this.destroyOutdatedContacts(); + } + _postSolve() { + let c = this._contactList; + while(c != null) { + let n = c._next; + if(c._touching) { + c._postSolve(); + } + c = n; + } + } + getNumContacts() { + return this._numContacts; + } + getContactList() { + return this._contactList; + } +} +oimo.dynamics.Island = class oimo_dynamics_Island { + constructor() { + this.rigidBodies = new Array(oimo.common.Setting.islandInitialRigidBodyArraySize); + this.solvers = new Array(oimo.common.Setting.islandInitialConstraintArraySize); + this.solversSi = new Array(oimo.common.Setting.islandInitialConstraintArraySize); + this.solversNgs = new Array(oimo.common.Setting.islandInitialConstraintArraySize); + this.numRigidBodies = 0; + this.numSolvers = 0; + this.numSolversSi = 0; + this.numSolversNgs = 0; + } + _clear() { + while(this.numRigidBodies > 0) this.rigidBodies[--this.numRigidBodies] = null; + while(this.numSolvers > 0) this.solvers[--this.numSolvers] = null; + while(this.numSolversSi > 0) this.solversSi[--this.numSolversSi] = null; + while(this.numSolversNgs > 0) this.solversNgs[--this.numSolversNgs] = null; + } + _addRigidBody(rigidBody) { + if(this.numRigidBodies == this.rigidBodies.length) { + let newArray = new Array(this.numRigidBodies << 1); + let _g = 0; + let _g1 = this.numRigidBodies; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.rigidBodies[i]; + this.rigidBodies[i] = null; + } + this.rigidBodies = newArray; + } + rigidBody._addedToIsland = true; + this.rigidBodies[this.numRigidBodies++] = rigidBody; + } + _addConstraintSolver(solver,positionCorrection) { + if(this.numSolvers == this.solvers.length) { + let newArray = new Array(this.numSolvers << 1); + let _g = 0; + let _g1 = this.numSolvers; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.solvers[i]; + this.solvers[i] = null; + } + this.solvers = newArray; + } + solver._addedToIsland = true; + this.solvers[this.numSolvers++] = solver; + if(positionCorrection == oimo.dynamics.constraint.PositionCorrectionAlgorithm.SPLIT_IMPULSE) { + if(this.numSolversSi == this.solversSi.length) { + let newArray = new Array(this.numSolversSi << 1); + let _g = 0; + let _g1 = this.numSolversSi; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.solversSi[i]; + this.solversSi[i] = null; + } + this.solversSi = newArray; + } + this.solversSi[this.numSolversSi++] = solver; + } + if(positionCorrection == oimo.dynamics.constraint.PositionCorrectionAlgorithm.NGS) { + if(this.numSolversNgs == this.solversNgs.length) { + let newArray = new Array(this.numSolversNgs << 1); + let _g = 0; + let _g1 = this.numSolversNgs; + while(_g < _g1) { + let i = _g++; + newArray[i] = this.solversNgs[i]; + this.solversNgs[i] = null; + } + this.solversNgs = newArray; + } + this.solversNgs[this.numSolversNgs++] = solver; + } + } + _stepSingleRigidBody(timeStep,rb) { + let dt = timeStep.dt; + let dst = rb._ptransform; + let src = rb._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + rb._linearContactImpulseX = 0; + rb._linearContactImpulseY = 0; + rb._linearContactImpulseZ = 0; + rb._angularContactImpulseX = 0; + rb._angularContactImpulseY = 0; + rb._angularContactImpulseZ = 0; + if(rb._autoSleep && rb._velX * rb._velX + rb._velY * rb._velY + rb._velZ * rb._velZ < oimo.common.Setting.sleepingVelocityThreshold * oimo.common.Setting.sleepingVelocityThreshold && rb._angVelX * rb._angVelX + rb._angVelY * rb._angVelY + rb._angVelZ * rb._angVelZ < oimo.common.Setting.sleepingAngularVelocityThreshold * oimo.common.Setting.sleepingAngularVelocityThreshold) { + rb._sleepTime += dt; + if(rb._sleepTime > oimo.common.Setting.sleepingTimeThreshold) { + rb._sleeping = true; + rb._sleepTime = 0; + } + } else { + rb._sleepTime = 0; + } + if(!rb._sleeping) { + if(rb._type == 0) { + let x = dt * rb._linearDamping; + let x2 = x * x; + let linScale = 1 / (1 + x + x2 * (0.5 + x * 0.16666666666666666 + x2 * 0.041666666666666664)); + let x1 = dt * rb._angularDamping; + let x21 = x1 * x1; + let angScale = 1 / (1 + x1 + x21 * (0.5 + x1 * 0.16666666666666666 + x21 * 0.041666666666666664)); + let linAccX; + let linAccY; + let linAccZ; + let angAccX; + let angAccY; + let angAccZ; + linAccX = this.gravityX * rb._gravityScale; + linAccY = this.gravityY * rb._gravityScale; + linAccZ = this.gravityZ * rb._gravityScale; + linAccX += rb._forceX * rb._invMass; + linAccY += rb._forceY * rb._invMass; + linAccZ += rb._forceZ * rb._invMass; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rb._invInertia00 * rb._torqueX + rb._invInertia01 * rb._torqueY + rb._invInertia02 * rb._torqueZ; + __tmp__Y = rb._invInertia10 * rb._torqueX + rb._invInertia11 * rb._torqueY + rb._invInertia12 * rb._torqueZ; + __tmp__Z = rb._invInertia20 * rb._torqueX + rb._invInertia21 * rb._torqueY + rb._invInertia22 * rb._torqueZ; + angAccX = __tmp__X; + angAccY = __tmp__Y; + angAccZ = __tmp__Z; + rb._velX += linAccX * dt; + rb._velY += linAccY * dt; + rb._velZ += linAccZ * dt; + rb._velX *= linScale; + rb._velY *= linScale; + rb._velZ *= linScale; + rb._angVelX += angAccX * dt; + rb._angVelY += angAccY * dt; + rb._angVelZ += angAccZ * dt; + rb._angVelX *= angScale; + rb._angVelY *= angScale; + rb._angVelZ *= angScale; + } + rb._integrate(dt); + let s = rb._shapeList; + while(s != null) { + let n = s._next; + let tf1 = rb._ptransform; + let tf2 = rb._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + } + _step(timeStep,numVelocityIterations,numPositionIterations) { + let dt = timeStep.dt; + let sleepIsland = true; + let _g = 0; + let _g1 = this.numRigidBodies; + while(_g < _g1) { + let rb = this.rigidBodies[_g++]; + let dst = rb._ptransform; + let src = rb._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + rb._linearContactImpulseX = 0; + rb._linearContactImpulseY = 0; + rb._linearContactImpulseZ = 0; + rb._angularContactImpulseX = 0; + rb._angularContactImpulseY = 0; + rb._angularContactImpulseZ = 0; + rb._sleeping = false; + if(rb._autoSleep && rb._velX * rb._velX + rb._velY * rb._velY + rb._velZ * rb._velZ < oimo.common.Setting.sleepingVelocityThreshold * oimo.common.Setting.sleepingVelocityThreshold && rb._angVelX * rb._angVelX + rb._angVelY * rb._angVelY + rb._angVelZ * rb._angVelZ < oimo.common.Setting.sleepingAngularVelocityThreshold * oimo.common.Setting.sleepingAngularVelocityThreshold) { + rb._sleepTime += dt; + } else { + rb._sleepTime = 0; + } + if(rb._sleepTime < oimo.common.Setting.sleepingTimeThreshold) { + sleepIsland = false; + } + if(rb._type == 0) { + let x = dt * rb._linearDamping; + let x2 = x * x; + let linScale = 1 / (1 + x + x2 * (0.5 + x * 0.16666666666666666 + x2 * 0.041666666666666664)); + let x1 = dt * rb._angularDamping; + let x21 = x1 * x1; + let angScale = 1 / (1 + x1 + x21 * (0.5 + x1 * 0.16666666666666666 + x21 * 0.041666666666666664)); + let linAccX; + let linAccY; + let linAccZ; + let angAccX; + let angAccY; + let angAccZ; + linAccX = this.gravityX * rb._gravityScale; + linAccY = this.gravityY * rb._gravityScale; + linAccZ = this.gravityZ * rb._gravityScale; + linAccX += rb._forceX * rb._invMass; + linAccY += rb._forceY * rb._invMass; + linAccZ += rb._forceZ * rb._invMass; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rb._invInertia00 * rb._torqueX + rb._invInertia01 * rb._torqueY + rb._invInertia02 * rb._torqueZ; + __tmp__Y = rb._invInertia10 * rb._torqueX + rb._invInertia11 * rb._torqueY + rb._invInertia12 * rb._torqueZ; + __tmp__Z = rb._invInertia20 * rb._torqueX + rb._invInertia21 * rb._torqueY + rb._invInertia22 * rb._torqueZ; + angAccX = __tmp__X; + angAccY = __tmp__Y; + angAccZ = __tmp__Z; + rb._velX += linAccX * dt; + rb._velY += linAccY * dt; + rb._velZ += linAccZ * dt; + rb._velX *= linScale; + rb._velY *= linScale; + rb._velZ *= linScale; + rb._angVelX += angAccX * dt; + rb._angVelY += angAccY * dt; + rb._angVelZ += angAccZ * dt; + rb._angVelX *= angScale; + rb._angVelY *= angScale; + rb._angVelZ *= angScale; + } + } + if(sleepIsland) { + let _g = 0; + let _g1 = this.numRigidBodies; + while(_g < _g1) { + let rb = this.rigidBodies[_g++]; + rb._sleeping = true; + rb._sleepTime = 0; + } + return; + } + let _g2 = 0; + let _g3 = this.numSolvers; + while(_g2 < _g3) this.solvers[_g2++].preSolveVelocity(timeStep); + let _g4 = 0; + let _g5 = this.numSolvers; + while(_g4 < _g5) this.solvers[_g4++].warmStart(timeStep); + let _g6 = 0; + while(_g6 < numVelocityIterations) { + ++_g6; + let _g = 0; + let _g1 = this.numSolvers; + while(_g < _g1) this.solvers[_g++].solveVelocity(); + } + let _g7 = 0; + let _g8 = this.numSolvers; + while(_g7 < _g8) this.solvers[_g7++].postSolveVelocity(timeStep); + let _g9 = 0; + let _g10 = this.numRigidBodies; + while(_g9 < _g10) this.rigidBodies[_g9++]._integrate(dt); + let _g11 = 0; + let _g12 = this.numSolversSi; + while(_g11 < _g12) this.solversSi[_g11++].preSolvePosition(timeStep); + let _g13 = 0; + while(_g13 < numPositionIterations) { + ++_g13; + let _g = 0; + let _g1 = this.numSolversSi; + while(_g < _g1) this.solversSi[_g++].solvePositionSplitImpulse(); + } + let _g14 = 0; + let _g15 = this.numRigidBodies; + while(_g14 < _g15) this.rigidBodies[_g14++]._integratePseudoVelocity(); + let _g16 = 0; + let _g17 = this.numSolversNgs; + while(_g16 < _g17) this.solversNgs[_g16++].preSolvePosition(timeStep); + let _g18 = 0; + while(_g18 < numPositionIterations) { + ++_g18; + let _g = 0; + let _g1 = this.numSolversNgs; + while(_g < _g1) this.solversNgs[_g++].solvePositionNgs(timeStep); + } + let _g19 = 0; + let _g20 = this.numSolvers; + while(_g19 < _g20) this.solvers[_g19++].postSolve(); + let _g21 = 0; + let _g22 = this.numRigidBodies; + while(_g21 < _g22) { + let rb = this.rigidBodies[_g21++]; + let s = rb._shapeList; + while(s != null) { + let n = s._next; + let tf1 = rb._ptransform; + let tf2 = rb._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + } +} +oimo.dynamics.TimeStep = class oimo_dynamics_TimeStep { + constructor() { + this.dt = 0; + this.invDt = 0; + this.dtRatio = 1; + } +} +oimo.dynamics.World = class oimo_dynamics_World { + constructor(broadPhaseType,gravity) { + if(broadPhaseType == null) { + broadPhaseType = 2; + } + switch(broadPhaseType) { + case 1: + this._broadPhase = new oimo.collision.broadphase.bruteforce.BruteForceBroadPhase(); + break; + case 2: + this._broadPhase = new oimo.collision.broadphase.bvh.BvhBroadPhase(); + break; + } + this._contactManager = new oimo.dynamics.ContactManager(this._broadPhase); + if(gravity == null) { + gravity = new oimo.common.Vec3(0,-9.80665,0); + } + this._gravity = new oimo.common.Vec3(gravity.x,gravity.y,gravity.z); + this._rigidBodyList = null; + this._rigidBodyListLast = null; + this._jointList = null; + this._jointListLast = null; + this._numRigidBodies = 0; + this._numShapes = 0; + this._numJoints = 0; + this._numIslands = 0; + this._numVelocityIterations = 10; + this._numPositionIterations = 5; + this._rayCastWrapper = new oimo.dynamics._World.RayCastWrapper(); + this._convexCastWrapper = new oimo.dynamics._World.ConvexCastWrapper(); + this._aabbTestWrapper = new oimo.dynamics._World.AabbTestWrapper(); + this._island = new oimo.dynamics.Island(); + this._solversInIslands = new Array(oimo.common.Setting.islandInitialConstraintArraySize); + this._rigidBodyStack = new Array(oimo.common.Setting.islandInitialRigidBodyArraySize); + this._timeStep = new oimo.dynamics.TimeStep(); + this._pool = new oimo.common.Pool(); + this._shapeIdCount = 0; + } + _updateContacts() { + let st = Date.now() / 1000; + this._contactManager._updateContacts(); + oimo.dynamics.common.Performance.broadPhaseCollisionTime = (Date.now() / 1000 - st) * 1000; + let st1 = Date.now() / 1000; + let c = this._contactManager._contactList; + while(c != null) { + let n = c._next; + if(!c._shouldBeSkipped) { + c._updateManifold(); + } + c = n; + } + oimo.dynamics.common.Performance.narrowPhaseCollisionTime = (Date.now() / 1000 - st1) * 1000; + } + _solveIslands() { + let st = Date.now() / 1000; + if(oimo.common.Setting.disableSleeping) { + let b = this._rigidBodyList; + while(b != null) { + b._sleeping = false; + b._sleepTime = 0; + b = b._next; + } + } + if(this._rigidBodyStack.length < this._numRigidBodies) { + let newStackSize = this._rigidBodyStack.length << 1; + while(newStackSize < this._numRigidBodies) newStackSize <<= 1; + this._rigidBodyStack = new Array(newStackSize); + } + this._numIslands = 0; + let _this = this._island; + let gravity = this._gravity; + _this.gravityX = gravity.x; + _this.gravityY = gravity.y; + _this.gravityZ = gravity.z; + let b = this._rigidBodyList; + this._numSolversInIslands = 0; + while(b != null) { + let n = b._next; + while(!(b._addedToIsland || b._sleeping || b._type == 1)) { + if(b._numContactLinks == 0 && b._numJointLinks == 0) { + this._island._stepSingleRigidBody(this._timeStep,b); + this._numIslands++; + break; + } + this.buildIsland(b); + this._island._step(this._timeStep,this._numVelocityIterations,this._numPositionIterations); + this._island._clear(); + this._numIslands++; + break; + } + b = n; + } + this._contactManager._postSolve(); + b = this._rigidBodyList; + while(b != null) { + b._addedToIsland = false; + b = b._next; + } + b = this._rigidBodyList; + while(b != null) { + b._forceX = 0; + b._forceY = 0; + b._forceZ = 0; + b._torqueX = 0; + b._torqueY = 0; + b._torqueZ = 0; + b = b._next; + } + while(this._numSolversInIslands > 0) { + this._solversInIslands[--this._numSolversInIslands]._addedToIsland = false; + this._solversInIslands[this._numSolversInIslands] = null; + } + oimo.dynamics.common.Performance.dynamicsTime = (Date.now() / 1000 - st) * 1000; + } + buildIsland(base) { + let stackCount = 1; + this._island._addRigidBody(base); + this._rigidBodyStack[0] = base; + while(stackCount > 0) { + let rb = this._rigidBodyStack[--stackCount]; + this._rigidBodyStack[stackCount] = null; + if(rb._type == 1) { + continue; + } + let cl = rb._contactLinkList; + while(cl != null) { + let n = cl._next; + let cc = cl._contact._contactConstraint; + let ccs = cl._contact._contactConstraint._solver; + if(cc.isTouching() && !ccs._addedToIsland) { + if(this._solversInIslands.length == this._numSolversInIslands) { + let newArray = new Array(this._numSolversInIslands << 1); + let _g = 0; + let _g1 = this._numSolversInIslands; + while(_g < _g1) { + let i = _g++; + newArray[i] = this._solversInIslands[i]; + this._solversInIslands[i] = null; + } + this._solversInIslands = newArray; + } + this._solversInIslands[this._numSolversInIslands++] = ccs; + this._island._addConstraintSolver(ccs,cc._positionCorrectionAlgorithm); + let other = cl._other; + if(!other._addedToIsland) { + this._island._addRigidBody(other); + this._rigidBodyStack[stackCount++] = other; + } + } + cl = n; + } + let jl = rb._jointLinkList; + while(jl != null) { + let n = jl._next; + let j = jl._joint; + let js1 = j._solver; + if(!js1._addedToIsland) { + if(this._solversInIslands.length == this._numSolversInIslands) { + let newArray = new Array(this._numSolversInIslands << 1); + let _g = 0; + let _g1 = this._numSolversInIslands; + while(_g < _g1) { + let i = _g++; + newArray[i] = this._solversInIslands[i]; + this._solversInIslands[i] = null; + } + this._solversInIslands = newArray; + } + this._solversInIslands[this._numSolversInIslands++] = js1; + this._island._addConstraintSolver(js1,j._positionCorrectionAlgorithm); + let other = jl._other; + if(!other._addedToIsland) { + this._island._addRigidBody(other); + this._rigidBodyStack[stackCount++] = other; + } + } + jl = n; + } + } + } + _drawBvh(d,tree) { + if(d.drawBvh) { + this._drawBvhNode(d,tree._root,0,d.style.bvhNodeColor); + } + } + _drawBvhNode(d,node,level,color) { + if(node == null) { + return; + } + if(level >= d.drawBvhMinLevel && level <= d.drawBvhMaxLevel) { + let _this = this._pool; + let min = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let max = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let v = min; + v.x = node._aabbMinX; + v.y = node._aabbMinY; + v.z = node._aabbMinZ; + let v1 = max; + v1.x = node._aabbMaxX; + v1.y = node._aabbMaxY; + v1.z = node._aabbMaxZ; + d.aabb(min,max,color); + let _this2 = this._pool; + if(min != null) { + min.zero(); + if(_this2.sizeVec3 == _this2.stackVec3.length) { + let newArray = new Array(_this2.sizeVec3 << 1); + let _g = 0; + let _g1 = _this2.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this2.stackVec3[i]; + _this2.stackVec3[i] = null; + } + _this2.stackVec3 = newArray; + } + _this2.stackVec3[_this2.sizeVec3++] = min; + } + let _this3 = this._pool; + if(max != null) { + max.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = max; + } + } + this._drawBvhNode(d,node._children[0],level + 1,color); + this._drawBvhNode(d,node._children[1],level + 1,color); + } + _drawRigidBodies(d) { + let style = d.style; + let r = this._rigidBodyList; + while(r != null) { + let n = r._next; + if(d.drawBases) { + let style = d.style; + d.basis(r._transform,style.basisLength,style.basisColorX,style.basisColorY,style.basisColorZ); + } + let shapeColor = null; + let isDynamic = r._type == 0; + if(!isDynamic) { + shapeColor = r._type == 2 ? style.kinematicShapeColor : style.staticShapeColor; + } + let s = r._shapeList; + while(s != null) { + let n = s._next; + if(isDynamic) { + if((s._id & 1) == 0) { + shapeColor = r._sleeping ? style.sleepingShapeColor1 : r._sleepTime > oimo.common.Setting.sleepingTimeThreshold ? style.sleepyShapeColor1 : style.shapeColor1; + } else { + shapeColor = r._sleeping ? style.sleepingShapeColor2 : r._sleepTime > oimo.common.Setting.sleepingTimeThreshold ? style.sleepyShapeColor2 : style.shapeColor2; + } + } + if(d.drawShapes) { + let geom = s._geom; + let tf = s._transform; + switch(geom._type) { + case 0: + d.sphere(tf,geom._radius,shapeColor); + break; + case 1: + let g = geom; + let _this = this._pool; + let hx = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let v = hx; + v.x = g._halfExtentsX; + v.y = g._halfExtentsY; + v.z = g._halfExtentsZ; + d.box(tf,hx,shapeColor); + let _this1 = this._pool; + if(hx != null) { + hx.zero(); + if(_this1.sizeVec3 == _this1.stackVec3.length) { + let newArray = new Array(_this1.sizeVec3 << 1); + let _g = 0; + let _g1 = _this1.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this1.stackVec3[i]; + _this1.stackVec3[i] = null; + } + _this1.stackVec3 = newArray; + } + _this1.stackVec3[_this1.sizeVec3++] = hx; + } + break; + case 2: + let g1 = geom; + d.cylinder(tf,g1._radius,g1._halfHeight,shapeColor); + break; + case 3: + let g2 = geom; + d.cone(tf,g2._radius,g2._halfHeight,shapeColor); + break; + case 4: + let g3 = geom; + d.capsule(tf,g3._radius,g3._halfHeight,shapeColor); + break; + case 5: + let g4 = geom; + let n = g4._numVertices; + let _this2 = this._pool; + let v1 = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this._pool; + let v2 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this._pool; + let v3 = _this4.sizeVec3 == 0 ? new oimo.common.Vec3() : _this4.stackVec3[--_this4.sizeVec3]; + let _this5 = this._pool; + let v12 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + let _this6 = this._pool; + let v13 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + let _this7 = this._pool; + let normal = _this7.sizeVec3 == 0 ? new oimo.common.Vec3() : _this7.stackVec3[--_this7.sizeVec3]; + let _this8 = this._pool; + let m = _this8.sizeMat3 == 0 ? new oimo.common.Mat3() : _this8.stackMat3[--_this8.sizeMat3]; + let _this9 = this._pool; + let o = _this9.sizeVec3 == 0 ? new oimo.common.Vec3() : _this9.stackVec3[--_this9.sizeVec3]; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + let v4 = o; + v4.x = tf._positionX; + v4.y = tf._positionY; + v4.z = tf._positionZ; + let _g = 0; + while(_g < n) { + let i = _g++; + let _this = g4._tmpVertices[i]; + let v = g4._vertices[i]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let y = _this.x * m.e10 + _this.y * m.e11 + _this.z * m.e12; + let z = _this.x * m.e20 + _this.y * m.e21 + _this.z * m.e22; + _this.x = _this.x * m.e00 + _this.y * m.e01 + _this.z * m.e02; + _this.y = y; + _this.z = z; + _this.x += o.x; + _this.y += o.y; + _this.z += o.z; + } + if(n > 30) { + let _g = 0; + while(_g < n) { + let i = _g++; + let v = g4._tmpVertices[i]; + v1.x = v.x; + v1.y = v.y; + v1.z = v.z; + let v3 = g4._tmpVertices[(i + 1) % n]; + v2.x = v3.x; + v2.y = v3.y; + v2.z = v3.z; + d.line(v1,v2,shapeColor); + } + } else if(this._debugDraw.wireframe || n > 10) { + let _g = 0; + while(_g < n) { + let i = _g++; + let v = g4._tmpVertices[i]; + v1.x = v.x; + v1.y = v.y; + v1.z = v.z; + let _g1 = 0; + while(_g1 < i) { + let v = g4._tmpVertices[_g1++]; + v2.x = v.x; + v2.y = v.y; + v2.z = v.z; + d.line(v1,v2,shapeColor); + } + } + } else { + let _g = 0; + while(_g < n) { + let i = _g++; + let v = g4._tmpVertices[i]; + v1.x = v.x; + v1.y = v.y; + v1.z = v.z; + let _g1 = 0; + while(_g1 < i) { + let j = _g1++; + let v = g4._tmpVertices[j]; + v2.x = v.x; + v2.y = v.y; + v2.z = v.z; + let _g = 0; + while(_g < j) { + let v = g4._tmpVertices[_g++]; + v3.x = v.x; + v3.y = v.y; + v3.z = v.z; + v12.x = v2.x; + v12.y = v2.y; + v12.z = v2.z; + let _this = v12; + _this.x -= v1.x; + _this.y -= v1.y; + _this.z -= v1.z; + v13.x = v3.x; + v13.y = v3.y; + v13.z = v3.z; + let _this1 = v13; + _this1.x -= v1.x; + _this1.y -= v1.y; + _this1.z -= v1.z; + normal.x = v12.x; + normal.y = v12.y; + normal.z = v12.z; + let _this2 = normal; + let y = _this2.z * v13.x - _this2.x * v13.z; + let z = _this2.x * v13.y - _this2.y * v13.x; + _this2.x = _this2.y * v13.z - _this2.z * v13.y; + _this2.y = y; + _this2.z = z; + let invLen = Math.sqrt(_this2.x * _this2.x + _this2.y * _this2.y + _this2.z * _this2.z); + if(invLen > 0) { + invLen = 1 / invLen; + } + _this2.x *= invLen; + _this2.y *= invLen; + _this2.z *= invLen; + d.triangle(v1,v2,v3,normal,normal,normal,shapeColor); + normal.x = -normal.x; + normal.y = -normal.y; + normal.z = -normal.z; + d.triangle(v1,v3,v2,normal,normal,normal,shapeColor); + } + } + } + } + let _this10 = this._pool; + if(v1 != null) { + v1.zero(); + if(_this10.sizeVec3 == _this10.stackVec3.length) { + let newArray = new Array(_this10.sizeVec3 << 1); + let _g = 0; + let _g1 = _this10.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this10.stackVec3[i]; + _this10.stackVec3[i] = null; + } + _this10.stackVec3 = newArray; + } + _this10.stackVec3[_this10.sizeVec3++] = v1; + } + let _this11 = this._pool; + if(v2 != null) { + v2.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = v2; + } + let _this12 = this._pool; + if(v3 != null) { + v3.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = v3; + } + let _this13 = this._pool; + if(v12 != null) { + v12.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = v12; + } + let _this14 = this._pool; + if(v13 != null) { + v13.zero(); + if(_this14.sizeVec3 == _this14.stackVec3.length) { + let newArray = new Array(_this14.sizeVec3 << 1); + let _g = 0; + let _g1 = _this14.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackVec3[i]; + _this14.stackVec3[i] = null; + } + _this14.stackVec3 = newArray; + } + _this14.stackVec3[_this14.sizeVec3++] = v13; + } + let _this15 = this._pool; + if(normal != null) { + normal.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = normal; + } + let _this16 = this._pool; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this16.sizeMat3 == _this16.stackMat3.length) { + let newArray = new Array(_this16.sizeMat3 << 1); + let _g = 0; + let _g1 = _this16.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this16.stackMat3[i]; + _this16.stackMat3[i] = null; + } + _this16.stackMat3 = newArray; + } + _this16.stackMat3[_this16.sizeMat3++] = m; + } + let _this17 = this._pool; + if(o != null) { + o.zero(); + if(_this17.sizeVec3 == _this17.stackVec3.length) { + let newArray = new Array(_this17.sizeVec3 << 1); + let _g = 0; + let _g1 = _this17.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this17.stackVec3[i]; + _this17.stackVec3[i] = null; + } + _this17.stackVec3 = newArray; + } + _this17.stackVec3[_this17.sizeVec3++] = o; + } + break; + } + } + if(d.drawAabbs) { + let aabb = s._aabb; + let color = style.aabbColor; + let _this = this._pool; + let min = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let max = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let v = min; + v.x = aabb._minX; + v.y = aabb._minY; + v.z = aabb._minZ; + let v1 = max; + v1.x = aabb._maxX; + v1.y = aabb._maxY; + v1.z = aabb._maxZ; + d.aabb(min,max,color); + let _this2 = this._pool; + if(min != null) { + min.zero(); + if(_this2.sizeVec3 == _this2.stackVec3.length) { + let newArray = new Array(_this2.sizeVec3 << 1); + let _g = 0; + let _g1 = _this2.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this2.stackVec3[i]; + _this2.stackVec3[i] = null; + } + _this2.stackVec3 = newArray; + } + _this2.stackVec3[_this2.sizeVec3++] = min; + } + let _this3 = this._pool; + if(max != null) { + max.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = max; + } + } + s = n; + } + r = n; + } + } + _drawConstraints(d) { + let style = d.style; + if(d.drawPairs || d.drawContacts) { + let c = this._contactManager._contactList; + while(c != null) { + let n = c._next; + if(d.drawPairs) { + let color = style.pairColor; + let _this = this._pool; + let v1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let v2 = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let v = v1; + v.x = c._s1._transform._positionX; + v.y = c._s1._transform._positionY; + v.z = c._s1._transform._positionZ; + let v3 = v2; + v3.x = c._s2._transform._positionX; + v3.y = c._s2._transform._positionY; + v3.z = c._s2._transform._positionZ; + d.line(v1,v2,color); + let _this2 = this._pool; + if(v1 != null) { + v1.zero(); + if(_this2.sizeVec3 == _this2.stackVec3.length) { + let newArray = new Array(_this2.sizeVec3 << 1); + let _g = 0; + let _g1 = _this2.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this2.stackVec3[i]; + _this2.stackVec3[i] = null; + } + _this2.stackVec3 = newArray; + } + _this2.stackVec3[_this2.sizeVec3++] = v1; + } + let _this3 = this._pool; + if(v2 != null) { + v2.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = v2; + } + } + if(d.drawContacts) { + let cc = c._contactConstraint; + let ps = c._contactConstraint._manifold._points; + let _g = 0; + let _g1 = c._contactConstraint._manifold._numPoints; + while(_g < _g1) { + let p = ps[_g++]; + let style = d.style; + let _this = this._pool; + let pos1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let pos2 = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let _this2 = this._pool; + let normal = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this._pool; + let tangent = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this._pool; + let binormal = _this4.sizeVec3 == 0 ? new oimo.common.Vec3() : _this4.stackVec3[--_this4.sizeVec3]; + let v = pos1; + v.x = p._pos1X; + v.y = p._pos1Y; + v.z = p._pos1Z; + let v1 = pos2; + v1.x = p._pos2X; + v1.y = p._pos2Y; + v1.z = p._pos2Z; + let v2 = normal; + v2.x = cc._manifold._normalX; + v2.y = cc._manifold._normalY; + v2.z = cc._manifold._normalZ; + let v3 = tangent; + v3.x = cc._manifold._tangentX; + v3.y = cc._manifold._tangentY; + v3.z = cc._manifold._tangentZ; + let v4 = binormal; + v4.x = cc._manifold._binormalX; + v4.y = cc._manifold._binormalY; + v4.z = cc._manifold._binormalZ; + if(p._disabled) { + d.point(pos1,style.disabledContactColor); + d.point(pos2,style.disabledContactColor); + d.line(pos1,pos2,style.disabledContactColor); + } else if(p._warmStarted) { + let color; + switch(p._id & 3) { + case 0: + color = style.contactColor; + break; + case 1: + color = style.contactColor2; + break; + case 2: + color = style.contactColor3; + break; + default: + color = style.contactColor4; + } + d.point(pos1,color); + d.point(pos2,color); + d.line(pos1,pos2,style.contactColor); + } else { + d.point(pos1,style.newContactColor); + d.point(pos2,style.newContactColor); + d.line(pos1,pos2,style.newContactColor); + } + pos2.x = pos1.x; + pos2.y = pos1.y; + pos2.z = pos1.z; + let _this5 = pos2; + let s = style.contactNormalLength; + _this5.x += normal.x * s; + _this5.y += normal.y * s; + _this5.z += normal.z * s; + d.line(pos1,pos2,style.contactNormalColor); + if(d.drawContactBases) { + pos2.x = pos1.x; + pos2.y = pos1.y; + pos2.z = pos1.z; + let _this = pos2; + let s = style.contactTangentLength; + _this.x += tangent.x * s; + _this.y += tangent.y * s; + _this.z += tangent.z * s; + d.line(pos1,pos2,style.contactTangentColor); + pos2.x = pos1.x; + pos2.y = pos1.y; + pos2.z = pos1.z; + let _this1 = pos2; + let s1 = style.contactBinormalLength; + _this1.x += binormal.x * s1; + _this1.y += binormal.y * s1; + _this1.z += binormal.z * s1; + d.line(pos1,pos2,style.contactBinormalColor); + } + let _this6 = this._pool; + if(pos1 != null) { + pos1.zero(); + if(_this6.sizeVec3 == _this6.stackVec3.length) { + let newArray = new Array(_this6.sizeVec3 << 1); + let _g = 0; + let _g1 = _this6.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this6.stackVec3[i]; + _this6.stackVec3[i] = null; + } + _this6.stackVec3 = newArray; + } + _this6.stackVec3[_this6.sizeVec3++] = pos1; + } + let _this7 = this._pool; + if(pos2 != null) { + pos2.zero(); + if(_this7.sizeVec3 == _this7.stackVec3.length) { + let newArray = new Array(_this7.sizeVec3 << 1); + let _g = 0; + let _g1 = _this7.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this7.stackVec3[i]; + _this7.stackVec3[i] = null; + } + _this7.stackVec3 = newArray; + } + _this7.stackVec3[_this7.sizeVec3++] = pos2; + } + let _this8 = this._pool; + if(normal != null) { + normal.zero(); + if(_this8.sizeVec3 == _this8.stackVec3.length) { + let newArray = new Array(_this8.sizeVec3 << 1); + let _g = 0; + let _g1 = _this8.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this8.stackVec3[i]; + _this8.stackVec3[i] = null; + } + _this8.stackVec3 = newArray; + } + _this8.stackVec3[_this8.sizeVec3++] = normal; + } + let _this9 = this._pool; + if(tangent != null) { + tangent.zero(); + if(_this9.sizeVec3 == _this9.stackVec3.length) { + let newArray = new Array(_this9.sizeVec3 << 1); + let _g = 0; + let _g1 = _this9.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this9.stackVec3[i]; + _this9.stackVec3[i] = null; + } + _this9.stackVec3 = newArray; + } + _this9.stackVec3[_this9.sizeVec3++] = tangent; + } + let _this10 = this._pool; + if(binormal != null) { + binormal.zero(); + if(_this10.sizeVec3 == _this10.stackVec3.length) { + let newArray = new Array(_this10.sizeVec3 << 1); + let _g = 0; + let _g1 = _this10.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this10.stackVec3[i]; + _this10.stackVec3[i] = null; + } + _this10.stackVec3 = newArray; + } + _this10.stackVec3[_this10.sizeVec3++] = binormal; + } + } + } + c = n; + } + } + if(d.drawJoints) { + let j = this._jointList; + while(j != null) { + let n = j._next; + let _this = this._pool; + let p1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let p2 = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let v = p1; + v.x = j._b1._transform._positionX; + v.y = j._b1._transform._positionY; + v.z = j._b1._transform._positionZ; + let v1 = p2; + v1.x = j._b2._transform._positionX; + v1.y = j._b2._transform._positionY; + v1.z = j._b2._transform._positionZ; + let _this2 = this._pool; + let anchor1 = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this._pool; + let anchor2 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this._pool; + let basisX1 = _this4.sizeVec3 == 0 ? new oimo.common.Vec3() : _this4.stackVec3[--_this4.sizeVec3]; + let _this5 = this._pool; + let basisY1 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + let _this6 = this._pool; + let basisZ1 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + let _this7 = this._pool; + let basisX2 = _this7.sizeVec3 == 0 ? new oimo.common.Vec3() : _this7.stackVec3[--_this7.sizeVec3]; + let _this8 = this._pool; + let basisY2 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + let _this9 = this._pool; + let basisZ2 = _this9.sizeVec3 == 0 ? new oimo.common.Vec3() : _this9.stackVec3[--_this9.sizeVec3]; + let v2 = anchor1; + v2.x = j._anchor1X; + v2.y = j._anchor1Y; + v2.z = j._anchor1Z; + let v3 = anchor2; + v3.x = j._anchor2X; + v3.y = j._anchor2Y; + v3.z = j._anchor2Z; + let v4 = basisX1; + v4.x = j._basisX1X; + v4.y = j._basisX1Y; + v4.z = j._basisX1Z; + let v5 = basisY1; + v5.x = j._basisY1X; + v5.y = j._basisY1Y; + v5.z = j._basisY1Z; + let v6 = basisZ1; + v6.x = j._basisZ1X; + v6.y = j._basisZ1Y; + v6.z = j._basisZ1Z; + let v7 = basisX2; + v7.x = j._basisX2X; + v7.y = j._basisX2Y; + v7.z = j._basisX2Z; + let v8 = basisY2; + v8.x = j._basisY2X; + v8.y = j._basisY2Y; + v8.z = j._basisY2Z; + let v9 = basisZ2; + v9.x = j._basisZ2X; + v9.y = j._basisZ2Y; + v9.z = j._basisZ2Z; + d.line(p1,anchor1,d.style.jointLineColor); + d.line(p2,anchor2,d.style.jointLineColor); + if(d.drawJointLimits) { + switch(j._type) { + case 0: + break; + case 1: + let lm = j._lm; + this._drawRotationalLimit(d,anchor1,basisY1,basisZ1,basisY2,d.style.jointRotationalConstraintRadius,lm.lowerLimit,lm.upperLimit,d.style.jointLineColor); + break; + case 2: + let j1 = j; + let color = d.style.jointLineColor; + let rlm = j1._rotLm; + let tlm = j1._translLm; + this._drawRotationalLimit(d,anchor2,basisY1,basisZ1,basisY2,d.style.jointRotationalConstraintRadius,rlm.lowerLimit,rlm.upperLimit,color); + this._drawTranslationalLimit(d,anchor1,basisX1,tlm.lowerLimit,tlm.upperLimit,color); + break; + case 3: + let lm1 = j._lm; + this._drawTranslationalLimit(d,anchor1,basisX1,lm1.lowerLimit,lm1.upperLimit,d.style.jointLineColor); + break; + case 4: + let j2 = j; + let radius = d.style.jointRotationalConstraintRadius; + let color1 = d.style.jointLineColor; + let lm11 = j2._lm1; + let lm2 = j2._lm2; + this._drawRotationalLimit(d,anchor1,basisY1,basisZ1,basisY1,radius,j2._angleX - lm11.upperLimit,j2._angleX - lm11.lowerLimit,color1); + this._drawRotationalLimit(d,anchor2,basisX2,basisY2,basisX2,radius,lm2.lowerLimit - j2._angleZ,lm2.upperLimit - j2._angleZ,color1); + break; + case 5: + let j3 = j; + let radius1 = d.style.jointRotationalConstraintRadius; + let color2 = d.style.jointLineColor; + let lm3 = j3._twistLm; + this._drawRotationalLimit(d,anchor2,basisY2,basisZ2,basisY2,radius1,lm3.lowerLimit - j3._twistAngle,lm3.upperLimit - j3._twistAngle,color2); + this._drawEllipseOnSphere(d,anchor1,basisX1,basisY1,basisZ1,j3._maxSwingAngle1,j3._maxSwingAngle2,radius1,color2); + let _this10 = this._pool; + let _this11 = _this10.sizeVec3 == 0 ? new oimo.common.Vec3() : _this10.stackVec3[--_this10.sizeVec3]; + _this11.x = anchor2.x; + _this11.y = anchor2.y; + _this11.z = anchor2.z; + let _this12 = _this11; + _this12.x += basisX2.x * radius1; + _this12.y += basisX2.y * radius1; + _this12.z += basisX2.z * radius1; + d.line(anchor2,_this12,color2); + let _this13 = this._pool; + if(_this12 != null) { + _this12.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = _this12; + } + break; + case 6: + let j4 = j; + let radius2 = d.style.jointRotationalConstraintRadius; + let color3 = d.style.jointLineColor; + let rxlm = j4._rotLms[0]; + let rylm = j4._rotLms[1]; + let rzlm = j4._rotLms[2]; + this._drawTranslationalLimit3D(d,anchor1,basisX1,basisY1,basisZ1,j4._translLms[0],j4._translLms[1],j4._translLms[2],color3); + let _this14 = this._pool; + let rotYAxis = _this14.sizeVec3 == 0 ? new oimo.common.Vec3() : _this14.stackVec3[--_this14.sizeVec3]; + let v10 = rotYAxis; + v10.x = j4._axisYX; + v10.y = j4._axisYY; + v10.z = j4._axisYZ; + let _this15 = this._pool; + let _this16 = _this15.sizeVec3 == 0 ? new oimo.common.Vec3() : _this15.stackVec3[--_this15.sizeVec3]; + _this16.x = basisX1.x; + _this16.y = basisX1.y; + _this16.z = basisX1.z; + let rotYBasisX = _this16; + let _this17 = this._pool; + let _this18 = _this17.sizeVec3 == 0 ? new oimo.common.Vec3() : _this17.stackVec3[--_this17.sizeVec3]; + _this18.x = basisX1.x; + _this18.y = basisX1.y; + _this18.z = basisX1.z; + let _this19 = _this18; + let y = _this19.z * rotYAxis.x - _this19.x * rotYAxis.z; + let z = _this19.x * rotYAxis.y - _this19.y * rotYAxis.x; + _this19.x = _this19.y * rotYAxis.z - _this19.z * rotYAxis.y; + _this19.y = y; + _this19.z = z; + this._drawRotationalLimit(d,anchor2,basisY1,basisZ1,basisY1,radius2,j4._angleX - rxlm.upperLimit,j4._angleX - rxlm.lowerLimit,color3); + this._drawRotationalLimit(d,anchor2,rotYBasisX,_this19,rotYBasisX,radius2,rylm.lowerLimit - j4._angleY,rylm.upperLimit - j4._angleY,color3); + this._drawRotationalLimit(d,anchor2,basisX2,basisY2,basisX2,radius2,rzlm.lowerLimit - j4._angleZ,rzlm.upperLimit - j4._angleZ,color3); + break; + } + } + d.line(anchor1,anchor2,d.style.jointErrorColor); + let _this20 = this._pool; + if(p1 != null) { + p1.zero(); + if(_this20.sizeVec3 == _this20.stackVec3.length) { + let newArray = new Array(_this20.sizeVec3 << 1); + let _g = 0; + let _g1 = _this20.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this20.stackVec3[i]; + _this20.stackVec3[i] = null; + } + _this20.stackVec3 = newArray; + } + _this20.stackVec3[_this20.sizeVec3++] = p1; + } + let _this21 = this._pool; + if(p2 != null) { + p2.zero(); + if(_this21.sizeVec3 == _this21.stackVec3.length) { + let newArray = new Array(_this21.sizeVec3 << 1); + let _g = 0; + let _g1 = _this21.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this21.stackVec3[i]; + _this21.stackVec3[i] = null; + } + _this21.stackVec3 = newArray; + } + _this21.stackVec3[_this21.sizeVec3++] = p2; + } + let _this22 = this._pool; + if(anchor1 != null) { + anchor1.zero(); + if(_this22.sizeVec3 == _this22.stackVec3.length) { + let newArray = new Array(_this22.sizeVec3 << 1); + let _g = 0; + let _g1 = _this22.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this22.stackVec3[i]; + _this22.stackVec3[i] = null; + } + _this22.stackVec3 = newArray; + } + _this22.stackVec3[_this22.sizeVec3++] = anchor1; + } + let _this23 = this._pool; + if(anchor2 != null) { + anchor2.zero(); + if(_this23.sizeVec3 == _this23.stackVec3.length) { + let newArray = new Array(_this23.sizeVec3 << 1); + let _g = 0; + let _g1 = _this23.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this23.stackVec3[i]; + _this23.stackVec3[i] = null; + } + _this23.stackVec3 = newArray; + } + _this23.stackVec3[_this23.sizeVec3++] = anchor2; + } + let _this24 = this._pool; + if(basisX1 != null) { + basisX1.zero(); + if(_this24.sizeVec3 == _this24.stackVec3.length) { + let newArray = new Array(_this24.sizeVec3 << 1); + let _g = 0; + let _g1 = _this24.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this24.stackVec3[i]; + _this24.stackVec3[i] = null; + } + _this24.stackVec3 = newArray; + } + _this24.stackVec3[_this24.sizeVec3++] = basisX1; + } + let _this25 = this._pool; + if(basisY1 != null) { + basisY1.zero(); + if(_this25.sizeVec3 == _this25.stackVec3.length) { + let newArray = new Array(_this25.sizeVec3 << 1); + let _g = 0; + let _g1 = _this25.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this25.stackVec3[i]; + _this25.stackVec3[i] = null; + } + _this25.stackVec3 = newArray; + } + _this25.stackVec3[_this25.sizeVec3++] = basisY1; + } + let _this26 = this._pool; + if(basisZ1 != null) { + basisZ1.zero(); + if(_this26.sizeVec3 == _this26.stackVec3.length) { + let newArray = new Array(_this26.sizeVec3 << 1); + let _g = 0; + let _g1 = _this26.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this26.stackVec3[i]; + _this26.stackVec3[i] = null; + } + _this26.stackVec3 = newArray; + } + _this26.stackVec3[_this26.sizeVec3++] = basisZ1; + } + let _this27 = this._pool; + if(basisX2 != null) { + basisX2.zero(); + if(_this27.sizeVec3 == _this27.stackVec3.length) { + let newArray = new Array(_this27.sizeVec3 << 1); + let _g = 0; + let _g1 = _this27.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this27.stackVec3[i]; + _this27.stackVec3[i] = null; + } + _this27.stackVec3 = newArray; + } + _this27.stackVec3[_this27.sizeVec3++] = basisX2; + } + let _this28 = this._pool; + if(basisY2 != null) { + basisY2.zero(); + if(_this28.sizeVec3 == _this28.stackVec3.length) { + let newArray = new Array(_this28.sizeVec3 << 1); + let _g = 0; + let _g1 = _this28.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this28.stackVec3[i]; + _this28.stackVec3[i] = null; + } + _this28.stackVec3 = newArray; + } + _this28.stackVec3[_this28.sizeVec3++] = basisY2; + } + let _this29 = this._pool; + if(basisZ2 != null) { + basisZ2.zero(); + if(_this29.sizeVec3 == _this29.stackVec3.length) { + let newArray = new Array(_this29.sizeVec3 << 1); + let _g = 0; + let _g1 = _this29.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this29.stackVec3[i]; + _this29.stackVec3[i] = null; + } + _this29.stackVec3 = newArray; + } + _this29.stackVec3[_this29.sizeVec3++] = basisZ2; + } + j = n; + } + } + } + _drawRotationalLimit(d,center,ex,ey,needle,radius,min,max,color) { + if(min != max) { + let _this = this._pool; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = center.x; + _this1.y = center.y; + _this1.z = center.z; + let _this2 = _this1; + _this2.x += needle.x * radius; + _this2.y += needle.y * radius; + _this2.z += needle.z * radius; + d.line(center,_this2,color); + let _this3 = this._pool; + if(_this2 != null) { + _this2.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = _this2; + } + if(min > max) { + d.ellipse(center,ex,ey,radius,radius,color); + } else { + d.arc(center,ex,ey,radius,radius,min,max,true,color); + } + } + } + _drawTranslationalLimit(d,center,ex,min,max,color) { + if(min < max) { + let _this = this._pool; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = center.x; + _this1.y = center.y; + _this1.z = center.z; + let _this2 = _this1; + _this2.x += ex.x * min; + _this2.y += ex.y * min; + _this2.z += ex.z * min; + let _this3 = this._pool; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = center.x; + _this4.y = center.y; + _this4.z = center.z; + let _this5 = _this4; + _this5.x += ex.x * max; + _this5.y += ex.y * max; + _this5.z += ex.z * max; + d.line(_this2,_this5,color); + let _this6 = this._pool; + if(_this2 != null) { + _this2.zero(); + if(_this6.sizeVec3 == _this6.stackVec3.length) { + let newArray = new Array(_this6.sizeVec3 << 1); + let _g = 0; + let _g1 = _this6.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this6.stackVec3[i]; + _this6.stackVec3[i] = null; + } + _this6.stackVec3 = newArray; + } + _this6.stackVec3[_this6.sizeVec3++] = _this2; + } + let _this7 = this._pool; + if(_this5 != null) { + _this5.zero(); + if(_this7.sizeVec3 == _this7.stackVec3.length) { + let newArray = new Array(_this7.sizeVec3 << 1); + let _g = 0; + let _g1 = _this7.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this7.stackVec3[i]; + _this7.stackVec3[i] = null; + } + _this7.stackVec3 = newArray; + } + _this7.stackVec3[_this7.sizeVec3++] = _this5; + } + } + } + _drawTranslationalLimit3D(d,center,ex,ey,ez,xlm,ylm,zlm,color) { + let minx = xlm.lowerLimit; + let maxx = xlm.upperLimit; + let miny = ylm.lowerLimit; + let maxy = ylm.upperLimit; + let minz = zlm.lowerLimit; + let maxz = zlm.upperLimit; + let _this = this._pool; + if(_this.sizeVec3 == 0) { + new oimo.common.Vec3(); + } else { + --_this.sizeVec3; + } + let _this1 = this._pool; + if(_this1.sizeVec3 == 0) { + new oimo.common.Vec3(); + } else { + --_this1.sizeVec3; + } + let _this2 = this._pool; + let _this3 = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + _this3.x = center.x; + _this3.y = center.y; + _this3.z = center.z; + let _this4 = _this3; + _this4.x += ex.x * minx; + _this4.y += ex.y * minx; + _this4.z += ex.z * minx; + _this4.x += ey.x * miny; + _this4.y += ey.y * miny; + _this4.z += ey.z * miny; + _this4.x += ez.x * minz; + _this4.y += ez.y * minz; + _this4.z += ez.z * minz; + let _this5 = this._pool; + let _this6 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + _this6.x = center.x; + _this6.y = center.y; + _this6.z = center.z; + let _this7 = _this6; + _this7.x += ex.x * minx; + _this7.y += ex.y * minx; + _this7.z += ex.z * minx; + _this7.x += ey.x * miny; + _this7.y += ey.y * miny; + _this7.z += ey.z * miny; + _this7.x += ez.x * maxz; + _this7.y += ez.y * maxz; + _this7.z += ez.z * maxz; + let _this8 = this._pool; + let _this9 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + _this9.x = center.x; + _this9.y = center.y; + _this9.z = center.z; + let _this10 = _this9; + _this10.x += ex.x * minx; + _this10.y += ex.y * minx; + _this10.z += ex.z * minx; + _this10.x += ey.x * maxy; + _this10.y += ey.y * maxy; + _this10.z += ey.z * maxy; + _this10.x += ez.x * minz; + _this10.y += ez.y * minz; + _this10.z += ez.z * minz; + let _this11 = this._pool; + let _this12 = _this11.sizeVec3 == 0 ? new oimo.common.Vec3() : _this11.stackVec3[--_this11.sizeVec3]; + _this12.x = center.x; + _this12.y = center.y; + _this12.z = center.z; + let _this13 = _this12; + _this13.x += ex.x * minx; + _this13.y += ex.y * minx; + _this13.z += ex.z * minx; + _this13.x += ey.x * maxy; + _this13.y += ey.y * maxy; + _this13.z += ey.z * maxy; + _this13.x += ez.x * maxz; + _this13.y += ez.y * maxz; + _this13.z += ez.z * maxz; + let _this14 = this._pool; + let _this15 = _this14.sizeVec3 == 0 ? new oimo.common.Vec3() : _this14.stackVec3[--_this14.sizeVec3]; + _this15.x = center.x; + _this15.y = center.y; + _this15.z = center.z; + let _this16 = _this15; + _this16.x += ex.x * maxx; + _this16.y += ex.y * maxx; + _this16.z += ex.z * maxx; + _this16.x += ey.x * miny; + _this16.y += ey.y * miny; + _this16.z += ey.z * miny; + _this16.x += ez.x * minz; + _this16.y += ez.y * minz; + _this16.z += ez.z * minz; + let _this17 = this._pool; + let _this18 = _this17.sizeVec3 == 0 ? new oimo.common.Vec3() : _this17.stackVec3[--_this17.sizeVec3]; + _this18.x = center.x; + _this18.y = center.y; + _this18.z = center.z; + let _this19 = _this18; + _this19.x += ex.x * maxx; + _this19.y += ex.y * maxx; + _this19.z += ex.z * maxx; + _this19.x += ey.x * miny; + _this19.y += ey.y * miny; + _this19.z += ey.z * miny; + _this19.x += ez.x * maxz; + _this19.y += ez.y * maxz; + _this19.z += ez.z * maxz; + let _this20 = this._pool; + let _this21 = _this20.sizeVec3 == 0 ? new oimo.common.Vec3() : _this20.stackVec3[--_this20.sizeVec3]; + _this21.x = center.x; + _this21.y = center.y; + _this21.z = center.z; + let _this22 = _this21; + _this22.x += ex.x * maxx; + _this22.y += ex.y * maxx; + _this22.z += ex.z * maxx; + _this22.x += ey.x * maxy; + _this22.y += ey.y * maxy; + _this22.z += ey.z * maxy; + _this22.x += ez.x * minz; + _this22.y += ez.y * minz; + _this22.z += ez.z * minz; + let _this23 = this._pool; + let _this24 = _this23.sizeVec3 == 0 ? new oimo.common.Vec3() : _this23.stackVec3[--_this23.sizeVec3]; + _this24.x = center.x; + _this24.y = center.y; + _this24.z = center.z; + let _this25 = _this24; + _this25.x += ex.x * maxx; + _this25.y += ex.y * maxx; + _this25.z += ex.z * maxx; + _this25.x += ey.x * maxy; + _this25.y += ey.y * maxy; + _this25.z += ey.z * maxy; + _this25.x += ez.x * maxz; + _this25.y += ez.y * maxz; + _this25.z += ez.z * maxz; + d.line(_this4,_this16,color); + d.line(_this10,_this22,color); + d.line(_this7,_this19,color); + d.line(_this13,_this25,color); + d.line(_this4,_this10,color); + d.line(_this16,_this22,color); + d.line(_this7,_this13,color); + d.line(_this19,_this25,color); + d.line(_this4,_this7,color); + d.line(_this16,_this19,color); + d.line(_this10,_this13,color); + d.line(_this22,_this25,color); + let _this26 = this._pool; + if(_this4 != null) { + _this4.zero(); + if(_this26.sizeVec3 == _this26.stackVec3.length) { + let newArray = new Array(_this26.sizeVec3 << 1); + let _g = 0; + let _g1 = _this26.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this26.stackVec3[i]; + _this26.stackVec3[i] = null; + } + _this26.stackVec3 = newArray; + } + _this26.stackVec3[_this26.sizeVec3++] = _this4; + } + let _this27 = this._pool; + if(_this7 != null) { + _this7.zero(); + if(_this27.sizeVec3 == _this27.stackVec3.length) { + let newArray = new Array(_this27.sizeVec3 << 1); + let _g = 0; + let _g1 = _this27.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this27.stackVec3[i]; + _this27.stackVec3[i] = null; + } + _this27.stackVec3 = newArray; + } + _this27.stackVec3[_this27.sizeVec3++] = _this7; + } + let _this28 = this._pool; + if(_this10 != null) { + _this10.zero(); + if(_this28.sizeVec3 == _this28.stackVec3.length) { + let newArray = new Array(_this28.sizeVec3 << 1); + let _g = 0; + let _g1 = _this28.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this28.stackVec3[i]; + _this28.stackVec3[i] = null; + } + _this28.stackVec3 = newArray; + } + _this28.stackVec3[_this28.sizeVec3++] = _this10; + } + let _this29 = this._pool; + if(_this13 != null) { + _this13.zero(); + if(_this29.sizeVec3 == _this29.stackVec3.length) { + let newArray = new Array(_this29.sizeVec3 << 1); + let _g = 0; + let _g1 = _this29.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this29.stackVec3[i]; + _this29.stackVec3[i] = null; + } + _this29.stackVec3 = newArray; + } + _this29.stackVec3[_this29.sizeVec3++] = _this13; + } + let _this30 = this._pool; + if(_this16 != null) { + _this16.zero(); + if(_this30.sizeVec3 == _this30.stackVec3.length) { + let newArray = new Array(_this30.sizeVec3 << 1); + let _g = 0; + let _g1 = _this30.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this30.stackVec3[i]; + _this30.stackVec3[i] = null; + } + _this30.stackVec3 = newArray; + } + _this30.stackVec3[_this30.sizeVec3++] = _this16; + } + let _this31 = this._pool; + if(_this19 != null) { + _this19.zero(); + if(_this31.sizeVec3 == _this31.stackVec3.length) { + let newArray = new Array(_this31.sizeVec3 << 1); + let _g = 0; + let _g1 = _this31.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this31.stackVec3[i]; + _this31.stackVec3[i] = null; + } + _this31.stackVec3 = newArray; + } + _this31.stackVec3[_this31.sizeVec3++] = _this19; + } + let _this32 = this._pool; + if(_this22 != null) { + _this22.zero(); + if(_this32.sizeVec3 == _this32.stackVec3.length) { + let newArray = new Array(_this32.sizeVec3 << 1); + let _g = 0; + let _g1 = _this32.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this32.stackVec3[i]; + _this32.stackVec3[i] = null; + } + _this32.stackVec3 = newArray; + } + _this32.stackVec3[_this32.sizeVec3++] = _this22; + } + let _this33 = this._pool; + if(_this25 != null) { + _this25.zero(); + if(_this33.sizeVec3 == _this33.stackVec3.length) { + let newArray = new Array(_this33.sizeVec3 << 1); + let _g = 0; + let _g1 = _this33.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this33.stackVec3[i]; + _this33.stackVec3[i] = null; + } + _this33.stackVec3 = newArray; + } + _this33.stackVec3[_this33.sizeVec3++] = _this25; + } + } + _drawEllipseOnSphere(d,center,normal,x,y,radiansX,radiansY,radius,color) { + let theta = 0; + let _this = this._pool; + let rotVec = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this._pool; + let rotQ = _this1.sizeQuat == 0 ? new oimo.common.Quat() : _this1.stackQuat[--_this1.sizeQuat]; + let _this2 = this._pool; + let rotM = _this2.sizeMat3 == 0 ? new oimo.common.Mat3() : _this2.stackMat3[--_this2.sizeMat3]; + let _this3 = this._pool; + let prevV = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _g = 0; + while(_g < 17) { + let i = _g++; + let rx = Math.cos(theta) * radiansX; + let ry = Math.sin(theta) * radiansY; + let halfRotAng = Math.sqrt(rx * rx + ry * ry); + let rotSin = Math.sin(halfRotAng * 0.5); + let rotCos = Math.cos(halfRotAng * 0.5); + let _this = rotVec.zero(); + _this.x += x.x * rx; + _this.y += x.y * rx; + _this.z += x.z * rx; + _this.x += y.x * ry; + _this.y += y.y * ry; + _this.z += y.z * ry; + let s = 1 / halfRotAng * rotSin; + rotVec.x *= s; + rotVec.y *= s; + rotVec.z *= s; + rotQ.x = rotVec.x; + rotQ.y = rotVec.y; + rotQ.z = rotVec.z; + rotQ.w = rotCos; + let x1 = rotQ.x; + let y1 = rotQ.y; + let z = rotQ.z; + let w = rotQ.w; + let x2 = 2 * x1; + let y2 = 2 * y1; + let z2 = 2 * z; + let xx = x1 * x2; + let yy = y1 * y2; + let zz = z * z2; + let xy = x1 * y2; + let yz = y1 * z2; + let xz = x1 * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + rotM.e00 = 1 - yy - zz; + rotM.e01 = xy - wz; + rotM.e02 = xz + wy; + rotM.e10 = xy + wz; + rotM.e11 = 1 - xx - zz; + rotM.e12 = yz - wx; + rotM.e20 = xz - wy; + rotM.e21 = yz + wx; + rotM.e22 = 1 - xx - yy; + let _this1 = this._pool; + let _this2 = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + _this2.x += normal.x * radius; + _this2.y += normal.y * radius; + _this2.z += normal.z * radius; + let v = _this2; + let y3 = v.x * rotM.e10 + v.y * rotM.e11 + v.z * rotM.e12; + let z1 = v.x * rotM.e20 + v.y * rotM.e21 + v.z * rotM.e22; + v.x = v.x * rotM.e00 + v.y * rotM.e01 + v.z * rotM.e02; + v.y = y3; + v.z = z1; + v.x += center.x; + v.y += center.y; + v.z += center.z; + if(i >= 1) { + d.line(prevV,v,color); + } + let _this3 = this._pool; + if(prevV != null) { + prevV.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = prevV; + } + prevV = v; + theta += 0.39269908169872375; + } + let _this4 = this._pool; + if(rotVec != null) { + rotVec.zero(); + if(_this4.sizeVec3 == _this4.stackVec3.length) { + let newArray = new Array(_this4.sizeVec3 << 1); + let _g = 0; + let _g1 = _this4.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this4.stackVec3[i]; + _this4.stackVec3[i] = null; + } + _this4.stackVec3 = newArray; + } + _this4.stackVec3[_this4.sizeVec3++] = rotVec; + } + let _this5 = this._pool; + if(rotQ != null) { + rotQ.x = 0; + rotQ.y = 0; + rotQ.z = 0; + rotQ.w = 1; + if(_this5.sizeQuat == _this5.stackQuat.length) { + let newArray = new Array(_this5.sizeQuat << 1); + let _g = 0; + let _g1 = _this5.sizeQuat; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this5.stackQuat[i]; + _this5.stackQuat[i] = null; + } + _this5.stackQuat = newArray; + } + _this5.stackQuat[_this5.sizeQuat++] = rotQ; + } + let _this6 = this._pool; + if(rotM != null) { + rotM.e00 = 1; + rotM.e01 = 0; + rotM.e02 = 0; + rotM.e10 = 0; + rotM.e11 = 1; + rotM.e12 = 0; + rotM.e20 = 0; + rotM.e21 = 0; + rotM.e22 = 1; + if(_this6.sizeMat3 == _this6.stackMat3.length) { + let newArray = new Array(_this6.sizeMat3 << 1); + let _g = 0; + let _g1 = _this6.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this6.stackMat3[i]; + _this6.stackMat3[i] = null; + } + _this6.stackMat3 = newArray; + } + _this6.stackMat3[_this6.sizeMat3++] = rotM; + } + let _this7 = this._pool; + if(prevV != null) { + prevV.zero(); + if(_this7.sizeVec3 == _this7.stackVec3.length) { + let newArray = new Array(_this7.sizeVec3 << 1); + let _g = 0; + let _g1 = _this7.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this7.stackVec3[i]; + _this7.stackVec3[i] = null; + } + _this7.stackVec3 = newArray; + } + _this7.stackVec3[_this7.sizeVec3++] = prevV; + } + } + step(timeStep) { + if(this._timeStep.dt > 0) { + this._timeStep.dtRatio = timeStep / this._timeStep.dt; + } + this._timeStep.dt = timeStep; + this._timeStep.invDt = 1 / timeStep; + let st = Date.now() / 1000; + this._updateContacts(); + this._solveIslands(); + oimo.dynamics.common.Performance.totalTime = (Date.now() / 1000 - st) * 1000; + } + addRigidBody(rigidBody) { + if(rigidBody._world != null) { + throw new Error("A rigid body cannot belong to multiple worlds."); + } + if(this._rigidBodyList == null) { + this._rigidBodyList = rigidBody; + this._rigidBodyListLast = rigidBody; + } else { + this._rigidBodyListLast._next = rigidBody; + rigidBody._prev = this._rigidBodyListLast; + this._rigidBodyListLast = rigidBody; + } + rigidBody._world = this; + let s = rigidBody._shapeList; + while(s != null) { + let n = s._next; + s._proxy = this._broadPhase.createProxy(s,s._aabb); + s._id = this._shapeIdCount++; + this._numShapes++; + s = n; + } + this._numRigidBodies++; + } + removeRigidBody(rigidBody) { + if(rigidBody._world != this) { + throw new Error("The rigid body doesn't belong to the world."); + } + let prev = rigidBody._prev; + let next = rigidBody._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(rigidBody == this._rigidBodyList) { + this._rigidBodyList = this._rigidBodyList._next; + } + if(rigidBody == this._rigidBodyListLast) { + this._rigidBodyListLast = this._rigidBodyListLast._prev; + } + rigidBody._next = null; + rigidBody._prev = null; + rigidBody._world = null; + let s = rigidBody._shapeList; + while(s != null) { + let n = s._next; + this._broadPhase.destroyProxy(s._proxy); + s._proxy = null; + s._id = -1; + let cl = s._rigidBody._contactLinkList; + while(cl != null) { + let n = cl._next; + let c = cl._contact; + if(c._s1 == s || c._s2 == s) { + let _this = cl._other; + _this._sleeping = false; + _this._sleepTime = 0; + let _this1 = this._contactManager; + let prev = c._prev; + let next = c._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(c == _this1._contactList) { + _this1._contactList = _this1._contactList._next; + } + if(c == _this1._contactListLast) { + _this1._contactListLast = _this1._contactListLast._prev; + } + c._next = null; + c._prev = null; + if(c._touching) { + let cc1 = c._s1._contactCallback; + let cc2 = c._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.endContact(c); + } + if(cc2 != null) { + cc2.endContact(c); + } + } + let prev1 = c._link1._prev; + let next1 = c._link1._next; + if(prev1 != null) { + prev1._next = next1; + } + if(next1 != null) { + next1._prev = prev1; + } + if(c._link1 == c._b1._contactLinkList) { + c._b1._contactLinkList = c._b1._contactLinkList._next; + } + if(c._link1 == c._b1._contactLinkListLast) { + c._b1._contactLinkListLast = c._b1._contactLinkListLast._prev; + } + c._link1._next = null; + c._link1._prev = null; + let prev2 = c._link2._prev; + let next2 = c._link2._next; + if(prev2 != null) { + prev2._next = next2; + } + if(next2 != null) { + next2._prev = prev2; + } + if(c._link2 == c._b2._contactLinkList) { + c._b2._contactLinkList = c._b2._contactLinkList._next; + } + if(c._link2 == c._b2._contactLinkListLast) { + c._b2._contactLinkListLast = c._b2._contactLinkListLast._prev; + } + c._link2._next = null; + c._link2._prev = null; + c._b1._numContactLinks--; + c._b2._numContactLinks--; + c._link1._other = null; + c._link2._other = null; + c._link1._contact = null; + c._link2._contact = null; + c._s1 = null; + c._s2 = null; + c._b1 = null; + c._b2 = null; + c._touching = false; + c._cachedDetectorData._clear(); + c._manifold._clear(); + c._detector = null; + let _this2 = c._contactConstraint; + _this2._s1 = null; + _this2._s2 = null; + _this2._b1 = null; + _this2._b2 = null; + _this2._tf1 = null; + _this2._tf2 = null; + c._next = _this1._contactPool; + _this1._contactPool = c; + _this1._numContacts--; + } + cl = n; + } + this._numShapes--; + s = n; + } + this._numRigidBodies--; + } + addJoint(joint) { + if(joint._world != null) { + throw new Error("A joint cannot belong to multiple worlds."); + } + if(this._jointList == null) { + this._jointList = joint; + this._jointListLast = joint; + } else { + this._jointListLast._next = joint; + joint._prev = this._jointListLast; + this._jointListLast = joint; + } + joint._world = this; + joint._link1._other = joint._b2; + joint._link2._other = joint._b1; + if(joint._b1._jointLinkList == null) { + joint._b1._jointLinkList = joint._link1; + joint._b1._jointLinkListLast = joint._link1; + } else { + joint._b1._jointLinkListLast._next = joint._link1; + joint._link1._prev = joint._b1._jointLinkListLast; + joint._b1._jointLinkListLast = joint._link1; + } + if(joint._b2._jointLinkList == null) { + joint._b2._jointLinkList = joint._link2; + joint._b2._jointLinkListLast = joint._link2; + } else { + joint._b2._jointLinkListLast._next = joint._link2; + joint._link2._prev = joint._b2._jointLinkListLast; + joint._b2._jointLinkListLast = joint._link2; + } + joint._b1._numJointLinks++; + joint._b2._numJointLinks++; + let _this = joint._b1; + _this._sleeping = false; + _this._sleepTime = 0; + let _this1 = joint._b2; + _this1._sleeping = false; + _this1._sleepTime = 0; + joint._syncAnchors(); + this._numJoints++; + } + removeJoint(joint) { + if(joint._world != this) { + throw new Error("The joint doesn't belong to the world."); + } + let prev = joint._prev; + let next = joint._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(joint == this._jointList) { + this._jointList = this._jointList._next; + } + if(joint == this._jointListLast) { + this._jointListLast = this._jointListLast._prev; + } + joint._next = null; + joint._prev = null; + joint._world = null; + let prev1 = joint._link1._prev; + let next1 = joint._link1._next; + if(prev1 != null) { + prev1._next = next1; + } + if(next1 != null) { + next1._prev = prev1; + } + if(joint._link1 == joint._b1._jointLinkList) { + joint._b1._jointLinkList = joint._b1._jointLinkList._next; + } + if(joint._link1 == joint._b1._jointLinkListLast) { + joint._b1._jointLinkListLast = joint._b1._jointLinkListLast._prev; + } + joint._link1._next = null; + joint._link1._prev = null; + let prev2 = joint._link2._prev; + let next2 = joint._link2._next; + if(prev2 != null) { + prev2._next = next2; + } + if(next2 != null) { + next2._prev = prev2; + } + if(joint._link2 == joint._b2._jointLinkList) { + joint._b2._jointLinkList = joint._b2._jointLinkList._next; + } + if(joint._link2 == joint._b2._jointLinkListLast) { + joint._b2._jointLinkListLast = joint._b2._jointLinkListLast._prev; + } + joint._link2._next = null; + joint._link2._prev = null; + joint._link1._other = null; + joint._link2._other = null; + joint._b1._numJointLinks--; + joint._b2._numJointLinks--; + let _this = joint._b1; + _this._sleeping = false; + _this._sleepTime = 0; + let _this1 = joint._b2; + _this1._sleeping = false; + _this1._sleepTime = 0; + this._numJoints--; + } + setDebugDraw(debugDraw) { + this._debugDraw = debugDraw; + } + getDebugDraw() { + return this._debugDraw; + } + debugDraw() { + if(this._debugDraw != null) { + if(this._broadPhase._type == 2) { + this._drawBvh(this._debugDraw,this._broadPhase._tree); + } + this._drawRigidBodies(this._debugDraw); + this._drawConstraints(this._debugDraw); + } + } + rayCast(begin,end,callback) { + let _this = this._rayCastWrapper.begin; + _this.x = begin.x; + _this.y = begin.y; + _this.z = begin.z; + let _this1 = this._rayCastWrapper.end; + _this1.x = end.x; + _this1.y = end.y; + _this1.z = end.z; + this._rayCastWrapper.callback = callback; + this._broadPhase.rayCast(begin,end,this._rayCastWrapper); + } + convexCast(convex,begin,translation,callback) { + this._convexCastWrapper.convex = convex; + let _this = this._convexCastWrapper.begin; + _this._positionX = begin._positionX; + _this._positionY = begin._positionY; + _this._positionZ = begin._positionZ; + _this._rotation00 = begin._rotation00; + _this._rotation01 = begin._rotation01; + _this._rotation02 = begin._rotation02; + _this._rotation10 = begin._rotation10; + _this._rotation11 = begin._rotation11; + _this._rotation12 = begin._rotation12; + _this._rotation20 = begin._rotation20; + _this._rotation21 = begin._rotation21; + _this._rotation22 = begin._rotation22; + let _this1 = this._convexCastWrapper.translation; + _this1.x = translation.x; + _this1.y = translation.y; + _this1.z = translation.z; + this._convexCastWrapper.callback = callback; + this._broadPhase.convexCast(convex,begin,translation,this._convexCastWrapper); + } + aabbTest(aabb,callback) { + this._aabbTestWrapper._aabb.copyFrom(aabb); + this._aabbTestWrapper._callback = callback; + this._broadPhase.aabbTest(aabb,this._aabbTestWrapper); + } + getRigidBodyList() { + return this._rigidBodyList; + } + getJointList() { + return this._jointList; + } + getBroadPhase() { + return this._broadPhase; + } + getContactManager() { + return this._contactManager; + } + getNumRigidBodies() { + return this._numRigidBodies; + } + getNumJoints() { + return this._numJoints; + } + getNumShapes() { + return this._numShapes; + } + getNumIslands() { + return this._numIslands; + } + getNumVelocityIterations() { + return this._numVelocityIterations; + } + setNumVelocityIterations(numVelocityIterations) { + this._numVelocityIterations = numVelocityIterations; + } + getNumPositionIterations() { + return this._numPositionIterations; + } + setNumPositionIterations(numPositionIterations) { + this._numPositionIterations = numPositionIterations; + } + getGravity() { + return this._gravity; + } + setGravity(gravity) { + let _this = this._gravity; + _this.x = gravity.x; + _this.y = gravity.y; + _this.z = gravity.z; + } +} +if(!oimo.dynamics._World) oimo.dynamics._World = {}; +oimo.dynamics._World.RayCastWrapper = class oimo_dynamics__$World_RayCastWrapper extends oimo.collision.broadphase.BroadPhaseProxyCallback { + constructor() { + super(); + this.rayCastHit = new oimo.collision.geometry.RayCastHit(); + this.begin = new oimo.common.Vec3(); + this.end = new oimo.common.Vec3(); + this.callback = null; + } + process(proxy) { + let shape = proxy.userData; + if(shape._geom.rayCast(this.begin,this.end,shape._transform,this.rayCastHit)) { + this.callback.process(shape,this.rayCastHit); + } + } +} +oimo.dynamics._World.ConvexCastWrapper = class oimo_dynamics__$World_ConvexCastWrapper extends oimo.collision.broadphase.BroadPhaseProxyCallback { + constructor() { + super(); + this.rayCastHit = new oimo.collision.geometry.RayCastHit(); + this.begin = new oimo.common.Transform(); + this.translation = new oimo.common.Vec3(); + this.zero = new oimo.common.Vec3(); + this.callback = null; + this.convex = null; + } + process(proxy) { + let shape = proxy.userData; + let type = shape._geom._type; + if(type < 0 || type > 5) { + return; + } + if(oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance.convexCast(this.convex,shape._geom,this.begin,shape._transform,this.translation,this.zero,this.rayCastHit)) { + this.callback.process(shape,this.rayCastHit); + } + } +} +oimo.dynamics._World.AabbTestWrapper = class oimo_dynamics__$World_AabbTestWrapper extends oimo.collision.broadphase.BroadPhaseProxyCallback { + constructor() { + super(); + this._aabb = new oimo.collision.geometry.Aabb(); + this._callback = null; + } + process(proxy) { + let shape = proxy.userData; + let shapeAabb = shape._aabb; + if(shapeAabb._minX < this._aabb._maxX && shapeAabb._maxX > this._aabb._minX && shapeAabb._minY < this._aabb._maxY && shapeAabb._maxY > this._aabb._minY && shapeAabb._minZ < this._aabb._maxZ && shapeAabb._maxZ > this._aabb._minZ) { + this._callback.process(shape); + } + } +} +if(!oimo.dynamics.callback) oimo.dynamics.callback = {}; +oimo.dynamics.callback.AabbTestCallback = class oimo_dynamics_callback_AabbTestCallback { + constructor() { + } + process(shape) { + } +} +oimo.dynamics.callback.ContactCallback = class oimo_dynamics_callback_ContactCallback { + constructor() { + } + beginContact(c) { + } + preSolve(c) { + } + postSolve(c) { + } + endContact(c) { + } +} +oimo.dynamics.callback.RayCastCallback = class oimo_dynamics_callback_RayCastCallback { + constructor() { + } + process(shape,hit) { + } +} +oimo.dynamics.callback.RayCastClosest = class oimo_dynamics_callback_RayCastClosest extends oimo.dynamics.callback.RayCastCallback { + constructor() { + super(); + this.position = new oimo.common.Vec3(); + this.normal = new oimo.common.Vec3(); + this.shape = null; + this.fraction = 1; + this.position.zero(); + this.normal.zero(); + this.hit = false; + } + clear() { + this.shape = null; + this.fraction = 1; + this.position.zero(); + this.normal.zero(); + this.hit = false; + } + process(shape,hit) { + if(hit.fraction < this.fraction) { + this.shape = shape; + this.hit = true; + this.fraction = hit.fraction; + let _this = this.position; + let v = hit.position; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let _this1 = this.normal; + let v1 = hit.normal; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + } + } +} +if(!oimo.dynamics.common) oimo.dynamics.common = {}; +oimo.dynamics.common.DebugDraw = class oimo_dynamics_common_DebugDraw { + constructor() { + this.p = new oimo.common.Pool(); + this.wireframe = false; + this.drawShapes = true; + this.drawBvh = false; + this.drawBvhMinLevel = 0; + this.drawBvhMaxLevel = 65536; + this.drawAabbs = false; + this.drawBases = false; + this.drawPairs = false; + this.drawContacts = false; + this.drawJoints = true; + this.drawJointLimits = false; + this.sphereCoords = new Array(5); + this.tmpSphereVerts = new Array(5); + this.tmpSphereNorms = new Array(5); + let _g = 0; + while(_g < 5) { + let i = _g++; + let num = i == 0 || i == 4 ? 1 : 8; + this.sphereCoords[i] = new Array(num); + this.tmpSphereVerts[i] = new Array(num); + this.tmpSphereNorms[i] = new Array(num); + let _g1 = 0; + while(_g1 < 8) { + let j = _g1++; + let theta = i * 0.7853981633974475; + let phi = j * 0.7853981633974475; + this.sphereCoords[i][j] = new oimo.common.Vec3(Math.sin(theta) * Math.cos(phi),Math.cos(theta),-Math.sin(theta) * Math.sin(phi)); + this.tmpSphereVerts[i][j] = new oimo.common.Vec3(); + this.tmpSphereNorms[i][j] = new oimo.common.Vec3(); + } + } + this.circleCoords = new Array(8); + this.circleCoordsShift = new Array(8); + this.tmpCircleVerts1 = new Array(8); + this.tmpCircleVerts2 = new Array(8); + this.tmpCircleNorms = new Array(8); + let _g1 = 0; + while(_g1 < 8) { + let i = _g1++; + this.circleCoords[i] = new oimo.common.Vec3(Math.cos(i * 0.7853981633974475),0,-Math.sin(i * 0.7853981633974475)); + this.circleCoordsShift[i] = new oimo.common.Vec3(Math.cos((i + 0.5) * 0.7853981633974475),0,-Math.sin((i + 0.5) * 0.7853981633974475)); + this.tmpCircleVerts1[i] = new oimo.common.Vec3(); + this.tmpCircleVerts2[i] = new oimo.common.Vec3(); + this.tmpCircleNorms[i] = new oimo.common.Vec3(); + } + this.style = new oimo.dynamics.common.DebugDrawStyle(); + } + aabb(min,max,color) { + let _this = this.p; + let v1 = (_this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]).init(min.x,min.y,min.z); + let _this1 = this.p; + let v2 = (_this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]).init(min.x,min.y,max.z); + let _this2 = this.p; + let v3 = (_this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]).init(min.x,max.y,min.z); + let _this3 = this.p; + let v4 = (_this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]).init(min.x,max.y,max.z); + let _this4 = this.p; + let v5 = (_this4.sizeVec3 == 0 ? new oimo.common.Vec3() : _this4.stackVec3[--_this4.sizeVec3]).init(max.x,min.y,min.z); + let _this5 = this.p; + let v6 = (_this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]).init(max.x,min.y,max.z); + let _this6 = this.p; + let v7 = (_this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]).init(max.x,max.y,min.z); + let _this7 = this.p; + let v8 = (_this7.sizeVec3 == 0 ? new oimo.common.Vec3() : _this7.stackVec3[--_this7.sizeVec3]).init(max.x,max.y,max.z); + this.line(v1,v2,color); + this.line(v3,v4,color); + this.line(v5,v6,color); + this.line(v7,v8,color); + this.line(v1,v3,color); + this.line(v2,v4,color); + this.line(v5,v7,color); + this.line(v6,v8,color); + this.line(v1,v5,color); + this.line(v2,v6,color); + this.line(v3,v7,color); + this.line(v4,v8,color); + let _this8 = this.p; + if(v1 != null) { + v1.zero(); + if(_this8.sizeVec3 == _this8.stackVec3.length) { + let newArray = new Array(_this8.sizeVec3 << 1); + let _g = 0; + let _g1 = _this8.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this8.stackVec3[i]; + _this8.stackVec3[i] = null; + } + _this8.stackVec3 = newArray; + } + _this8.stackVec3[_this8.sizeVec3++] = v1; + } + let _this9 = this.p; + if(v2 != null) { + v2.zero(); + if(_this9.sizeVec3 == _this9.stackVec3.length) { + let newArray = new Array(_this9.sizeVec3 << 1); + let _g = 0; + let _g1 = _this9.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this9.stackVec3[i]; + _this9.stackVec3[i] = null; + } + _this9.stackVec3 = newArray; + } + _this9.stackVec3[_this9.sizeVec3++] = v2; + } + let _this10 = this.p; + if(v3 != null) { + v3.zero(); + if(_this10.sizeVec3 == _this10.stackVec3.length) { + let newArray = new Array(_this10.sizeVec3 << 1); + let _g = 0; + let _g1 = _this10.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this10.stackVec3[i]; + _this10.stackVec3[i] = null; + } + _this10.stackVec3 = newArray; + } + _this10.stackVec3[_this10.sizeVec3++] = v3; + } + let _this11 = this.p; + if(v4 != null) { + v4.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = v4; + } + let _this12 = this.p; + if(v5 != null) { + v5.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = v5; + } + let _this13 = this.p; + if(v6 != null) { + v6.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = v6; + } + let _this14 = this.p; + if(v7 != null) { + v7.zero(); + if(_this14.sizeVec3 == _this14.stackVec3.length) { + let newArray = new Array(_this14.sizeVec3 << 1); + let _g = 0; + let _g1 = _this14.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackVec3[i]; + _this14.stackVec3[i] = null; + } + _this14.stackVec3 = newArray; + } + _this14.stackVec3[_this14.sizeVec3++] = v7; + } + let _this15 = this.p; + if(v8 != null) { + v8.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = v8; + } + } + basis(transform,length,colorX,colorY,colorZ) { + let _this = this.p; + let pos = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let rot = _this1.sizeMat3 == 0 ? new oimo.common.Mat3() : _this1.stackMat3[--_this1.sizeMat3]; + let _this2 = this.p; + let ex = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this.p; + let ey = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this.p; + let ez = _this4.sizeVec3 == 0 ? new oimo.common.Vec3() : _this4.stackVec3[--_this4.sizeVec3]; + let v = pos; + v.x = transform._positionX; + v.y = transform._positionY; + v.z = transform._positionZ; + let m = rot; + m.e00 = transform._rotation00; + m.e01 = transform._rotation01; + m.e02 = transform._rotation02; + m.e10 = transform._rotation10; + m.e11 = transform._rotation11; + m.e12 = transform._rotation12; + m.e20 = transform._rotation20; + m.e21 = transform._rotation21; + m.e22 = transform._rotation22; + ex.init(rot.e00,rot.e10,rot.e20); + ey.init(rot.e01,rot.e11,rot.e21); + ez.init(rot.e02,rot.e12,rot.e22); + ex.x *= length; + ex.y *= length; + ex.z *= length; + let _this5 = ex; + _this5.x += pos.x; + _this5.y += pos.y; + _this5.z += pos.z; + ey.x *= length; + ey.y *= length; + ey.z *= length; + let _this6 = ey; + _this6.x += pos.x; + _this6.y += pos.y; + _this6.z += pos.z; + ez.x *= length; + ez.y *= length; + ez.z *= length; + let _this7 = ez; + _this7.x += pos.x; + _this7.y += pos.y; + _this7.z += pos.z; + this.line(pos,ex,colorX); + this.line(pos,ey,colorY); + this.line(pos,ez,colorZ); + let _this8 = this.p; + if(pos != null) { + pos.zero(); + if(_this8.sizeVec3 == _this8.stackVec3.length) { + let newArray = new Array(_this8.sizeVec3 << 1); + let _g = 0; + let _g1 = _this8.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this8.stackVec3[i]; + _this8.stackVec3[i] = null; + } + _this8.stackVec3 = newArray; + } + _this8.stackVec3[_this8.sizeVec3++] = pos; + } + let _this9 = this.p; + if(rot != null) { + rot.e00 = 1; + rot.e01 = 0; + rot.e02 = 0; + rot.e10 = 0; + rot.e11 = 1; + rot.e12 = 0; + rot.e20 = 0; + rot.e21 = 0; + rot.e22 = 1; + if(_this9.sizeMat3 == _this9.stackMat3.length) { + let newArray = new Array(_this9.sizeMat3 << 1); + let _g = 0; + let _g1 = _this9.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this9.stackMat3[i]; + _this9.stackMat3[i] = null; + } + _this9.stackMat3 = newArray; + } + _this9.stackMat3[_this9.sizeMat3++] = rot; + } + let _this10 = this.p; + if(ex != null) { + ex.zero(); + if(_this10.sizeVec3 == _this10.stackVec3.length) { + let newArray = new Array(_this10.sizeVec3 << 1); + let _g = 0; + let _g1 = _this10.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this10.stackVec3[i]; + _this10.stackVec3[i] = null; + } + _this10.stackVec3 = newArray; + } + _this10.stackVec3[_this10.sizeVec3++] = ex; + } + let _this11 = this.p; + if(ey != null) { + ey.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = ey; + } + let _this12 = this.p; + if(ez != null) { + ez.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = ez; + } + } + ellipse(center,ex,ey,radiusX,radiusY,color) { + this.arc(center,ex,ey,radiusX,radiusY,0,6.28318530717958,false,color); + } + arc(center,ex,ey,radiusX,radiusY,startAngle,endAngle,drawSector,color) { + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = ex.x; + _this1.y = ex.y; + _this1.z = ex.z; + let _this2 = _this1; + _this2.x *= radiusX; + _this2.y *= radiusX; + _this2.z *= radiusX; + + let _this3 = this.p; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = ey.x; + _this4.y = ey.y; + _this4.z = ey.z; + let _this5 = _this4; + _this5.x *= radiusY; + _this5.y *= radiusY; + _this5.z *= radiusY; + + let angDiff = endAngle - startAngle; + if(angDiff < 0) { + angDiff = -angDiff; + } + let n = angDiff / 0.52359877559829837 + 0.5 | 0; + if(n == 0) { + n = 1; + } + let theta = startAngle; + let dt = (endAngle - startAngle) / n; + let _this6 = this.p; + let _this7 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + _this7.x = center.x; + _this7.y = center.y; + _this7.z = center.z; + let _this8 = _this7; + let s = Math.cos(startAngle); + _this8.x += _this2.x * s; + _this8.y += _this2.y * s; + _this8.z += _this2.z * s; + let s1 = Math.sin(startAngle); + _this8.x += _this5.x * s1; + _this8.y += _this5.y * s1; + _this8.z += _this5.z * s1; + let prevV = _this8; + if(drawSector) { + this.line(center,_this8,color); + } + let _g = 0; + let _g1 = n; + while(_g < _g1) { + ++_g; + theta += dt; + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = center.x; + _this1.y = center.y; + _this1.z = center.z; + let _this3 = _this1; + let s = Math.cos(theta); + _this3.x += _this2.x * s; + _this3.y += _this2.y * s; + _this3.z += _this2.z * s; + let s1 = Math.sin(theta); + _this3.x += _this5.x * s1; + _this3.y += _this5.y * s1; + _this3.z += _this5.z * s1; + this.line(prevV,_this3,color); + let _this4 = this.p; + if(prevV != null) { + prevV.zero(); + if(_this4.sizeVec3 == _this4.stackVec3.length) { + let newArray = new Array(_this4.sizeVec3 << 1); + let _g = 0; + let _g1 = _this4.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this4.stackVec3[i]; + _this4.stackVec3[i] = null; + } + _this4.stackVec3 = newArray; + } + _this4.stackVec3[_this4.sizeVec3++] = prevV; + } + prevV = _this3; + } + if(drawSector) { + this.line(center,prevV,color); + } + let _this9 = this.p; + if(prevV != null) { + prevV.zero(); + if(_this9.sizeVec3 == _this9.stackVec3.length) { + let newArray = new Array(_this9.sizeVec3 << 1); + let _g = 0; + let _g1 = _this9.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this9.stackVec3[i]; + _this9.stackVec3[i] = null; + } + _this9.stackVec3 = newArray; + } + _this9.stackVec3[_this9.sizeVec3++] = prevV; + } + let _this10 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this10.sizeVec3 == _this10.stackVec3.length) { + let newArray = new Array(_this10.sizeVec3 << 1); + let _g = 0; + let _g1 = _this10.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this10.stackVec3[i]; + _this10.stackVec3[i] = null; + } + _this10.stackVec3 = newArray; + } + _this10.stackVec3[_this10.sizeVec3++] = _this2; + } + let _this11 = this.p; + if(_this5 != null) { + _this5.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = _this5; + } + } + cone(tf,radius,halfHeight,color) { + let _this = this.p; + let ex = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let ey = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let _this2 = this.p; + let ez = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this.p; + let o = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this.p; + let m = _this4.sizeMat3 == 0 ? new oimo.common.Mat3() : _this4.stackMat3[--_this4.sizeMat3]; + let v = o; + v.x = tf._positionX; + v.y = tf._positionY; + v.z = tf._positionZ; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + ex.init(m.e00,m.e10,m.e20); + ey.init(m.e01,m.e11,m.e21); + ez.init(m.e02,m.e12,m.e22); + let _this5 = this.p; + let _this6 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + _this6.x = o.x; + _this6.y = o.y; + _this6.z = o.z; + let _this7 = _this6; + _this7.x += ey.x * halfHeight; + _this7.y += ey.y * halfHeight; + _this7.z += ey.z * halfHeight; + let _this8 = this.p; + let _this9 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + _this9.x = o.x; + _this9.y = o.y; + _this9.z = o.z; + let _this10 = _this9; + let s = -halfHeight; + _this10.x += ey.x * s; + _this10.y += ey.y * s; + _this10.z += ey.z * s; + if(this.wireframe) { + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = _this10.x; + _this1.y = _this10.y; + _this1.z = _this10.z; + let _this2 = _this1; + let s = -radius; + _this2.x += ex.x * s; + _this2.y += ex.y * s; + _this2.z += ex.z * s; + _this2.x += ez.x * 0; + _this2.y += ez.y * 0; + _this2.z += ez.z * 0; + let _this3 = this.p; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = _this10.x; + _this4.y = _this10.y; + _this4.z = _this10.z; + let _this5 = _this4; + _this5.x += ex.x * radius; + _this5.y += ex.y * radius; + _this5.z += ex.z * radius; + _this5.x += ez.x * 0; + _this5.y += ez.y * 0; + _this5.z += ez.z * 0; + let _this6 = this.p; + let _this8 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + _this8.x = _this10.x; + _this8.y = _this10.y; + _this8.z = _this10.z; + let _this9 = _this8; + _this9.x += ex.x * 0; + _this9.y += ex.y * 0; + _this9.z += ex.z * 0; + let s1 = -radius; + _this9.x += ez.x * s1; + _this9.y += ez.y * s1; + _this9.z += ez.z * s1; + let _this11 = this.p; + let _this12 = _this11.sizeVec3 == 0 ? new oimo.common.Vec3() : _this11.stackVec3[--_this11.sizeVec3]; + _this12.x = _this10.x; + _this12.y = _this10.y; + _this12.z = _this10.z; + let _this13 = _this12; + _this13.x += ex.x * 0; + _this13.y += ex.y * 0; + _this13.z += ex.z * 0; + _this13.x += ez.x * radius; + _this13.y += ez.y * radius; + _this13.z += ez.z * radius; + this.ellipse(_this10,ex,ez,radius,radius,color); + this.line(_this7,_this2,color); + this.line(_this7,_this5,color); + this.line(_this7,_this9,color); + this.line(_this7,_this13,color); + let _this14 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this14.sizeVec3 == _this14.stackVec3.length) { + let newArray = new Array(_this14.sizeVec3 << 1); + let _g = 0; + let _g1 = _this14.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackVec3[i]; + _this14.stackVec3[i] = null; + } + _this14.stackVec3 = newArray; + } + _this14.stackVec3[_this14.sizeVec3++] = _this2; + } + let _this15 = this.p; + if(_this5 != null) { + _this5.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = _this5; + } + let _this16 = this.p; + if(_this9 != null) { + _this9.zero(); + if(_this16.sizeVec3 == _this16.stackVec3.length) { + let newArray = new Array(_this16.sizeVec3 << 1); + let _g = 0; + let _g1 = _this16.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this16.stackVec3[i]; + _this16.stackVec3[i] = null; + } + _this16.stackVec3 = newArray; + } + _this16.stackVec3[_this16.sizeVec3++] = _this9; + } + let _this17 = this.p; + if(_this13 != null) { + _this13.zero(); + if(_this17.sizeVec3 == _this17.stackVec3.length) { + let newArray = new Array(_this17.sizeVec3 << 1); + let _g = 0; + let _g1 = _this17.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this17.stackVec3[i]; + _this17.stackVec3[i] = null; + } + _this17.stackVec3 = newArray; + } + _this17.stackVec3[_this17.sizeVec3++] = _this13; + } + } else { + let invDenom = 1 / Math.sqrt(radius * radius + 4 * halfHeight * halfHeight); + let cos = 2 * halfHeight * invDenom; + let sin = radius * invDenom; + let _g = 0; + while(_g < 8) { + let i = _g++; + let _this = this.tmpCircleNorms[i]; + let v = this.circleCoords[i]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + _this.x *= cos; + _this.y *= cos; + _this.z *= cos; + _this.y += sin; + let _this1 = this.tmpCircleNorms[i]; + let y = _this1.x * m.e10 + _this1.y * m.e11 + _this1.z * m.e12; + let z = _this1.x * m.e20 + _this1.y * m.e21 + _this1.z * m.e22; + _this1.x = _this1.x * m.e00 + _this1.y * m.e01 + _this1.z * m.e02; + _this1.y = y; + _this1.z = z; + let _this2 = this.tmpCircleVerts1[i]; + let v1 = this.circleCoordsShift[i]; + _this2.x = v1.x; + _this2.y = v1.y; + _this2.z = v1.z; + _this2.x *= cos; + _this2.y *= cos; + _this2.z *= cos; + _this2.y += sin; + let _this3 = this.tmpCircleVerts1[i]; + let y1 = _this3.x * m.e10 + _this3.y * m.e11 + _this3.z * m.e12; + let z1 = _this3.x * m.e20 + _this3.y * m.e21 + _this3.z * m.e22; + _this3.x = _this3.x * m.e00 + _this3.y * m.e01 + _this3.z * m.e02; + _this3.y = y1; + _this3.z = z1; + let _this4 = this.tmpCircleVerts2[i]; + let v2 = this.circleCoords[i]; + _this4.x = v2.x; + _this4.y = v2.y; + _this4.z = v2.z; + let y2 = _this4.x * m.e10 + _this4.y * m.e11 + _this4.z * m.e12; + let z2 = _this4.x * m.e20 + _this4.y * m.e21 + _this4.z * m.e22; + _this4.x = _this4.x * m.e00 + _this4.y * m.e01 + _this4.z * m.e02; + _this4.y = y2; + _this4.z = z2; + _this4.x *= radius; + _this4.y *= radius; + _this4.z *= radius; + _this4.x += o.x; + _this4.y += o.y; + _this4.z += o.z; + let _this5 = this.tmpCircleVerts2[i]; + let s = -halfHeight; + _this5.x += ey.x * s; + _this5.y += ey.y * s; + _this5.z += ey.z * s; + } + let _g1 = 0; + while(_g1 < 8) { + let i = _g1++; + let v2 = this.tmpCircleVerts2[i]; + let v3 = this.tmpCircleVerts2[(i + 1) % 8]; + let n1 = this.tmpCircleVerts1[i]; + this.triangle(_this7,v2,v3,n1,this.tmpCircleNorms[i],this.tmpCircleNorms[(i + 1) % 8],color); + v2 = this.tmpCircleVerts2[(i + 1) % 8]; + v3 = this.tmpCircleVerts2[i]; + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = ey.x; + _this1.y = ey.y; + _this1.z = ey.z; + let _this2 = _this1; + _this2.x = -_this2.x; + _this2.y = -_this2.y; + _this2.z = -_this2.z; + + this.triangle(_this10,v2,v3,_this2,_this2,_this2,color); + let _this3 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = _this2; + } + } + } + let _this11 = this.p; + if(_this7 != null) { + _this7.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = _this7; + } + let _this12 = this.p; + if(_this10 != null) { + _this10.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = _this10; + } + let _this13 = this.p; + if(o != null) { + o.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = o; + } + let _this14 = this.p; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this14.sizeMat3 == _this14.stackMat3.length) { + let newArray = new Array(_this14.sizeMat3 << 1); + let _g = 0; + let _g1 = _this14.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackMat3[i]; + _this14.stackMat3[i] = null; + } + _this14.stackMat3 = newArray; + } + _this14.stackMat3[_this14.sizeMat3++] = m; + } + let _this15 = this.p; + if(ex != null) { + ex.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = ex; + } + let _this16 = this.p; + if(ey != null) { + ey.zero(); + if(_this16.sizeVec3 == _this16.stackVec3.length) { + let newArray = new Array(_this16.sizeVec3 << 1); + let _g = 0; + let _g1 = _this16.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this16.stackVec3[i]; + _this16.stackVec3[i] = null; + } + _this16.stackVec3 = newArray; + } + _this16.stackVec3[_this16.sizeVec3++] = ey; + } + let _this17 = this.p; + if(ez != null) { + ez.zero(); + if(_this17.sizeVec3 == _this17.stackVec3.length) { + let newArray = new Array(_this17.sizeVec3 << 1); + let _g = 0; + let _g1 = _this17.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this17.stackVec3[i]; + _this17.stackVec3[i] = null; + } + _this17.stackVec3 = newArray; + } + _this17.stackVec3[_this17.sizeVec3++] = ez; + } + } + cylinder(tf,radius,halfHeight,color) { + let _this = this.p; + let ex = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let ey = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let _this2 = this.p; + let ez = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this.p; + let o = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this.p; + let m = _this4.sizeMat3 == 0 ? new oimo.common.Mat3() : _this4.stackMat3[--_this4.sizeMat3]; + let v = o; + v.x = tf._positionX; + v.y = tf._positionY; + v.z = tf._positionZ; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + ex.init(m.e00,m.e10,m.e20); + ey.init(m.e01,m.e11,m.e21); + ez.init(m.e02,m.e12,m.e22); + let _this5 = this.p; + let _this6 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + _this6.x = o.x; + _this6.y = o.y; + _this6.z = o.z; + let _this7 = _this6; + _this7.x += ey.x * halfHeight; + _this7.y += ey.y * halfHeight; + _this7.z += ey.z * halfHeight; + let _this8 = this.p; + let _this9 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + _this9.x = o.x; + _this9.y = o.y; + _this9.z = o.z; + let _this10 = _this9; + let s = -halfHeight; + _this10.x += ey.x * s; + _this10.y += ey.y * s; + _this10.z += ey.z * s; + if(this.wireframe) { + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = _this7.x; + _this1.y = _this7.y; + _this1.z = _this7.z; + let _this2 = _this1; + let s = -radius; + _this2.x += ex.x * s; + _this2.y += ex.y * s; + _this2.z += ex.z * s; + _this2.x += ez.x * 0; + _this2.y += ez.y * 0; + _this2.z += ez.z * 0; + let _this3 = this.p; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = _this7.x; + _this4.y = _this7.y; + _this4.z = _this7.z; + let _this5 = _this4; + _this5.x += ex.x * radius; + _this5.y += ex.y * radius; + _this5.z += ex.z * radius; + _this5.x += ez.x * 0; + _this5.y += ez.y * 0; + _this5.z += ez.z * 0; + let _this6 = this.p; + let _this8 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + _this8.x = _this7.x; + _this8.y = _this7.y; + _this8.z = _this7.z; + let _this9 = _this8; + _this9.x += ex.x * 0; + _this9.y += ex.y * 0; + _this9.z += ex.z * 0; + let s1 = -radius; + _this9.x += ez.x * s1; + _this9.y += ez.y * s1; + _this9.z += ez.z * s1; + let _this11 = this.p; + let _this12 = _this11.sizeVec3 == 0 ? new oimo.common.Vec3() : _this11.stackVec3[--_this11.sizeVec3]; + _this12.x = _this7.x; + _this12.y = _this7.y; + _this12.z = _this7.z; + let _this13 = _this12; + _this13.x += ex.x * 0; + _this13.y += ex.y * 0; + _this13.z += ex.z * 0; + _this13.x += ez.x * radius; + _this13.y += ez.y * radius; + _this13.z += ez.z * radius; + let _this14 = this.p; + let _this15 = _this14.sizeVec3 == 0 ? new oimo.common.Vec3() : _this14.stackVec3[--_this14.sizeVec3]; + _this15.x = _this10.x; + _this15.y = _this10.y; + _this15.z = _this10.z; + let _this16 = _this15; + let s2 = -radius; + _this16.x += ex.x * s2; + _this16.y += ex.y * s2; + _this16.z += ex.z * s2; + _this16.x += ez.x * 0; + _this16.y += ez.y * 0; + _this16.z += ez.z * 0; + let _this17 = this.p; + let _this18 = _this17.sizeVec3 == 0 ? new oimo.common.Vec3() : _this17.stackVec3[--_this17.sizeVec3]; + _this18.x = _this10.x; + _this18.y = _this10.y; + _this18.z = _this10.z; + let _this19 = _this18; + _this19.x += ex.x * radius; + _this19.y += ex.y * radius; + _this19.z += ex.z * radius; + _this19.x += ez.x * 0; + _this19.y += ez.y * 0; + _this19.z += ez.z * 0; + let _this20 = this.p; + let _this21 = _this20.sizeVec3 == 0 ? new oimo.common.Vec3() : _this20.stackVec3[--_this20.sizeVec3]; + _this21.x = _this10.x; + _this21.y = _this10.y; + _this21.z = _this10.z; + let _this22 = _this21; + _this22.x += ex.x * 0; + _this22.y += ex.y * 0; + _this22.z += ex.z * 0; + let s3 = -radius; + _this22.x += ez.x * s3; + _this22.y += ez.y * s3; + _this22.z += ez.z * s3; + let _this23 = this.p; + let _this24 = _this23.sizeVec3 == 0 ? new oimo.common.Vec3() : _this23.stackVec3[--_this23.sizeVec3]; + _this24.x = _this10.x; + _this24.y = _this10.y; + _this24.z = _this10.z; + let _this25 = _this24; + _this25.x += ex.x * 0; + _this25.y += ex.y * 0; + _this25.z += ex.z * 0; + _this25.x += ez.x * radius; + _this25.y += ez.y * radius; + _this25.z += ez.z * radius; + this.ellipse(_this7,ex,ez,radius,radius,color); + this.ellipse(_this10,ex,ez,radius,radius,color); + this.line(_this2,_this16,color); + this.line(_this5,_this19,color); + this.line(_this9,_this22,color); + this.line(_this13,_this25,color); + let _this26 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this26.sizeVec3 == _this26.stackVec3.length) { + let newArray = new Array(_this26.sizeVec3 << 1); + let _g = 0; + let _g1 = _this26.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this26.stackVec3[i]; + _this26.stackVec3[i] = null; + } + _this26.stackVec3 = newArray; + } + _this26.stackVec3[_this26.sizeVec3++] = _this2; + } + let _this27 = this.p; + if(_this5 != null) { + _this5.zero(); + if(_this27.sizeVec3 == _this27.stackVec3.length) { + let newArray = new Array(_this27.sizeVec3 << 1); + let _g = 0; + let _g1 = _this27.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this27.stackVec3[i]; + _this27.stackVec3[i] = null; + } + _this27.stackVec3 = newArray; + } + _this27.stackVec3[_this27.sizeVec3++] = _this5; + } + let _this28 = this.p; + if(_this9 != null) { + _this9.zero(); + if(_this28.sizeVec3 == _this28.stackVec3.length) { + let newArray = new Array(_this28.sizeVec3 << 1); + let _g = 0; + let _g1 = _this28.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this28.stackVec3[i]; + _this28.stackVec3[i] = null; + } + _this28.stackVec3 = newArray; + } + _this28.stackVec3[_this28.sizeVec3++] = _this9; + } + let _this29 = this.p; + if(_this13 != null) { + _this13.zero(); + if(_this29.sizeVec3 == _this29.stackVec3.length) { + let newArray = new Array(_this29.sizeVec3 << 1); + let _g = 0; + let _g1 = _this29.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this29.stackVec3[i]; + _this29.stackVec3[i] = null; + } + _this29.stackVec3 = newArray; + } + _this29.stackVec3[_this29.sizeVec3++] = _this13; + } + let _this30 = this.p; + if(_this16 != null) { + _this16.zero(); + if(_this30.sizeVec3 == _this30.stackVec3.length) { + let newArray = new Array(_this30.sizeVec3 << 1); + let _g = 0; + let _g1 = _this30.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this30.stackVec3[i]; + _this30.stackVec3[i] = null; + } + _this30.stackVec3 = newArray; + } + _this30.stackVec3[_this30.sizeVec3++] = _this16; + } + let _this31 = this.p; + if(_this19 != null) { + _this19.zero(); + if(_this31.sizeVec3 == _this31.stackVec3.length) { + let newArray = new Array(_this31.sizeVec3 << 1); + let _g = 0; + let _g1 = _this31.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this31.stackVec3[i]; + _this31.stackVec3[i] = null; + } + _this31.stackVec3 = newArray; + } + _this31.stackVec3[_this31.sizeVec3++] = _this19; + } + let _this32 = this.p; + if(_this22 != null) { + _this22.zero(); + if(_this32.sizeVec3 == _this32.stackVec3.length) { + let newArray = new Array(_this32.sizeVec3 << 1); + let _g = 0; + let _g1 = _this32.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this32.stackVec3[i]; + _this32.stackVec3[i] = null; + } + _this32.stackVec3 = newArray; + } + _this32.stackVec3[_this32.sizeVec3++] = _this22; + } + let _this33 = this.p; + if(_this25 != null) { + _this25.zero(); + if(_this33.sizeVec3 == _this33.stackVec3.length) { + let newArray = new Array(_this33.sizeVec3 << 1); + let _g = 0; + let _g1 = _this33.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this33.stackVec3[i]; + _this33.stackVec3[i] = null; + } + _this33.stackVec3 = newArray; + } + _this33.stackVec3[_this33.sizeVec3++] = _this25; + } + } else { + let _g = 0; + while(_g < 8) { + let i = _g++; + let _this = this.tmpCircleNorms[i]; + let v = this.circleCoords[i]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let y = _this.x * m.e10 + _this.y * m.e11 + _this.z * m.e12; + let z = _this.x * m.e20 + _this.y * m.e21 + _this.z * m.e22; + _this.x = _this.x * m.e00 + _this.y * m.e01 + _this.z * m.e02; + _this.y = y; + _this.z = z; + let _this1 = this.tmpCircleVerts1[i]; + let v1 = this.tmpCircleNorms[i]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + _this1.x *= radius; + _this1.y *= radius; + _this1.z *= radius; + _this1.x += o.x; + _this1.y += o.y; + _this1.z += o.z; + let _this2 = this.tmpCircleVerts2[i]; + let v2 = this.tmpCircleVerts1[i]; + _this2.x = v2.x; + _this2.y = v2.y; + _this2.z = v2.z; + let _this3 = this.tmpCircleVerts1[i]; + _this3.x += ey.x * halfHeight; + _this3.y += ey.y * halfHeight; + _this3.z += ey.z * halfHeight; + let _this4 = this.tmpCircleVerts2[i]; + let s = -halfHeight; + _this4.x += ey.x * s; + _this4.y += ey.y * s; + _this4.z += ey.z * s; + } + let _g1 = 0; + while(_g1 < 8) { + let i = _g1++; + let v1; + let v2 = this.tmpCircleVerts1[i]; + let v3 = this.tmpCircleVerts1[(i + 1) % 8]; + let n1 = ey; + this.triangle(_this7,v2,v3,n1,n1,n1,color); + + v2 = this.tmpCircleVerts2[(i + 1) % 8]; + v3 = this.tmpCircleVerts2[i]; + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = ey.x; + _this1.y = ey.y; + _this1.z = ey.z; + let _this2 = _this1; + _this2.x = -_this2.x; + _this2.y = -_this2.y; + _this2.z = -_this2.z; + + this.triangle(_this10,v2,v3,_this2,_this2,_this2,color); + let _this3 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this3.sizeVec3 == _this3.stackVec3.length) { + let newArray = new Array(_this3.sizeVec3 << 1); + let _g = 0; + let _g1 = _this3.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackVec3[i]; + _this3.stackVec3[i] = null; + } + _this3.stackVec3 = newArray; + } + _this3.stackVec3[_this3.sizeVec3++] = _this2; + } + v1 = this.tmpCircleVerts1[i]; + v2 = this.tmpCircleVerts2[i]; + v3 = this.tmpCircleVerts2[(i + 1) % 8]; + n1 = this.tmpCircleNorms[i]; + let n2 = this.tmpCircleNorms[(i + 1) % 8]; + this.rect(v1,v2,v3,this.tmpCircleVerts1[(i + 1) % 8],n1,n1,n2,n2,color); + } + } + let _this11 = this.p; + if(_this7 != null) { + _this7.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = _this7; + } + let _this12 = this.p; + if(_this10 != null) { + _this10.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = _this10; + } + let _this13 = this.p; + if(o != null) { + o.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = o; + } + let _this14 = this.p; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this14.sizeMat3 == _this14.stackMat3.length) { + let newArray = new Array(_this14.sizeMat3 << 1); + let _g = 0; + let _g1 = _this14.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackMat3[i]; + _this14.stackMat3[i] = null; + } + _this14.stackMat3 = newArray; + } + _this14.stackMat3[_this14.sizeMat3++] = m; + } + let _this15 = this.p; + if(ex != null) { + ex.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = ex; + } + let _this16 = this.p; + if(ey != null) { + ey.zero(); + if(_this16.sizeVec3 == _this16.stackVec3.length) { + let newArray = new Array(_this16.sizeVec3 << 1); + let _g = 0; + let _g1 = _this16.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this16.stackVec3[i]; + _this16.stackVec3[i] = null; + } + _this16.stackVec3 = newArray; + } + _this16.stackVec3[_this16.sizeVec3++] = ey; + } + let _this17 = this.p; + if(ez != null) { + ez.zero(); + if(_this17.sizeVec3 == _this17.stackVec3.length) { + let newArray = new Array(_this17.sizeVec3 << 1); + let _g = 0; + let _g1 = _this17.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this17.stackVec3[i]; + _this17.stackVec3[i] = null; + } + _this17.stackVec3 = newArray; + } + _this17.stackVec3[_this17.sizeVec3++] = ez; + } + } + capsule(tf,radius,halfHeight,color) { + let _this = this.p; + let ex = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let ey = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let _this2 = this.p; + let ez = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this.p; + let o = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this.p; + let m = _this4.sizeMat3 == 0 ? new oimo.common.Mat3() : _this4.stackMat3[--_this4.sizeMat3]; + let v = o; + v.x = tf._positionX; + v.y = tf._positionY; + v.z = tf._positionZ; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + ex.init(m.e00,m.e10,m.e20); + ey.init(m.e01,m.e11,m.e21); + ez.init(m.e02,m.e12,m.e22); + let vs = this.tmpSphereVerts; + let ns = this.tmpSphereNorms; + let _g = 0; + while(_g < 5) { + let i2 = _g++; + let n = this.tmpSphereVerts[i2].length; + let _g1 = 0; + while(_g1 < n) { + let j2 = _g1++; + let _this = ns[i2][j2]; + let v = this.sphereCoords[i2][j2]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let y = _this.x * m.e10 + _this.y * m.e11 + _this.z * m.e12; + let z = _this.x * m.e20 + _this.y * m.e21 + _this.z * m.e22; + _this.x = _this.x * m.e00 + _this.y * m.e01 + _this.z * m.e02; + _this.y = y; + _this.z = z; + } + } + let _g1 = 0; + while(_g1 < 4) { + let i = _g1++; + if(i == 0) { + let _g = 0; + while(_g < 3) { + let i2 = _g++; + let n = this.tmpSphereVerts[i2].length; + let _g1 = 0; + while(_g1 < n) { + let j2 = _g1++; + let _this = vs[i2][j2]; + let v = ns[i2][j2]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + _this.x *= radius; + _this.y *= radius; + _this.z *= radius; + _this.x += o.x; + _this.y += o.y; + _this.z += o.z; + _this.x += ey.x * halfHeight; + _this.y += ey.y * halfHeight; + _this.z += ey.z * halfHeight; + } + } + } + if(i == 2) { + let _g = 2; + while(_g < 5) { + let i2 = _g++; + let n = this.tmpSphereVerts[i2].length; + let _g1 = 0; + while(_g1 < n) { + let j2 = _g1++; + let _this = vs[i2][j2]; + let v = ns[i2][j2]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + _this.x *= radius; + _this.y *= radius; + _this.z *= radius; + _this.x += o.x; + _this.y += o.y; + _this.z += o.z; + let s = -halfHeight; + _this.x += ey.x * s; + _this.y += ey.y * s; + _this.z += ey.z * s; + } + } + } + let _g = 0; + while(_g < 8) { + let j = _g++; + let v1; + let v2; + let v3; + let v4; + let n1; + let n2; + let n3; + let n4; + if(i == 0) { + if(this.wireframe) { + v1 = vs[0][0]; + v2 = vs[1][j]; + this.line(v1,v2,color); + } else { + v1 = vs[0][0]; + v2 = vs[1][j]; + v3 = vs[1][(j + 1) % 8]; + n1 = ns[0][0]; + n2 = ns[1][j]; + n3 = ns[1][(j + 1) % 8]; + this.triangle(v1,v2,v3,n1,n2,n3,color); + } + } else if(i == 3) { + if(this.wireframe) { + v1 = vs[4][0]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i][j]; + this.line(v1,v2,color); + this.line(v2,v3,color); + } else { + v1 = vs[4][0]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i][j]; + n1 = ns[4][0]; + n2 = ns[i][(j + 1) % 8]; + n3 = ns[i][j]; + this.triangle(v1,v2,v3,n1,n2,n3,color); + } + } else if(this.wireframe) { + v1 = vs[i][j]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i + 1][j]; + this.line(v1,v2,color); + this.line(v1,v3,color); + } else { + v1 = vs[i][j]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i + 1][j]; + v4 = vs[i + 1][(j + 1) % 8]; + n1 = ns[i][j]; + n2 = ns[i][(j + 1) % 8]; + n3 = ns[i + 1][j]; + n4 = ns[i + 1][(j + 1) % 8]; + this.rect(v1,v3,v4,v2,n1,n3,n4,n2,color); + } + } + } + let _this5 = this.p; + let _this6 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + _this6.x = o.x; + _this6.y = o.y; + _this6.z = o.z; + let _this7 = _this6; + _this7.x += ey.x * halfHeight; + _this7.y += ey.y * halfHeight; + _this7.z += ey.z * halfHeight; + let _this8 = this.p; + let _this9 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + _this9.x = o.x; + _this9.y = o.y; + _this9.z = o.z; + let _this10 = _this9; + let s = -halfHeight; + _this10.x += ey.x * s; + _this10.y += ey.y * s; + _this10.z += ey.z * s; + if(this.wireframe) { + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = _this7.x; + _this1.y = _this7.y; + _this1.z = _this7.z; + let _this2 = _this1; + let s = -radius; + _this2.x += ex.x * s; + _this2.y += ex.y * s; + _this2.z += ex.z * s; + _this2.x += ez.x * 0; + _this2.y += ez.y * 0; + _this2.z += ez.z * 0; + let _this3 = this.p; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = _this7.x; + _this4.y = _this7.y; + _this4.z = _this7.z; + let _this5 = _this4; + _this5.x += ex.x * radius; + _this5.y += ex.y * radius; + _this5.z += ex.z * radius; + _this5.x += ez.x * 0; + _this5.y += ez.y * 0; + _this5.z += ez.z * 0; + let _this6 = this.p; + let _this8 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + _this8.x = _this7.x; + _this8.y = _this7.y; + _this8.z = _this7.z; + let _this9 = _this8; + _this9.x += ex.x * 0; + _this9.y += ex.y * 0; + _this9.z += ex.z * 0; + let s1 = -radius; + _this9.x += ez.x * s1; + _this9.y += ez.y * s1; + _this9.z += ez.z * s1; + let _this11 = this.p; + let _this12 = _this11.sizeVec3 == 0 ? new oimo.common.Vec3() : _this11.stackVec3[--_this11.sizeVec3]; + _this12.x = _this7.x; + _this12.y = _this7.y; + _this12.z = _this7.z; + let _this13 = _this12; + _this13.x += ex.x * 0; + _this13.y += ex.y * 0; + _this13.z += ex.z * 0; + _this13.x += ez.x * radius; + _this13.y += ez.y * radius; + _this13.z += ez.z * radius; + let _this14 = this.p; + let _this15 = _this14.sizeVec3 == 0 ? new oimo.common.Vec3() : _this14.stackVec3[--_this14.sizeVec3]; + _this15.x = _this10.x; + _this15.y = _this10.y; + _this15.z = _this10.z; + let _this16 = _this15; + let s2 = -radius; + _this16.x += ex.x * s2; + _this16.y += ex.y * s2; + _this16.z += ex.z * s2; + _this16.x += ez.x * 0; + _this16.y += ez.y * 0; + _this16.z += ez.z * 0; + let _this17 = this.p; + let _this18 = _this17.sizeVec3 == 0 ? new oimo.common.Vec3() : _this17.stackVec3[--_this17.sizeVec3]; + _this18.x = _this10.x; + _this18.y = _this10.y; + _this18.z = _this10.z; + let _this19 = _this18; + _this19.x += ex.x * radius; + _this19.y += ex.y * radius; + _this19.z += ex.z * radius; + _this19.x += ez.x * 0; + _this19.y += ez.y * 0; + _this19.z += ez.z * 0; + let _this20 = this.p; + let _this21 = _this20.sizeVec3 == 0 ? new oimo.common.Vec3() : _this20.stackVec3[--_this20.sizeVec3]; + _this21.x = _this10.x; + _this21.y = _this10.y; + _this21.z = _this10.z; + let _this22 = _this21; + _this22.x += ex.x * 0; + _this22.y += ex.y * 0; + _this22.z += ex.z * 0; + let s3 = -radius; + _this22.x += ez.x * s3; + _this22.y += ez.y * s3; + _this22.z += ez.z * s3; + let _this23 = this.p; + let _this24 = _this23.sizeVec3 == 0 ? new oimo.common.Vec3() : _this23.stackVec3[--_this23.sizeVec3]; + _this24.x = _this10.x; + _this24.y = _this10.y; + _this24.z = _this10.z; + let _this25 = _this24; + _this25.x += ex.x * 0; + _this25.y += ex.y * 0; + _this25.z += ex.z * 0; + _this25.x += ez.x * radius; + _this25.y += ez.y * radius; + _this25.z += ez.z * radius; + this.ellipse(_this7,ex,ez,radius,radius,color); + this.ellipse(_this10,ex,ez,radius,radius,color); + this.line(_this2,_this16,color); + this.line(_this5,_this19,color); + this.line(_this9,_this22,color); + this.line(_this13,_this25,color); + let _this26 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this26.sizeVec3 == _this26.stackVec3.length) { + let newArray = new Array(_this26.sizeVec3 << 1); + let _g = 0; + let _g1 = _this26.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this26.stackVec3[i]; + _this26.stackVec3[i] = null; + } + _this26.stackVec3 = newArray; + } + _this26.stackVec3[_this26.sizeVec3++] = _this2; + } + let _this27 = this.p; + if(_this5 != null) { + _this5.zero(); + if(_this27.sizeVec3 == _this27.stackVec3.length) { + let newArray = new Array(_this27.sizeVec3 << 1); + let _g = 0; + let _g1 = _this27.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this27.stackVec3[i]; + _this27.stackVec3[i] = null; + } + _this27.stackVec3 = newArray; + } + _this27.stackVec3[_this27.sizeVec3++] = _this5; + } + let _this28 = this.p; + if(_this9 != null) { + _this9.zero(); + if(_this28.sizeVec3 == _this28.stackVec3.length) { + let newArray = new Array(_this28.sizeVec3 << 1); + let _g = 0; + let _g1 = _this28.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this28.stackVec3[i]; + _this28.stackVec3[i] = null; + } + _this28.stackVec3 = newArray; + } + _this28.stackVec3[_this28.sizeVec3++] = _this9; + } + let _this29 = this.p; + if(_this13 != null) { + _this13.zero(); + if(_this29.sizeVec3 == _this29.stackVec3.length) { + let newArray = new Array(_this29.sizeVec3 << 1); + let _g = 0; + let _g1 = _this29.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this29.stackVec3[i]; + _this29.stackVec3[i] = null; + } + _this29.stackVec3 = newArray; + } + _this29.stackVec3[_this29.sizeVec3++] = _this13; + } + let _this30 = this.p; + if(_this16 != null) { + _this16.zero(); + if(_this30.sizeVec3 == _this30.stackVec3.length) { + let newArray = new Array(_this30.sizeVec3 << 1); + let _g = 0; + let _g1 = _this30.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this30.stackVec3[i]; + _this30.stackVec3[i] = null; + } + _this30.stackVec3 = newArray; + } + _this30.stackVec3[_this30.sizeVec3++] = _this16; + } + let _this31 = this.p; + if(_this19 != null) { + _this19.zero(); + if(_this31.sizeVec3 == _this31.stackVec3.length) { + let newArray = new Array(_this31.sizeVec3 << 1); + let _g = 0; + let _g1 = _this31.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this31.stackVec3[i]; + _this31.stackVec3[i] = null; + } + _this31.stackVec3 = newArray; + } + _this31.stackVec3[_this31.sizeVec3++] = _this19; + } + let _this32 = this.p; + if(_this22 != null) { + _this22.zero(); + if(_this32.sizeVec3 == _this32.stackVec3.length) { + let newArray = new Array(_this32.sizeVec3 << 1); + let _g = 0; + let _g1 = _this32.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this32.stackVec3[i]; + _this32.stackVec3[i] = null; + } + _this32.stackVec3 = newArray; + } + _this32.stackVec3[_this32.sizeVec3++] = _this22; + } + let _this33 = this.p; + if(_this25 != null) { + _this25.zero(); + if(_this33.sizeVec3 == _this33.stackVec3.length) { + let newArray = new Array(_this33.sizeVec3 << 1); + let _g = 0; + let _g1 = _this33.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this33.stackVec3[i]; + _this33.stackVec3[i] = null; + } + _this33.stackVec3 = newArray; + } + _this33.stackVec3[_this33.sizeVec3++] = _this25; + } + } else { + let _g = 0; + while(_g < 8) { + let i = _g++; + let _this = this.tmpCircleNorms[i]; + let v = this.circleCoords[i]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let y = _this.x * m.e10 + _this.y * m.e11 + _this.z * m.e12; + let z = _this.x * m.e20 + _this.y * m.e21 + _this.z * m.e22; + _this.x = _this.x * m.e00 + _this.y * m.e01 + _this.z * m.e02; + _this.y = y; + _this.z = z; + let _this1 = this.tmpCircleVerts1[i]; + let v1 = this.tmpCircleNorms[i]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + _this1.x *= radius; + _this1.y *= radius; + _this1.z *= radius; + _this1.x += o.x; + _this1.y += o.y; + _this1.z += o.z; + let _this2 = this.tmpCircleVerts2[i]; + let v2 = this.tmpCircleVerts1[i]; + _this2.x = v2.x; + _this2.y = v2.y; + _this2.z = v2.z; + let _this3 = this.tmpCircleVerts1[i]; + _this3.x += ey.x * halfHeight; + _this3.y += ey.y * halfHeight; + _this3.z += ey.z * halfHeight; + let _this4 = this.tmpCircleVerts2[i]; + let s = -halfHeight; + _this4.x += ey.x * s; + _this4.y += ey.y * s; + _this4.z += ey.z * s; + } + let _g1 = 0; + while(_g1 < 8) { + let i = _g1++; + let n1 = this.tmpCircleNorms[i]; + let n2 = this.tmpCircleNorms[(i + 1) % 8]; + this.rect(this.tmpCircleVerts1[i],this.tmpCircleVerts2[i],this.tmpCircleVerts2[(i + 1) % 8],this.tmpCircleVerts1[(i + 1) % 8],n1,n1,n2,n2,color); + } + } + let _this11 = this.p; + if(_this7 != null) { + _this7.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = _this7; + } + let _this12 = this.p; + if(_this10 != null) { + _this10.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = _this10; + } + let _this13 = this.p; + if(o != null) { + o.zero(); + if(_this13.sizeVec3 == _this13.stackVec3.length) { + let newArray = new Array(_this13.sizeVec3 << 1); + let _g = 0; + let _g1 = _this13.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this13.stackVec3[i]; + _this13.stackVec3[i] = null; + } + _this13.stackVec3 = newArray; + } + _this13.stackVec3[_this13.sizeVec3++] = o; + } + let _this14 = this.p; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this14.sizeMat3 == _this14.stackMat3.length) { + let newArray = new Array(_this14.sizeMat3 << 1); + let _g = 0; + let _g1 = _this14.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackMat3[i]; + _this14.stackMat3[i] = null; + } + _this14.stackMat3 = newArray; + } + _this14.stackMat3[_this14.sizeMat3++] = m; + } + let _this15 = this.p; + if(ex != null) { + ex.zero(); + if(_this15.sizeVec3 == _this15.stackVec3.length) { + let newArray = new Array(_this15.sizeVec3 << 1); + let _g = 0; + let _g1 = _this15.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this15.stackVec3[i]; + _this15.stackVec3[i] = null; + } + _this15.stackVec3 = newArray; + } + _this15.stackVec3[_this15.sizeVec3++] = ex; + } + let _this16 = this.p; + if(ey != null) { + ey.zero(); + if(_this16.sizeVec3 == _this16.stackVec3.length) { + let newArray = new Array(_this16.sizeVec3 << 1); + let _g = 0; + let _g1 = _this16.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this16.stackVec3[i]; + _this16.stackVec3[i] = null; + } + _this16.stackVec3 = newArray; + } + _this16.stackVec3[_this16.sizeVec3++] = ey; + } + let _this17 = this.p; + if(ez != null) { + ez.zero(); + if(_this17.sizeVec3 == _this17.stackVec3.length) { + let newArray = new Array(_this17.sizeVec3 << 1); + let _g = 0; + let _g1 = _this17.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this17.stackVec3[i]; + _this17.stackVec3[i] = null; + } + _this17.stackVec3 = newArray; + } + _this17.stackVec3[_this17.sizeVec3++] = ez; + } + } + sphere(tf,radius,color) { + let _this = this.p; + let o = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let m = _this1.sizeMat3 == 0 ? new oimo.common.Mat3() : _this1.stackMat3[--_this1.sizeMat3]; + let v = o; + v.x = tf._positionX; + v.y = tf._positionY; + v.z = tf._positionZ; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + let vs = this.tmpSphereVerts; + let ns = this.tmpSphereNorms; + let _g = 0; + while(_g < 5) { + let i = _g++; + let n = this.tmpSphereVerts[i].length; + let _g1 = 0; + while(_g1 < n) { + let j = _g1++; + let _this = ns[i][j]; + let v = this.sphereCoords[i][j]; + _this.x = v.x; + _this.y = v.y; + _this.z = v.z; + let y = _this.x * m.e10 + _this.y * m.e11 + _this.z * m.e12; + let z = _this.x * m.e20 + _this.y * m.e21 + _this.z * m.e22; + _this.x = _this.x * m.e00 + _this.y * m.e01 + _this.z * m.e02; + _this.y = y; + _this.z = z; + let _this1 = vs[i][j]; + let v1 = ns[i][j]; + _this1.x = v1.x; + _this1.y = v1.y; + _this1.z = v1.z; + _this1.x *= radius; + _this1.y *= radius; + _this1.z *= radius; + _this1.x += o.x; + _this1.y += o.y; + _this1.z += o.z; + } + } + let _g1 = 0; + while(_g1 < 4) { + let i = _g1++; + let _g = 0; + while(_g < 8) { + let j = _g++; + let v1; + let v2; + let v3; + let v4; + let n1; + let n2; + let n3; + let n4; + if(i == 0) { + if(this.wireframe) { + v1 = vs[0][0]; + v2 = vs[1][j]; + this.line(v1,v2,color); + } else { + v1 = vs[0][0]; + v2 = vs[1][j]; + v3 = vs[1][(j + 1) % 8]; + n1 = ns[0][0]; + n2 = ns[1][j]; + n3 = ns[1][(j + 1) % 8]; + this.triangle(v1,v2,v3,n1,n2,n3,color); + } + } else if(i == 3) { + if(this.wireframe) { + v1 = vs[4][0]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i][j]; + this.line(v1,v2,color); + this.line(v2,v3,color); + } else { + v1 = vs[4][0]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i][j]; + n1 = ns[4][0]; + n2 = ns[i][(j + 1) % 8]; + n3 = ns[i][j]; + this.triangle(v1,v2,v3,n1,n2,n3,color); + } + } else if(this.wireframe) { + v1 = vs[i][j]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i + 1][j]; + this.line(v1,v2,color); + this.line(v1,v3,color); + } else { + v1 = vs[i][j]; + v2 = vs[i][(j + 1) % 8]; + v3 = vs[i + 1][j]; + v4 = vs[i + 1][(j + 1) % 8]; + n1 = ns[i][j]; + n2 = ns[i][(j + 1) % 8]; + n3 = ns[i + 1][j]; + n4 = ns[i + 1][(j + 1) % 8]; + this.rect(v1,v3,v4,v2,n1,n3,n4,n2,color); + } + } + } + let _this2 = this.p; + if(o != null) { + o.zero(); + if(_this2.sizeVec3 == _this2.stackVec3.length) { + let newArray = new Array(_this2.sizeVec3 << 1); + let _g = 0; + let _g1 = _this2.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this2.stackVec3[i]; + _this2.stackVec3[i] = null; + } + _this2.stackVec3 = newArray; + } + _this2.stackVec3[_this2.sizeVec3++] = o; + } + let _this3 = this.p; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this3.sizeMat3 == _this3.stackMat3.length) { + let newArray = new Array(_this3.sizeMat3 << 1); + let _g = 0; + let _g1 = _this3.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this3.stackMat3[i]; + _this3.stackMat3[i] = null; + } + _this3.stackMat3 = newArray; + } + _this3.stackMat3[_this3.sizeMat3++] = m; + } + } + box(tf,halfExtents,color) { + let _this = this.p; + let ex = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + let _this1 = this.p; + let ey = _this1.sizeVec3 == 0 ? new oimo.common.Vec3() : _this1.stackVec3[--_this1.sizeVec3]; + let _this2 = this.p; + let ez = _this2.sizeVec3 == 0 ? new oimo.common.Vec3() : _this2.stackVec3[--_this2.sizeVec3]; + let _this3 = this.p; + let o = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + let _this4 = this.p; + let m = _this4.sizeMat3 == 0 ? new oimo.common.Mat3() : _this4.stackMat3[--_this4.sizeMat3]; + let v = o; + v.x = tf._positionX; + v.y = tf._positionY; + v.z = tf._positionZ; + let m1 = m; + m1.e00 = tf._rotation00; + m1.e01 = tf._rotation01; + m1.e02 = tf._rotation02; + m1.e10 = tf._rotation10; + m1.e11 = tf._rotation11; + m1.e12 = tf._rotation12; + m1.e20 = tf._rotation20; + m1.e21 = tf._rotation21; + m1.e22 = tf._rotation22; + ex.init(m.e00,m.e10,m.e20); + ey.init(m.e01,m.e11,m.e21); + ez.init(m.e02,m.e12,m.e22); + let hx = halfExtents.x; + let hy = halfExtents.y; + let hz = halfExtents.z; + let _this5 = this.p; + let _this6 = _this5.sizeVec3 == 0 ? new oimo.common.Vec3() : _this5.stackVec3[--_this5.sizeVec3]; + _this6.x = o.x; + _this6.y = o.y; + _this6.z = o.z; + let _this7 = _this6; + let s = -hx; + _this7.x += ex.x * s; + _this7.y += ex.y * s; + _this7.z += ex.z * s; + let s1 = -hy; + _this7.x += ey.x * s1; + _this7.y += ey.y * s1; + _this7.z += ey.z * s1; + let s2 = -hz; + _this7.x += ez.x * s2; + _this7.y += ez.y * s2; + _this7.z += ez.z * s2; + let _this8 = this.p; + let _this9 = _this8.sizeVec3 == 0 ? new oimo.common.Vec3() : _this8.stackVec3[--_this8.sizeVec3]; + _this9.x = o.x; + _this9.y = o.y; + _this9.z = o.z; + let _this10 = _this9; + let s3 = -hx; + _this10.x += ex.x * s3; + _this10.y += ex.y * s3; + _this10.z += ex.z * s3; + let s4 = -hy; + _this10.x += ey.x * s4; + _this10.y += ey.y * s4; + _this10.z += ey.z * s4; + _this10.x += ez.x * hz; + _this10.y += ez.y * hz; + _this10.z += ez.z * hz; + let _this11 = this.p; + let _this12 = _this11.sizeVec3 == 0 ? new oimo.common.Vec3() : _this11.stackVec3[--_this11.sizeVec3]; + _this12.x = o.x; + _this12.y = o.y; + _this12.z = o.z; + let _this13 = _this12; + let s5 = -hx; + _this13.x += ex.x * s5; + _this13.y += ex.y * s5; + _this13.z += ex.z * s5; + _this13.x += ey.x * hy; + _this13.y += ey.y * hy; + _this13.z += ey.z * hy; + let s6 = -hz; + _this13.x += ez.x * s6; + _this13.y += ez.y * s6; + _this13.z += ez.z * s6; + let _this14 = this.p; + let _this15 = _this14.sizeVec3 == 0 ? new oimo.common.Vec3() : _this14.stackVec3[--_this14.sizeVec3]; + _this15.x = o.x; + _this15.y = o.y; + _this15.z = o.z; + let _this16 = _this15; + let s7 = -hx; + _this16.x += ex.x * s7; + _this16.y += ex.y * s7; + _this16.z += ex.z * s7; + _this16.x += ey.x * hy; + _this16.y += ey.y * hy; + _this16.z += ey.z * hy; + _this16.x += ez.x * hz; + _this16.y += ez.y * hz; + _this16.z += ez.z * hz; + let _this17 = this.p; + let _this18 = _this17.sizeVec3 == 0 ? new oimo.common.Vec3() : _this17.stackVec3[--_this17.sizeVec3]; + _this18.x = o.x; + _this18.y = o.y; + _this18.z = o.z; + let _this19 = _this18; + _this19.x += ex.x * hx; + _this19.y += ex.y * hx; + _this19.z += ex.z * hx; + let s8 = -hy; + _this19.x += ey.x * s8; + _this19.y += ey.y * s8; + _this19.z += ey.z * s8; + let s9 = -hz; + _this19.x += ez.x * s9; + _this19.y += ez.y * s9; + _this19.z += ez.z * s9; + let _this20 = this.p; + let _this21 = _this20.sizeVec3 == 0 ? new oimo.common.Vec3() : _this20.stackVec3[--_this20.sizeVec3]; + _this21.x = o.x; + _this21.y = o.y; + _this21.z = o.z; + let _this22 = _this21; + _this22.x += ex.x * hx; + _this22.y += ex.y * hx; + _this22.z += ex.z * hx; + let s10 = -hy; + _this22.x += ey.x * s10; + _this22.y += ey.y * s10; + _this22.z += ey.z * s10; + _this22.x += ez.x * hz; + _this22.y += ez.y * hz; + _this22.z += ez.z * hz; + let _this23 = this.p; + let _this24 = _this23.sizeVec3 == 0 ? new oimo.common.Vec3() : _this23.stackVec3[--_this23.sizeVec3]; + _this24.x = o.x; + _this24.y = o.y; + _this24.z = o.z; + let _this25 = _this24; + _this25.x += ex.x * hx; + _this25.y += ex.y * hx; + _this25.z += ex.z * hx; + _this25.x += ey.x * hy; + _this25.y += ey.y * hy; + _this25.z += ey.z * hy; + let s11 = -hz; + _this25.x += ez.x * s11; + _this25.y += ez.y * s11; + _this25.z += ez.z * s11; + let _this26 = this.p; + let _this27 = _this26.sizeVec3 == 0 ? new oimo.common.Vec3() : _this26.stackVec3[--_this26.sizeVec3]; + _this27.x = o.x; + _this27.y = o.y; + _this27.z = o.z; + let _this28 = _this27; + _this28.x += ex.x * hx; + _this28.y += ex.y * hx; + _this28.z += ex.z * hx; + _this28.x += ey.x * hy; + _this28.y += ey.y * hy; + _this28.z += ey.z * hy; + _this28.x += ez.x * hz; + _this28.y += ez.y * hz; + _this28.z += ez.z * hz; + if(this.wireframe) { + this.line(_this7,_this10,color); + this.line(_this13,_this16,color); + this.line(_this19,_this22,color); + this.line(_this25,_this28,color); + this.line(_this7,_this13,color); + this.line(_this10,_this16,color); + this.line(_this19,_this25,color); + this.line(_this22,_this28,color); + this.line(_this7,_this19,color); + this.line(_this10,_this22,color); + this.line(_this13,_this25,color); + this.line(_this16,_this28,color); + } else { + let _this = this.p; + let _this1 = _this.sizeVec3 == 0 ? new oimo.common.Vec3() : _this.stackVec3[--_this.sizeVec3]; + _this1.x = ex.x; + _this1.y = ex.y; + _this1.z = ex.z; + let _this2 = _this1; + _this2.x = -_this2.x; + _this2.y = -_this2.y; + _this2.z = -_this2.z; + let _this3 = this.p; + let _this4 = _this3.sizeVec3 == 0 ? new oimo.common.Vec3() : _this3.stackVec3[--_this3.sizeVec3]; + _this4.x = ey.x; + _this4.y = ey.y; + _this4.z = ey.z; + let _this5 = _this4; + _this5.x = -_this5.x; + _this5.y = -_this5.y; + _this5.z = -_this5.z; + let _this6 = this.p; + let _this8 = _this6.sizeVec3 == 0 ? new oimo.common.Vec3() : _this6.stackVec3[--_this6.sizeVec3]; + _this8.x = ez.x; + _this8.y = ez.y; + _this8.z = ez.z; + let _this9 = _this8; + _this9.x = -_this9.x; + _this9.y = -_this9.y; + _this9.z = -_this9.z; + this.rect(_this7,_this10,_this16,_this13,_this2,_this2,_this2,_this2,color); + this.rect(_this19,_this25,_this28,_this22,ex,ex,ex,ex,color); + this.rect(_this7,_this19,_this22,_this10,_this5,_this5,_this5,_this5,color); + this.rect(_this13,_this16,_this28,_this25,ey,ey,ey,ey,color); + this.rect(_this7,_this13,_this25,_this19,_this9,_this9,_this9,_this9,color); + this.rect(_this10,_this22,_this28,_this16,ez,ez,ez,ez,color); + let _this11 = this.p; + if(_this2 != null) { + _this2.zero(); + if(_this11.sizeVec3 == _this11.stackVec3.length) { + let newArray = new Array(_this11.sizeVec3 << 1); + let _g = 0; + let _g1 = _this11.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this11.stackVec3[i]; + _this11.stackVec3[i] = null; + } + _this11.stackVec3 = newArray; + } + _this11.stackVec3[_this11.sizeVec3++] = _this2; + } + let _this12 = this.p; + if(_this5 != null) { + _this5.zero(); + if(_this12.sizeVec3 == _this12.stackVec3.length) { + let newArray = new Array(_this12.sizeVec3 << 1); + let _g = 0; + let _g1 = _this12.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this12.stackVec3[i]; + _this12.stackVec3[i] = null; + } + _this12.stackVec3 = newArray; + } + _this12.stackVec3[_this12.sizeVec3++] = _this5; + } + let _this14 = this.p; + if(_this9 != null) { + _this9.zero(); + if(_this14.sizeVec3 == _this14.stackVec3.length) { + let newArray = new Array(_this14.sizeVec3 << 1); + let _g = 0; + let _g1 = _this14.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this14.stackVec3[i]; + _this14.stackVec3[i] = null; + } + _this14.stackVec3 = newArray; + } + _this14.stackVec3[_this14.sizeVec3++] = _this9; + } + } + let _this29 = this.p; + if(_this7 != null) { + _this7.zero(); + if(_this29.sizeVec3 == _this29.stackVec3.length) { + let newArray = new Array(_this29.sizeVec3 << 1); + let _g = 0; + let _g1 = _this29.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this29.stackVec3[i]; + _this29.stackVec3[i] = null; + } + _this29.stackVec3 = newArray; + } + _this29.stackVec3[_this29.sizeVec3++] = _this7; + } + let _this30 = this.p; + if(_this10 != null) { + _this10.zero(); + if(_this30.sizeVec3 == _this30.stackVec3.length) { + let newArray = new Array(_this30.sizeVec3 << 1); + let _g = 0; + let _g1 = _this30.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this30.stackVec3[i]; + _this30.stackVec3[i] = null; + } + _this30.stackVec3 = newArray; + } + _this30.stackVec3[_this30.sizeVec3++] = _this10; + } + let _this31 = this.p; + if(_this13 != null) { + _this13.zero(); + if(_this31.sizeVec3 == _this31.stackVec3.length) { + let newArray = new Array(_this31.sizeVec3 << 1); + let _g = 0; + let _g1 = _this31.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this31.stackVec3[i]; + _this31.stackVec3[i] = null; + } + _this31.stackVec3 = newArray; + } + _this31.stackVec3[_this31.sizeVec3++] = _this13; + } + let _this32 = this.p; + if(_this16 != null) { + _this16.zero(); + if(_this32.sizeVec3 == _this32.stackVec3.length) { + let newArray = new Array(_this32.sizeVec3 << 1); + let _g = 0; + let _g1 = _this32.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this32.stackVec3[i]; + _this32.stackVec3[i] = null; + } + _this32.stackVec3 = newArray; + } + _this32.stackVec3[_this32.sizeVec3++] = _this16; + } + let _this33 = this.p; + if(_this19 != null) { + _this19.zero(); + if(_this33.sizeVec3 == _this33.stackVec3.length) { + let newArray = new Array(_this33.sizeVec3 << 1); + let _g = 0; + let _g1 = _this33.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this33.stackVec3[i]; + _this33.stackVec3[i] = null; + } + _this33.stackVec3 = newArray; + } + _this33.stackVec3[_this33.sizeVec3++] = _this19; + } + let _this34 = this.p; + if(_this22 != null) { + _this22.zero(); + if(_this34.sizeVec3 == _this34.stackVec3.length) { + let newArray = new Array(_this34.sizeVec3 << 1); + let _g = 0; + let _g1 = _this34.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this34.stackVec3[i]; + _this34.stackVec3[i] = null; + } + _this34.stackVec3 = newArray; + } + _this34.stackVec3[_this34.sizeVec3++] = _this22; + } + let _this35 = this.p; + if(_this25 != null) { + _this25.zero(); + if(_this35.sizeVec3 == _this35.stackVec3.length) { + let newArray = new Array(_this35.sizeVec3 << 1); + let _g = 0; + let _g1 = _this35.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this35.stackVec3[i]; + _this35.stackVec3[i] = null; + } + _this35.stackVec3 = newArray; + } + _this35.stackVec3[_this35.sizeVec3++] = _this25; + } + let _this36 = this.p; + if(_this28 != null) { + _this28.zero(); + if(_this36.sizeVec3 == _this36.stackVec3.length) { + let newArray = new Array(_this36.sizeVec3 << 1); + let _g = 0; + let _g1 = _this36.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this36.stackVec3[i]; + _this36.stackVec3[i] = null; + } + _this36.stackVec3 = newArray; + } + _this36.stackVec3[_this36.sizeVec3++] = _this28; + } + let _this37 = this.p; + if(o != null) { + o.zero(); + if(_this37.sizeVec3 == _this37.stackVec3.length) { + let newArray = new Array(_this37.sizeVec3 << 1); + let _g = 0; + let _g1 = _this37.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this37.stackVec3[i]; + _this37.stackVec3[i] = null; + } + _this37.stackVec3 = newArray; + } + _this37.stackVec3[_this37.sizeVec3++] = o; + } + let _this38 = this.p; + if(m != null) { + m.e00 = 1; + m.e01 = 0; + m.e02 = 0; + m.e10 = 0; + m.e11 = 1; + m.e12 = 0; + m.e20 = 0; + m.e21 = 0; + m.e22 = 1; + if(_this38.sizeMat3 == _this38.stackMat3.length) { + let newArray = new Array(_this38.sizeMat3 << 1); + let _g = 0; + let _g1 = _this38.sizeMat3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this38.stackMat3[i]; + _this38.stackMat3[i] = null; + } + _this38.stackMat3 = newArray; + } + _this38.stackMat3[_this38.sizeMat3++] = m; + } + let _this39 = this.p; + if(ex != null) { + ex.zero(); + if(_this39.sizeVec3 == _this39.stackVec3.length) { + let newArray = new Array(_this39.sizeVec3 << 1); + let _g = 0; + let _g1 = _this39.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this39.stackVec3[i]; + _this39.stackVec3[i] = null; + } + _this39.stackVec3 = newArray; + } + _this39.stackVec3[_this39.sizeVec3++] = ex; + } + let _this40 = this.p; + if(ey != null) { + ey.zero(); + if(_this40.sizeVec3 == _this40.stackVec3.length) { + let newArray = new Array(_this40.sizeVec3 << 1); + let _g = 0; + let _g1 = _this40.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this40.stackVec3[i]; + _this40.stackVec3[i] = null; + } + _this40.stackVec3 = newArray; + } + _this40.stackVec3[_this40.sizeVec3++] = ey; + } + let _this41 = this.p; + if(ez != null) { + ez.zero(); + if(_this41.sizeVec3 == _this41.stackVec3.length) { + let newArray = new Array(_this41.sizeVec3 << 1); + let _g = 0; + let _g1 = _this41.sizeVec3; + while(_g < _g1) { + let i = _g++; + newArray[i] = _this41.stackVec3[i]; + _this41.stackVec3[i] = null; + } + _this41.stackVec3 = newArray; + } + _this41.stackVec3[_this41.sizeVec3++] = ez; + } + } + rect(v1,v2,v3,v4,n1,n2,n3,n4,color) { + this.triangle(v1,v2,v3,n1,n2,n3,color); + this.triangle(v1,v3,v4,n1,n3,n4,color); + } + point(v,color) { + } + triangle(v1,v2,v3,n1,n2,n3,color) { + } + line(v1,v2,color) { + } +} +oimo.dynamics.common.DebugDrawStyle = class oimo_dynamics_common_DebugDrawStyle { + constructor() { + this.basisColorZ = new oimo.common.Vec3(0.0,0.0,1.0); + this.basisColorY = new oimo.common.Vec3(0.0,1.0,0.0); + this.basisColorX = new oimo.common.Vec3(1.0,0.0,0.0); + this.basisLength = 0.5; + this.jointRotationalConstraintRadius = 0.3; + this.jointErrorColor = new oimo.common.Vec3(1.0,0.1,0.1); + this.jointLineColor = new oimo.common.Vec3(0.8,0.8,0.8); + this.contactBinormalLength = 0.5; + this.contactTangentLength = 0.5; + this.contactNormalLength = 0.5; + this.contactBinormalColor = new oimo.common.Vec3(0.2,0.2,1.0); + this.contactTangentColor = new oimo.common.Vec3(0.1,0.8,0.1); + this.contactNormalColor = new oimo.common.Vec3(1.0,0.1,0.1); + this.disabledContactColor = new oimo.common.Vec3(0.5,0.1,0.1); + this.newContactColor = new oimo.common.Vec3(1.0,1.0,0.1); + this.contactColor4 = new oimo.common.Vec3(0.8,0.1,1.0); + this.contactColor3 = new oimo.common.Vec3(0.1,0.8,0.6); + this.contactColor2 = new oimo.common.Vec3(1.0,0.6,0.1); + this.contactColor = new oimo.common.Vec3(1.0,0.1,0.1); + this.pairColor = new oimo.common.Vec3(1.0,1.0,0.1); + this.bvhNodeColor = new oimo.common.Vec3(0.4,0.4,0.4); + this.aabbColor = new oimo.common.Vec3(1.0,0.1,0.1); + this.kinematicShapeColor = new oimo.common.Vec3(1.0,0.5,0.1); + this.staticShapeColor = new oimo.common.Vec3(0.7,0.7,0.7); + this.sleepingShapeColor2 = new oimo.common.Vec3(0.2,0.8,0.5); + this.sleepingShapeColor1 = new oimo.common.Vec3(0.3,0.3,0.8); + this.sleepyShapeColor2 = new oimo.common.Vec3(0.6,0.8,0.3); + this.sleepyShapeColor1 = new oimo.common.Vec3(0.5,0.25,0.6); + this.shapeColor2 = new oimo.common.Vec3(1.0,0.8,0.1); + this.shapeColor1 = new oimo.common.Vec3(0.7,0.2,0.4); + } +} +oimo.dynamics.common.Performance = class oimo_dynamics_common_Performance { +} +if(!oimo.dynamics.constraint) oimo.dynamics.constraint = {}; +oimo.dynamics.constraint.ConstraintSolver = class oimo_dynamics_constraint_ConstraintSolver { + constructor() { + this._b1 = null; + this._b2 = null; + this._addedToIsland = false; + } + preSolveVelocity(timeStep) { + } + warmStart(timeStep) { + } + solveVelocity() { + } + postSolveVelocity(timeStep) { + } + preSolvePosition(timeStep) { + } + solvePositionSplitImpulse() { + } + solvePositionNgs(timeStep) { + } + postSolve() { + } +} +oimo.dynamics.constraint.PositionCorrectionAlgorithm = class oimo_dynamics_constraint_PositionCorrectionAlgorithm { +} +if(!oimo.dynamics.constraint.contact) oimo.dynamics.constraint.contact = {}; +oimo.dynamics.constraint.contact.ContactConstraint = class oimo_dynamics_constraint_contact_ContactConstraint { + constructor(manifold) { + this._solver = new oimo.dynamics.constraint.solver.pgs.PgsContactConstraintSolver(this); + this._manifold = manifold; + } + _getVelocitySolverInfo(timeStep,info) { + info.b1 = this._b1; + info.b2 = this._b2; + let normalX; + let normalY; + let normalZ; + let tangentX; + let tangentY; + let tangentZ; + let binormalX; + let binormalY; + let binormalZ; + normalX = this._manifold._normalX; + normalY = this._manifold._normalY; + normalZ = this._manifold._normalZ; + tangentX = this._manifold._tangentX; + tangentY = this._manifold._tangentY; + tangentZ = this._manifold._tangentZ; + binormalX = this._manifold._binormalX; + binormalY = this._manifold._binormalY; + binormalZ = this._manifold._binormalZ; + let friction = Math.sqrt(this._s1._friction * this._s2._friction); + let restitution = Math.sqrt(this._s1._restitution * this._s2._restitution); + let num = this._manifold._numPoints; + info.numRows = 0; + let _g = 0; + while(_g < num) { + let p = this._manifold._points[_g++]; + if(p._depth < 0) { + p._disabled = true; + let _this = p._impulse; + _this.impulseN = 0; + _this.impulseT = 0; + _this.impulseB = 0; + _this.impulseP = 0; + _this.impulseLX = 0; + _this.impulseLY = 0; + _this.impulseLZ = 0; + continue; + } else { + p._disabled = false; + } + let row = info.rows[info.numRows++]; + row.friction = friction; + row.cfm = 0; + let j = row.jacobianN; + j.lin1X = normalX; + j.lin1Y = normalY; + j.lin1Z = normalZ; + j.lin2X = normalX; + j.lin2Y = normalY; + j.lin2Z = normalZ; + j.ang1X = p._relPos1Y * normalZ - p._relPos1Z * normalY; + j.ang1Y = p._relPos1Z * normalX - p._relPos1X * normalZ; + j.ang1Z = p._relPos1X * normalY - p._relPos1Y * normalX; + j.ang2X = p._relPos2Y * normalZ - p._relPos2Z * normalY; + j.ang2Y = p._relPos2Z * normalX - p._relPos2X * normalZ; + j.ang2Z = p._relPos2X * normalY - p._relPos2Y * normalX; + j = row.jacobianT; + j.lin1X = tangentX; + j.lin1Y = tangentY; + j.lin1Z = tangentZ; + j.lin2X = tangentX; + j.lin2Y = tangentY; + j.lin2Z = tangentZ; + j.ang1X = p._relPos1Y * tangentZ - p._relPos1Z * tangentY; + j.ang1Y = p._relPos1Z * tangentX - p._relPos1X * tangentZ; + j.ang1Z = p._relPos1X * tangentY - p._relPos1Y * tangentX; + j.ang2X = p._relPos2Y * tangentZ - p._relPos2Z * tangentY; + j.ang2Y = p._relPos2Z * tangentX - p._relPos2X * tangentZ; + j.ang2Z = p._relPos2X * tangentY - p._relPos2Y * tangentX; + j = row.jacobianB; + j.lin1X = binormalX; + j.lin1Y = binormalY; + j.lin1Z = binormalZ; + j.lin2X = binormalX; + j.lin2Y = binormalY; + j.lin2Z = binormalZ; + j.ang1X = p._relPos1Y * binormalZ - p._relPos1Z * binormalY; + j.ang1Y = p._relPos1Z * binormalX - p._relPos1X * binormalZ; + j.ang1Z = p._relPos1X * binormalY - p._relPos1Y * binormalX; + j.ang2X = p._relPos2Y * binormalZ - p._relPos2Z * binormalY; + j.ang2Y = p._relPos2Z * binormalX - p._relPos2X * binormalZ; + j.ang2Z = p._relPos2X * binormalY - p._relPos2Y * binormalX; + j = row.jacobianN; + let rvn = j.lin1X * this._b1._velX + j.lin1Y * this._b1._velY + j.lin1Z * this._b1._velZ + (j.ang1X * this._b1._angVelX + j.ang1Y * this._b1._angVelY + j.ang1Z * this._b1._angVelZ) - (j.lin2X * this._b2._velX + j.lin2Y * this._b2._velY + j.lin2Z * this._b2._velZ + (j.ang2X * this._b2._angVelX + j.ang2Y * this._b2._angVelY + j.ang2Z * this._b2._angVelZ)); + if(rvn < -oimo.common.Setting.contactEnableBounceThreshold && !p._warmStarted) { + row.rhs = -rvn * restitution; + } else { + row.rhs = 0; + } + if(this._positionCorrectionAlgorithm == oimo.dynamics.constraint.PositionCorrectionAlgorithm.BAUMGARTE) { + if(p._depth > oimo.common.Setting.linearSlop) { + let minRhs = (p._depth - oimo.common.Setting.linearSlop) * oimo.common.Setting.velocityBaumgarte * timeStep.invDt; + if(row.rhs < minRhs) { + row.rhs = minRhs; + } + } + } + if(!p._warmStarted) { + let _this = p._impulse; + _this.impulseN = 0; + _this.impulseT = 0; + _this.impulseB = 0; + _this.impulseP = 0; + _this.impulseLX = 0; + _this.impulseLY = 0; + _this.impulseLZ = 0; + } + row.impulse = p._impulse; + } + } + _getPositionSolverInfo(info) { + info.b1 = this._b1; + info.b2 = this._b2; + let normalX; + let normalY; + let normalZ; + normalX = this._manifold._normalX; + normalY = this._manifold._normalY; + normalZ = this._manifold._normalZ; + let num = this._manifold._numPoints; + info.numRows = 0; + let _g = 0; + while(_g < num) { + let p = this._manifold._points[_g++]; + if(p._disabled) { + continue; + } + let row = info.rows[info.numRows++]; + let j = row.jacobianN; + j.lin1X = normalX; + j.lin1Y = normalY; + j.lin1Z = normalZ; + j.lin2X = normalX; + j.lin2Y = normalY; + j.lin2Z = normalZ; + j.ang1X = p._relPos1Y * normalZ - p._relPos1Z * normalY; + j.ang1Y = p._relPos1Z * normalX - p._relPos1X * normalZ; + j.ang1Z = p._relPos1X * normalY - p._relPos1Y * normalX; + j.ang2X = p._relPos2Y * normalZ - p._relPos2Z * normalY; + j.ang2Y = p._relPos2Z * normalX - p._relPos2X * normalZ; + j.ang2Z = p._relPos2X * normalY - p._relPos2Y * normalX; + row.rhs = p._depth - oimo.common.Setting.linearSlop; + if(row.rhs < 0) { + row.rhs = 0; + } + row.impulse = p._impulse; + } + } + _syncManifold() { + this._manifold._updateDepthsAndPositions(this._tf1,this._tf2); + } + getShape1() { + return this._s1; + } + getShape2() { + return this._s2; + } + getManifold() { + return this._manifold; + } + isTouching() { + let _g = 0; + let _g1 = this._manifold._numPoints; + while(_g < _g1) if(this._manifold._points[_g++]._depth >= 0) { + return true; + } + return false; + } +} +oimo.dynamics.constraint.contact.ContactImpulse = class oimo_dynamics_constraint_contact_ContactImpulse { + constructor() { + this.impulseN = 0; + this.impulseT = 0; + this.impulseB = 0; + this.impulseP = 0; + this.impulseLX = 0; + this.impulseLY = 0; + this.impulseLZ = 0; + } + copyFrom(imp) { + this.impulseN = imp.impulseN; + this.impulseT = imp.impulseT; + this.impulseB = imp.impulseB; + this.impulseLX = imp.impulseLX; + this.impulseLY = imp.impulseLY; + this.impulseLZ = imp.impulseLZ; + } +} +oimo.dynamics.constraint.contact.Manifold = class oimo_dynamics_constraint_contact_Manifold { + constructor() { + this._normalX = 0; + this._normalY = 0; + this._normalZ = 0; + this._tangentX = 0; + this._tangentY = 0; + this._tangentZ = 0; + this._binormalX = 0; + this._binormalY = 0; + this._binormalZ = 0; + this._numPoints = 0; + this._points = new Array(oimo.common.Setting.maxManifoldPoints); + let _g = 0; + let _g1 = oimo.common.Setting.maxManifoldPoints; + while(_g < _g1) this._points[_g++] = new oimo.dynamics.constraint.contact.ManifoldPoint(); + } + _clear() { + let _g = 0; + let _g1 = this._numPoints; + while(_g < _g1) { + let _this = this._points[_g++]; + _this._localPos1X = 0; + _this._localPos1Y = 0; + _this._localPos1Z = 0; + _this._localPos2X = 0; + _this._localPos2Y = 0; + _this._localPos2Z = 0; + _this._relPos1X = 0; + _this._relPos1Y = 0; + _this._relPos1Z = 0; + _this._relPos2X = 0; + _this._relPos2Y = 0; + _this._relPos2Z = 0; + _this._pos1X = 0; + _this._pos1Y = 0; + _this._pos1Z = 0; + _this._pos2X = 0; + _this._pos2Y = 0; + _this._pos2Z = 0; + _this._depth = 0; + let _this1 = _this._impulse; + _this1.impulseN = 0; + _this1.impulseT = 0; + _this1.impulseB = 0; + _this1.impulseP = 0; + _this1.impulseLX = 0; + _this1.impulseLY = 0; + _this1.impulseLZ = 0; + _this._warmStarted = false; + _this._disabled = false; + _this._id = -1; + } + this._numPoints = 0; + } + _buildBasis(normal) { + this._normalX = normal.x; + this._normalY = normal.y; + this._normalZ = normal.z; + let nx = normal.x; + let ny = normal.y; + let nz = normal.z; + let nx2 = nx * nx; + let ny2 = ny * ny; + let nz2 = nz * nz; + let tx; + let ty; + let tz; + let bx; + let by; + let bz; + if(nx2 < ny2) { + if(nx2 < nz2) { + let invL = 1 / Math.sqrt(ny2 + nz2); + tx = 0; + ty = -nz * invL; + tz = ny * invL; + bx = ny * tz - nz * ty; + by = -nx * tz; + bz = nx * ty; + } else { + let invL = 1 / Math.sqrt(nx2 + ny2); + tx = -ny * invL; + ty = nx * invL; + tz = 0; + bx = -nz * ty; + by = nz * tx; + bz = nx * ty - ny * tx; + } + } else if(ny2 < nz2) { + let invL = 1 / Math.sqrt(nx2 + nz2); + tx = nz * invL; + ty = 0; + tz = -nx * invL; + bx = ny * tz; + by = nz * tx - nx * tz; + bz = -ny * tx; + } else { + let invL = 1 / Math.sqrt(nx2 + ny2); + tx = -ny * invL; + ty = nx * invL; + tz = 0; + bx = -nz * ty; + by = nz * tx; + bz = nx * ty - ny * tx; + } + this._tangentX = tx; + this._tangentY = ty; + this._tangentZ = tz; + this._binormalX = bx; + this._binormalY = by; + this._binormalZ = bz; + } + _updateDepthsAndPositions(tf1,tf2) { + let _g = 0; + let _g1 = this._numPoints; + while(_g < _g1) { + let p = this._points[_g++]; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * p._localPos1X + tf1._rotation01 * p._localPos1Y + tf1._rotation02 * p._localPos1Z; + __tmp__Y = tf1._rotation10 * p._localPos1X + tf1._rotation11 * p._localPos1Y + tf1._rotation12 * p._localPos1Z; + __tmp__Z = tf1._rotation20 * p._localPos1X + tf1._rotation21 * p._localPos1Y + tf1._rotation22 * p._localPos1Z; + p._relPos1X = __tmp__X; + p._relPos1Y = __tmp__Y; + p._relPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * p._localPos2X + tf2._rotation01 * p._localPos2Y + tf2._rotation02 * p._localPos2Z; + __tmp__Y1 = tf2._rotation10 * p._localPos2X + tf2._rotation11 * p._localPos2Y + tf2._rotation12 * p._localPos2Z; + __tmp__Z1 = tf2._rotation20 * p._localPos2X + tf2._rotation21 * p._localPos2Y + tf2._rotation22 * p._localPos2Z; + p._relPos2X = __tmp__X1; + p._relPos2Y = __tmp__Y1; + p._relPos2Z = __tmp__Z1; + p._pos1X = p._relPos1X + tf1._positionX; + p._pos1Y = p._relPos1Y + tf1._positionY; + p._pos1Z = p._relPos1Z + tf1._positionZ; + p._pos2X = p._relPos2X + tf2._positionX; + p._pos2Y = p._relPos2Y + tf2._positionY; + p._pos2Z = p._relPos2Z + tf2._positionZ; + let diffX; + let diffY; + let diffZ; + diffX = p._pos1X - p._pos2X; + diffY = p._pos1Y - p._pos2Y; + diffZ = p._pos1Z - p._pos2Z; + p._depth = -(diffX * this._normalX + diffY * this._normalY + diffZ * this._normalZ); + } + } + getNormal() { + let v = new oimo.common.Vec3(); + v.x = this._normalX; + v.y = this._normalY; + v.z = this._normalZ; + return v; + } + getNormalTo(normal) { + normal.x = this._normalX; + normal.y = this._normalY; + normal.z = this._normalZ; + } + getTangent() { + let v = new oimo.common.Vec3(); + v.x = this._tangentX; + v.y = this._tangentY; + v.z = this._tangentZ; + return v; + } + getTangentTo(tangent) { + tangent.x = this._tangentX; + tangent.y = this._tangentY; + tangent.z = this._tangentZ; + } + getBinormal() { + let v = new oimo.common.Vec3(); + v.x = this._binormalX; + v.y = this._binormalY; + v.z = this._binormalZ; + return v; + } + getBinormalTo(binormal) { + binormal.x = this._binormalX; + binormal.y = this._binormalY; + binormal.z = this._binormalZ; + } + getPoints() { + return this._points; + } + getNumPoints() { + return this._numPoints; + } +} +oimo.dynamics.constraint.contact.ManifoldPoint = class oimo_dynamics_constraint_contact_ManifoldPoint { + constructor() { + this._localPos1X = 0; + this._localPos1Y = 0; + this._localPos1Z = 0; + this._localPos2X = 0; + this._localPos2Y = 0; + this._localPos2Z = 0; + this._relPos1X = 0; + this._relPos1Y = 0; + this._relPos1Z = 0; + this._relPos2X = 0; + this._relPos2Y = 0; + this._relPos2Z = 0; + this._pos1X = 0; + this._pos1Y = 0; + this._pos1Z = 0; + this._pos2X = 0; + this._pos2Y = 0; + this._pos2Z = 0; + this._depth = 0; + this._impulse = new oimo.dynamics.constraint.contact.ContactImpulse(); + this._warmStarted = false; + this._disabled = false; + this._id = -1; + } + getPosition1() { + let v = new oimo.common.Vec3(); + v.x = this._pos1X; + v.y = this._pos1Y; + v.z = this._pos1Z; + return v; + } + getPosition1To(position) { + position.x = this._pos1X; + position.y = this._pos1Y; + position.z = this._pos1Z; + } + getPosition2() { + let v = new oimo.common.Vec3(); + v.x = this._pos2X; + v.y = this._pos2Y; + v.z = this._pos2Z; + return v; + } + getPosition2To(position) { + position.x = this._pos2X; + position.y = this._pos2Y; + position.z = this._pos2Z; + } + getDepth() { + return this._depth; + } + isWarmStarted() { + return this._warmStarted; + } + getNormalImpulse() { + return this._impulse.impulseN; + } + getTangentImpulse() { + return this._impulse.impulseT; + } + getBinormalImpulse() { + return this._impulse.impulseB; + } + isEnabled() { + return !this._disabled; + } +} +oimo.dynamics.constraint.contact.ManifoldUpdater = class oimo_dynamics_constraint_contact_ManifoldUpdater { + constructor(manifold) { + this._manifold = manifold; + this.numOldPoints = 0; + this.oldPoints = new Array(oimo.common.Setting.maxManifoldPoints); + let _g = 0; + let _g1 = oimo.common.Setting.maxManifoldPoints; + while(_g < _g1) this.oldPoints[_g++] = new oimo.dynamics.constraint.contact.ManifoldPoint(); + } + removeOutdatedPoints() { + let index = this._manifold._numPoints; + while(--index >= 0) { + let p = this._manifold._points[index]; + let diffX; + let diffY; + let diffZ; + diffX = p._pos1X - p._pos2X; + diffY = p._pos1Y - p._pos2Y; + diffZ = p._pos1Z - p._pos2Z; + let dotN = this._manifold._normalX * diffX + this._manifold._normalY * diffY + this._manifold._normalZ * diffZ; + if(dotN > oimo.common.Setting.contactPersistenceThreshold) { + this.removeManifoldPoint(index); + continue; + } + diffX += this._manifold._normalX * -dotN; + diffY += this._manifold._normalY * -dotN; + diffZ += this._manifold._normalZ * -dotN; + if(diffX * diffX + diffY * diffY + diffZ * diffZ > oimo.common.Setting.contactPersistenceThreshold * oimo.common.Setting.contactPersistenceThreshold) { + this.removeManifoldPoint(index); + continue; + } + } + } + removeManifoldPoint(index) { + let lastIndex = --this._manifold._numPoints; + if(index != lastIndex) { + let tmp = this._manifold._points[index]; + this._manifold._points[index] = this._manifold._points[lastIndex]; + this._manifold._points[lastIndex] = tmp; + } + let _this = this._manifold._points[lastIndex]; + _this._localPos1X = 0; + _this._localPos1Y = 0; + _this._localPos1Z = 0; + _this._localPos2X = 0; + _this._localPos2Y = 0; + _this._localPos2Z = 0; + _this._relPos1X = 0; + _this._relPos1Y = 0; + _this._relPos1Z = 0; + _this._relPos2X = 0; + _this._relPos2Y = 0; + _this._relPos2Z = 0; + _this._pos1X = 0; + _this._pos1Y = 0; + _this._pos1Z = 0; + _this._pos2X = 0; + _this._pos2Y = 0; + _this._pos2Z = 0; + _this._depth = 0; + let _this1 = _this._impulse; + _this1.impulseN = 0; + _this1.impulseT = 0; + _this1.impulseB = 0; + _this1.impulseP = 0; + _this1.impulseLX = 0; + _this1.impulseLY = 0; + _this1.impulseLZ = 0; + _this._warmStarted = false; + _this._disabled = false; + _this._id = -1; + } + addManifoldPoint(point,tf1,tf2) { + let num = this._manifold._numPoints; + if(num == oimo.common.Setting.maxManifoldPoints) { + let targetIndex = this.computeTargetIndex(point,tf1,tf2); + let _this = this._manifold._points[targetIndex]; + let v = point.position1; + _this._pos1X = v.x; + _this._pos1Y = v.y; + _this._pos1Z = v.z; + let v1 = point.position2; + _this._pos2X = v1.x; + _this._pos2Y = v1.y; + _this._pos2Z = v1.z; + _this._relPos1X = _this._pos1X - tf1._positionX; + _this._relPos1Y = _this._pos1Y - tf1._positionY; + _this._relPos1Z = _this._pos1Z - tf1._positionZ; + _this._relPos2X = _this._pos2X - tf2._positionX; + _this._relPos2Y = _this._pos2Y - tf2._positionY; + _this._relPos2Z = _this._pos2Z - tf2._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * _this._relPos1X + tf1._rotation10 * _this._relPos1Y + tf1._rotation20 * _this._relPos1Z; + __tmp__Y = tf1._rotation01 * _this._relPos1X + tf1._rotation11 * _this._relPos1Y + tf1._rotation21 * _this._relPos1Z; + __tmp__Z = tf1._rotation02 * _this._relPos1X + tf1._rotation12 * _this._relPos1Y + tf1._rotation22 * _this._relPos1Z; + _this._localPos1X = __tmp__X; + _this._localPos1Y = __tmp__Y; + _this._localPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * _this._relPos2X + tf2._rotation10 * _this._relPos2Y + tf2._rotation20 * _this._relPos2Z; + __tmp__Y1 = tf2._rotation01 * _this._relPos2X + tf2._rotation11 * _this._relPos2Y + tf2._rotation21 * _this._relPos2Z; + __tmp__Z1 = tf2._rotation02 * _this._relPos2X + tf2._rotation12 * _this._relPos2Y + tf2._rotation22 * _this._relPos2Z; + _this._localPos2X = __tmp__X1; + _this._localPos2Y = __tmp__Y1; + _this._localPos2Z = __tmp__Z1; + _this._depth = point.depth; + let _this1 = _this._impulse; + _this1.impulseN = 0; + _this1.impulseT = 0; + _this1.impulseB = 0; + _this1.impulseP = 0; + _this1.impulseLX = 0; + _this1.impulseLY = 0; + _this1.impulseLZ = 0; + _this._id = point.id; + _this._warmStarted = false; + _this._disabled = false; + return; + } + let _this = this._manifold._points[num]; + let v = point.position1; + _this._pos1X = v.x; + _this._pos1Y = v.y; + _this._pos1Z = v.z; + let v1 = point.position2; + _this._pos2X = v1.x; + _this._pos2Y = v1.y; + _this._pos2Z = v1.z; + _this._relPos1X = _this._pos1X - tf1._positionX; + _this._relPos1Y = _this._pos1Y - tf1._positionY; + _this._relPos1Z = _this._pos1Z - tf1._positionZ; + _this._relPos2X = _this._pos2X - tf2._positionX; + _this._relPos2Y = _this._pos2Y - tf2._positionY; + _this._relPos2Z = _this._pos2Z - tf2._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * _this._relPos1X + tf1._rotation10 * _this._relPos1Y + tf1._rotation20 * _this._relPos1Z; + __tmp__Y = tf1._rotation01 * _this._relPos1X + tf1._rotation11 * _this._relPos1Y + tf1._rotation21 * _this._relPos1Z; + __tmp__Z = tf1._rotation02 * _this._relPos1X + tf1._rotation12 * _this._relPos1Y + tf1._rotation22 * _this._relPos1Z; + _this._localPos1X = __tmp__X; + _this._localPos1Y = __tmp__Y; + _this._localPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * _this._relPos2X + tf2._rotation10 * _this._relPos2Y + tf2._rotation20 * _this._relPos2Z; + __tmp__Y1 = tf2._rotation01 * _this._relPos2X + tf2._rotation11 * _this._relPos2Y + tf2._rotation21 * _this._relPos2Z; + __tmp__Z1 = tf2._rotation02 * _this._relPos2X + tf2._rotation12 * _this._relPos2Y + tf2._rotation22 * _this._relPos2Z; + _this._localPos2X = __tmp__X1; + _this._localPos2Y = __tmp__Y1; + _this._localPos2Z = __tmp__Z1; + _this._depth = point.depth; + let _this1 = _this._impulse; + _this1.impulseN = 0; + _this1.impulseT = 0; + _this1.impulseB = 0; + _this1.impulseP = 0; + _this1.impulseLX = 0; + _this1.impulseLY = 0; + _this1.impulseLZ = 0; + _this._id = point.id; + _this._warmStarted = false; + _this._disabled = false; + this._manifold._numPoints++; + } + computeTargetIndex(newPoint,tf1,tf2) { + let p1 = this._manifold._points[0]; + let p2 = this._manifold._points[1]; + let p3 = this._manifold._points[2]; + let p4 = this._manifold._points[3]; + let maxDepth = p1._depth; + let maxDepthIndex = 0; + if(p2._depth > maxDepth) { + maxDepth = p2._depth; + maxDepthIndex = 1; + } + if(p3._depth > maxDepth) { + maxDepth = p3._depth; + maxDepthIndex = 2; + } + if(p4._depth > maxDepth) { + + maxDepthIndex = 3; + } + let rp1X; + let rp1Y; + let rp1Z; + let v = newPoint.position1; + rp1X = v.x; + rp1Y = v.y; + rp1Z = v.z; + rp1X -= tf1._positionX; + rp1Y -= tf1._positionY; + rp1Z -= tf1._positionZ; + let p1X = p2._relPos1X; + let p1Y = p2._relPos1Y; + let p1Z = p2._relPos1Z; + let p2X = p3._relPos1X; + let p2Y = p3._relPos1Y; + let p2Z = p3._relPos1Z; + let p3X = p4._relPos1X; + let p3Y = p4._relPos1Y; + let p3Z = p4._relPos1Z; + let v12X; + let v12Y; + let v12Z; + let v34X; + let v34Y; + let v34Z; + let v13X; + let v13Y; + let v13Z; + let v24X; + let v24Y; + let v24Z; + let v14X; + let v14Y; + let v14Z; + let v23X; + let v23Y; + let v23Z; + v12X = p2X - p1X; + v12Y = p2Y - p1Y; + v12Z = p2Z - p1Z; + v34X = rp1X - p3X; + v34Y = rp1Y - p3Y; + v34Z = rp1Z - p3Z; + v13X = p3X - p1X; + v13Y = p3Y - p1Y; + v13Z = p3Z - p1Z; + v24X = rp1X - p2X; + v24Y = rp1Y - p2Y; + v24Z = rp1Z - p2Z; + v14X = rp1X - p1X; + v14Y = rp1Y - p1Y; + v14Z = rp1Z - p1Z; + v23X = p3X - p2X; + v23Y = p3Y - p2Y; + v23Z = p3Z - p2Z; + let cross1X; + let cross1Y; + let cross1Z; + let cross2X; + let cross2Y; + let cross2Z; + let cross3X; + let cross3Y; + let cross3Z; + cross1X = v12Y * v34Z - v12Z * v34Y; + cross1Y = v12Z * v34X - v12X * v34Z; + cross1Z = v12X * v34Y - v12Y * v34X; + cross2X = v13Y * v24Z - v13Z * v24Y; + cross2Y = v13Z * v24X - v13X * v24Z; + cross2Z = v13X * v24Y - v13Y * v24X; + cross3X = v14Y * v23Z - v14Z * v23Y; + cross3Y = v14Z * v23X - v14X * v23Z; + cross3Z = v14X * v23Y - v14Y * v23X; + let a1 = cross1X * cross1X + cross1Y * cross1Y + cross1Z * cross1Z; + let a2 = cross2X * cross2X + cross2Y * cross2Y + cross2Z * cross2Z; + let a3 = cross3X * cross3X + cross3Y * cross3Y + cross3Z * cross3Z; + let p1X1 = p1._relPos1X; + let p1Y1 = p1._relPos1Y; + let p1Z1 = p1._relPos1Z; + let p2X1 = p3._relPos1X; + let p2Y1 = p3._relPos1Y; + let p2Z1 = p3._relPos1Z; + let p3X1 = p4._relPos1X; + let p3Y1 = p4._relPos1Y; + let p3Z1 = p4._relPos1Z; + let v12X1; + let v12Y1; + let v12Z1; + let v34X1; + let v34Y1; + let v34Z1; + let v13X1; + let v13Y1; + let v13Z1; + let v24X1; + let v24Y1; + let v24Z1; + let v14X1; + let v14Y1; + let v14Z1; + let v23X1; + let v23Y1; + let v23Z1; + v12X1 = p2X1 - p1X1; + v12Y1 = p2Y1 - p1Y1; + v12Z1 = p2Z1 - p1Z1; + v34X1 = rp1X - p3X1; + v34Y1 = rp1Y - p3Y1; + v34Z1 = rp1Z - p3Z1; + v13X1 = p3X1 - p1X1; + v13Y1 = p3Y1 - p1Y1; + v13Z1 = p3Z1 - p1Z1; + v24X1 = rp1X - p2X1; + v24Y1 = rp1Y - p2Y1; + v24Z1 = rp1Z - p2Z1; + v14X1 = rp1X - p1X1; + v14Y1 = rp1Y - p1Y1; + v14Z1 = rp1Z - p1Z1; + v23X1 = p3X1 - p2X1; + v23Y1 = p3Y1 - p2Y1; + v23Z1 = p3Z1 - p2Z1; + let cross1X1; + let cross1Y1; + let cross1Z1; + let cross2X1; + let cross2Y1; + let cross2Z1; + let cross3X1; + let cross3Y1; + let cross3Z1; + cross1X1 = v12Y1 * v34Z1 - v12Z1 * v34Y1; + cross1Y1 = v12Z1 * v34X1 - v12X1 * v34Z1; + cross1Z1 = v12X1 * v34Y1 - v12Y1 * v34X1; + cross2X1 = v13Y1 * v24Z1 - v13Z1 * v24Y1; + cross2Y1 = v13Z1 * v24X1 - v13X1 * v24Z1; + cross2Z1 = v13X1 * v24Y1 - v13Y1 * v24X1; + cross3X1 = v14Y1 * v23Z1 - v14Z1 * v23Y1; + cross3Y1 = v14Z1 * v23X1 - v14X1 * v23Z1; + cross3Z1 = v14X1 * v23Y1 - v14Y1 * v23X1; + let a11 = cross1X1 * cross1X1 + cross1Y1 * cross1Y1 + cross1Z1 * cross1Z1; + let a21 = cross2X1 * cross2X1 + cross2Y1 * cross2Y1 + cross2Z1 * cross2Z1; + let a31 = cross3X1 * cross3X1 + cross3Y1 * cross3Y1 + cross3Z1 * cross3Z1; + let a22 = a11 > a21 ? a11 > a31 ? a11 : a31 : a21 > a31 ? a21 : a31; + let p1X2 = p1._relPos1X; + let p1Y2 = p1._relPos1Y; + let p1Z2 = p1._relPos1Z; + let p2X2 = p2._relPos1X; + let p2Y2 = p2._relPos1Y; + let p2Z2 = p2._relPos1Z; + let p3X2 = p4._relPos1X; + let p3Y2 = p4._relPos1Y; + let p3Z2 = p4._relPos1Z; + let v12X2; + let v12Y2; + let v12Z2; + let v34X2; + let v34Y2; + let v34Z2; + let v13X2; + let v13Y2; + let v13Z2; + let v24X2; + let v24Y2; + let v24Z2; + let v14X2; + let v14Y2; + let v14Z2; + let v23X2; + let v23Y2; + let v23Z2; + v12X2 = p2X2 - p1X2; + v12Y2 = p2Y2 - p1Y2; + v12Z2 = p2Z2 - p1Z2; + v34X2 = rp1X - p3X2; + v34Y2 = rp1Y - p3Y2; + v34Z2 = rp1Z - p3Z2; + v13X2 = p3X2 - p1X2; + v13Y2 = p3Y2 - p1Y2; + v13Z2 = p3Z2 - p1Z2; + v24X2 = rp1X - p2X2; + v24Y2 = rp1Y - p2Y2; + v24Z2 = rp1Z - p2Z2; + v14X2 = rp1X - p1X2; + v14Y2 = rp1Y - p1Y2; + v14Z2 = rp1Z - p1Z2; + v23X2 = p3X2 - p2X2; + v23Y2 = p3Y2 - p2Y2; + v23Z2 = p3Z2 - p2Z2; + let cross1X2; + let cross1Y2; + let cross1Z2; + let cross2X2; + let cross2Y2; + let cross2Z2; + let cross3X2; + let cross3Y2; + let cross3Z2; + cross1X2 = v12Y2 * v34Z2 - v12Z2 * v34Y2; + cross1Y2 = v12Z2 * v34X2 - v12X2 * v34Z2; + cross1Z2 = v12X2 * v34Y2 - v12Y2 * v34X2; + cross2X2 = v13Y2 * v24Z2 - v13Z2 * v24Y2; + cross2Y2 = v13Z2 * v24X2 - v13X2 * v24Z2; + cross2Z2 = v13X2 * v24Y2 - v13Y2 * v24X2; + cross3X2 = v14Y2 * v23Z2 - v14Z2 * v23Y2; + cross3Y2 = v14Z2 * v23X2 - v14X2 * v23Z2; + cross3Z2 = v14X2 * v23Y2 - v14Y2 * v23X2; + let a12 = cross1X2 * cross1X2 + cross1Y2 * cross1Y2 + cross1Z2 * cross1Z2; + let a23 = cross2X2 * cross2X2 + cross2Y2 * cross2Y2 + cross2Z2 * cross2Z2; + let a32 = cross3X2 * cross3X2 + cross3Y2 * cross3Y2 + cross3Z2 * cross3Z2; + let a33 = a12 > a23 ? a12 > a32 ? a12 : a32 : a23 > a32 ? a23 : a32; + let p1X3 = p1._relPos1X; + let p1Y3 = p1._relPos1Y; + let p1Z3 = p1._relPos1Z; + let p2X3 = p2._relPos1X; + let p2Y3 = p2._relPos1Y; + let p2Z3 = p2._relPos1Z; + let p3X3 = p3._relPos1X; + let p3Y3 = p3._relPos1Y; + let p3Z3 = p3._relPos1Z; + let v12X3; + let v12Y3; + let v12Z3; + let v34X3; + let v34Y3; + let v34Z3; + let v13X3; + let v13Y3; + let v13Z3; + let v24X3; + let v24Y3; + let v24Z3; + let v14X3; + let v14Y3; + let v14Z3; + let v23X3; + let v23Y3; + let v23Z3; + v12X3 = p2X3 - p1X3; + v12Y3 = p2Y3 - p1Y3; + v12Z3 = p2Z3 - p1Z3; + v34X3 = rp1X - p3X3; + v34Y3 = rp1Y - p3Y3; + v34Z3 = rp1Z - p3Z3; + v13X3 = p3X3 - p1X3; + v13Y3 = p3Y3 - p1Y3; + v13Z3 = p3Z3 - p1Z3; + v24X3 = rp1X - p2X3; + v24Y3 = rp1Y - p2Y3; + v24Z3 = rp1Z - p2Z3; + v14X3 = rp1X - p1X3; + v14Y3 = rp1Y - p1Y3; + v14Z3 = rp1Z - p1Z3; + v23X3 = p3X3 - p2X3; + v23Y3 = p3Y3 - p2Y3; + v23Z3 = p3Z3 - p2Z3; + let cross1X3; + let cross1Y3; + let cross1Z3; + let cross2X3; + let cross2Y3; + let cross2Z3; + let cross3X3; + let cross3Y3; + let cross3Z3; + cross1X3 = v12Y3 * v34Z3 - v12Z3 * v34Y3; + cross1Y3 = v12Z3 * v34X3 - v12X3 * v34Z3; + cross1Z3 = v12X3 * v34Y3 - v12Y3 * v34X3; + cross2X3 = v13Y3 * v24Z3 - v13Z3 * v24Y3; + cross2Y3 = v13Z3 * v24X3 - v13X3 * v24Z3; + cross2Z3 = v13X3 * v24Y3 - v13Y3 * v24X3; + cross3X3 = v14Y3 * v23Z3 - v14Z3 * v23Y3; + cross3Y3 = v14Z3 * v23X3 - v14X3 * v23Z3; + cross3Z3 = v14X3 * v23Y3 - v14Y3 * v23X3; + let a13 = cross1X3 * cross1X3 + cross1Y3 * cross1Y3 + cross1Z3 * cross1Z3; + let a24 = cross2X3 * cross2X3 + cross2Y3 * cross2Y3 + cross2Z3 * cross2Z3; + let a34 = cross3X3 * cross3X3 + cross3Y3 * cross3Y3 + cross3Z3 * cross3Z3; + let a4 = a13 > a24 ? a13 > a34 ? a13 : a34 : a24 > a34 ? a24 : a34; + let max = a1 > a2 ? a1 > a3 ? a1 : a3 : a2 > a3 ? a2 : a3; + let target = 0; + if(a22 > max && maxDepthIndex != 1 || maxDepthIndex == 0) { + max = a22; + target = 1; + } + if(a33 > max && maxDepthIndex != 2) { + max = a33; + target = 2; + } + if(a4 > max && maxDepthIndex != 3) { + + target = 3; + } + return target; + } + computeRelativePositions(tf1,tf2) { + let num = this._manifold._numPoints; + let _g = 0; + while(_g < num) { + let p = this._manifold._points[_g++]; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * p._localPos1X + tf1._rotation01 * p._localPos1Y + tf1._rotation02 * p._localPos1Z; + __tmp__Y = tf1._rotation10 * p._localPos1X + tf1._rotation11 * p._localPos1Y + tf1._rotation12 * p._localPos1Z; + __tmp__Z = tf1._rotation20 * p._localPos1X + tf1._rotation21 * p._localPos1Y + tf1._rotation22 * p._localPos1Z; + p._relPos1X = __tmp__X; + p._relPos1Y = __tmp__Y; + p._relPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * p._localPos2X + tf2._rotation01 * p._localPos2Y + tf2._rotation02 * p._localPos2Z; + __tmp__Y1 = tf2._rotation10 * p._localPos2X + tf2._rotation11 * p._localPos2Y + tf2._rotation12 * p._localPos2Z; + __tmp__Z1 = tf2._rotation20 * p._localPos2X + tf2._rotation21 * p._localPos2Y + tf2._rotation22 * p._localPos2Z; + p._relPos2X = __tmp__X1; + p._relPos2Y = __tmp__Y1; + p._relPos2Z = __tmp__Z1; + p._warmStarted = true; + } + } + findNearestContactPointIndex(target,tf1,tf2) { + let nearestSq = oimo.common.Setting.contactPersistenceThreshold * oimo.common.Setting.contactPersistenceThreshold; + let idx = -1; + let _g = 0; + let _g1 = this._manifold._numPoints; + while(_g < _g1) { + let i = _g++; + let mp = this._manifold._points[i]; + let rp1X; + let rp1Y; + let rp1Z; + let rp2X; + let rp2Y; + let rp2Z; + let v = target.position1; + rp1X = v.x; + rp1Y = v.y; + rp1Z = v.z; + let v1 = target.position2; + rp2X = v1.x; + rp2Y = v1.y; + rp2Z = v1.z; + rp1X -= tf1._positionX; + rp1Y -= tf1._positionY; + rp1Z -= tf1._positionZ; + rp2X -= tf2._positionX; + rp2Y -= tf2._positionY; + rp2Z -= tf2._positionZ; + let diff1X; + let diff1Y; + let diff1Z; + let diff2X; + let diff2Y; + let diff2Z; + diff1X = mp._relPos1X - rp1X; + diff1Y = mp._relPos1Y - rp1Y; + diff1Z = mp._relPos1Z - rp1Z; + diff2X = mp._relPos2X - rp2X; + diff2Y = mp._relPos2Y - rp2Y; + diff2Z = mp._relPos2Z - rp2Z; + let sq1 = diff1X * diff1X + diff1Y * diff1Y + diff1Z * diff1Z; + let sq2 = diff2X * diff2X + diff2Y * diff2Y + diff2Z * diff2Z; + let d = sq1 < sq2 ? sq1 : sq2; + if(d < nearestSq) { + nearestSq = d; + idx = i; + } + } + return idx; + } + totalUpdate(result,tf1,tf2) { + this.numOldPoints = this._manifold._numPoints; + let _g = 0; + let _g1 = this.numOldPoints; + while(_g < _g1) { + let i = _g++; + let _this = this.oldPoints[i]; + let cp = this._manifold._points[i]; + _this._localPos1X = cp._localPos1X; + _this._localPos1Y = cp._localPos1Y; + _this._localPos1Z = cp._localPos1Z; + _this._localPos2X = cp._localPos2X; + _this._localPos2Y = cp._localPos2Y; + _this._localPos2Z = cp._localPos2Z; + _this._relPos1X = cp._relPos1X; + _this._relPos1Y = cp._relPos1Y; + _this._relPos1Z = cp._relPos1Z; + _this._relPos2X = cp._relPos2X; + _this._relPos2Y = cp._relPos2Y; + _this._relPos2Z = cp._relPos2Z; + _this._pos1X = cp._pos1X; + _this._pos1Y = cp._pos1Y; + _this._pos1Z = cp._pos1Z; + _this._pos2X = cp._pos2X; + _this._pos2Y = cp._pos2Y; + _this._pos2Z = cp._pos2Z; + _this._depth = cp._depth; + _this._impulse.copyFrom(cp._impulse); + _this._id = cp._id; + _this._warmStarted = cp._warmStarted; + _this._disabled = false; + } + let num = result.numPoints; + this._manifold._numPoints = num; + let _g2 = 0; + while(_g2 < num) { + let i = _g2++; + let p = this._manifold._points[i]; + let ref = result.points[i]; + let v = ref.position1; + p._pos1X = v.x; + p._pos1Y = v.y; + p._pos1Z = v.z; + let v1 = ref.position2; + p._pos2X = v1.x; + p._pos2Y = v1.y; + p._pos2Z = v1.z; + p._relPos1X = p._pos1X - tf1._positionX; + p._relPos1Y = p._pos1Y - tf1._positionY; + p._relPos1Z = p._pos1Z - tf1._positionZ; + p._relPos2X = p._pos2X - tf2._positionX; + p._relPos2Y = p._pos2Y - tf2._positionY; + p._relPos2Z = p._pos2Z - tf2._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * p._relPos1X + tf1._rotation10 * p._relPos1Y + tf1._rotation20 * p._relPos1Z; + __tmp__Y = tf1._rotation01 * p._relPos1X + tf1._rotation11 * p._relPos1Y + tf1._rotation21 * p._relPos1Z; + __tmp__Z = tf1._rotation02 * p._relPos1X + tf1._rotation12 * p._relPos1Y + tf1._rotation22 * p._relPos1Z; + p._localPos1X = __tmp__X; + p._localPos1Y = __tmp__Y; + p._localPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * p._relPos2X + tf2._rotation10 * p._relPos2Y + tf2._rotation20 * p._relPos2Z; + __tmp__Y1 = tf2._rotation01 * p._relPos2X + tf2._rotation11 * p._relPos2Y + tf2._rotation21 * p._relPos2Z; + __tmp__Z1 = tf2._rotation02 * p._relPos2X + tf2._rotation12 * p._relPos2Y + tf2._rotation22 * p._relPos2Z; + p._localPos2X = __tmp__X1; + p._localPos2Y = __tmp__Y1; + p._localPos2Z = __tmp__Z1; + p._depth = ref.depth; + let _this = p._impulse; + _this.impulseN = 0; + _this.impulseT = 0; + _this.impulseB = 0; + _this.impulseP = 0; + _this.impulseLX = 0; + _this.impulseLY = 0; + _this.impulseLZ = 0; + p._id = ref.id; + p._warmStarted = false; + p._disabled = false; + let _g = 0; + let _g1 = this.numOldPoints; + while(_g < _g1) { + let ocp = this.oldPoints[_g++]; + if(p._id == ocp._id) { + p._impulse.copyFrom(ocp._impulse); + p._warmStarted = true; + break; + } + } + } + } + incrementalUpdate(result,tf1,tf2) { + this._manifold._updateDepthsAndPositions(tf1,tf2); + let _g = 0; + let _g1 = this._manifold._numPoints; + while(_g < _g1) this._manifold._points[_g++]._warmStarted = true; + let newPoint = result.points[0]; + let index = this.findNearestContactPointIndex(newPoint,tf1,tf2); + if(index == -1) { + this.addManifoldPoint(newPoint,tf1,tf2); + } else { + let cp = this._manifold._points[index]; + let v = newPoint.position1; + cp._pos1X = v.x; + cp._pos1Y = v.y; + cp._pos1Z = v.z; + let v1 = newPoint.position2; + cp._pos2X = v1.x; + cp._pos2Y = v1.y; + cp._pos2Z = v1.z; + cp._relPos1X = cp._pos1X - tf1._positionX; + cp._relPos1Y = cp._pos1Y - tf1._positionY; + cp._relPos1Z = cp._pos1Z - tf1._positionZ; + cp._relPos2X = cp._pos2X - tf2._positionX; + cp._relPos2Y = cp._pos2Y - tf2._positionY; + cp._relPos2Z = cp._pos2Z - tf2._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * cp._relPos1X + tf1._rotation10 * cp._relPos1Y + tf1._rotation20 * cp._relPos1Z; + __tmp__Y = tf1._rotation01 * cp._relPos1X + tf1._rotation11 * cp._relPos1Y + tf1._rotation21 * cp._relPos1Z; + __tmp__Z = tf1._rotation02 * cp._relPos1X + tf1._rotation12 * cp._relPos1Y + tf1._rotation22 * cp._relPos1Z; + cp._localPos1X = __tmp__X; + cp._localPos1Y = __tmp__Y; + cp._localPos1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * cp._relPos2X + tf2._rotation10 * cp._relPos2Y + tf2._rotation20 * cp._relPos2Z; + __tmp__Y1 = tf2._rotation01 * cp._relPos2X + tf2._rotation11 * cp._relPos2Y + tf2._rotation21 * cp._relPos2Z; + __tmp__Z1 = tf2._rotation02 * cp._relPos2X + tf2._rotation12 * cp._relPos2Y + tf2._rotation22 * cp._relPos2Z; + cp._localPos2X = __tmp__X1; + cp._localPos2Y = __tmp__Y1; + cp._localPos2Z = __tmp__Z1; + cp._depth = newPoint.depth; + } + this.removeOutdatedPoints(); + } +} +if(!oimo.dynamics.constraint.info) oimo.dynamics.constraint.info = {}; +oimo.dynamics.constraint.info.JacobianRow = class oimo_dynamics_constraint_info_JacobianRow { + constructor() { + this.lin1X = 0; + this.lin1Y = 0; + this.lin1Z = 0; + this.lin2X = 0; + this.lin2Y = 0; + this.lin2Z = 0; + this.ang1X = 0; + this.ang1Y = 0; + this.ang1Z = 0; + this.ang2X = 0; + this.ang2Y = 0; + this.ang2Z = 0; + this.flag = 0; + } + updateSparsity() { + this.flag = 0; + if(!(this.lin1X == 0 && this.lin1Y == 0 && this.lin1Z == 0) || !(this.lin2X == 0 && this.lin2Y == 0 && this.lin2Z == 0)) { + this.flag |= 1; + } + if(!(this.ang1X == 0 && this.ang1Y == 0 && this.ang1Z == 0) || !(this.ang2X == 0 && this.ang2Y == 0 && this.ang2Z == 0)) { + this.flag |= 2; + } + } +} +if(!oimo.dynamics.constraint.info.contact) oimo.dynamics.constraint.info.contact = {}; +oimo.dynamics.constraint.info.contact.ContactSolverInfo = class oimo_dynamics_constraint_info_contact_ContactSolverInfo { + constructor() { + this.b1 = null; + this.b2 = null; + this.numRows = 0; + this.rows = new Array(oimo.common.Setting.maxManifoldPoints); + let _g = 0; + let _g1 = this.rows.length; + while(_g < _g1) this.rows[_g++] = new oimo.dynamics.constraint.info.contact.ContactSolverInfoRow(); + } +} +oimo.dynamics.constraint.info.contact.ContactSolverInfoRow = class oimo_dynamics_constraint_info_contact_ContactSolverInfoRow { + constructor() { + this.jacobianN = new oimo.dynamics.constraint.info.JacobianRow(); + this.jacobianT = new oimo.dynamics.constraint.info.JacobianRow(); + this.jacobianB = new oimo.dynamics.constraint.info.JacobianRow(); + this.rhs = 0; + this.cfm = 0; + this.friction = 0; + this.impulse = null; + } +} +if(!oimo.dynamics.constraint.info.joint) oimo.dynamics.constraint.info.joint = {}; +oimo.dynamics.constraint.info.joint.JointSolverInfo = class oimo_dynamics_constraint_info_joint_JointSolverInfo { + constructor() { + this.b1 = null; + this.b2 = null; + this.numRows = 0; + this.rows = new Array(oimo.common.Setting.maxJacobianRows); + let _g = 0; + let _g1 = this.rows.length; + while(_g < _g1) this.rows[_g++] = new oimo.dynamics.constraint.info.joint.JointSolverInfoRow(); + } +} +oimo.dynamics.constraint.info.joint.JointSolverInfoRow = class oimo_dynamics_constraint_info_joint_JointSolverInfoRow { + constructor() { + this.jacobian = new oimo.dynamics.constraint.info.JacobianRow(); + this.rhs = 0; + this.cfm = 0; + this.minImpulse = 0; + this.maxImpulse = 0; + this.motorSpeed = 0; + this.motorMaxImpulse = 0; + this.impulse = null; + } +} +if(!oimo.dynamics.constraint.joint) oimo.dynamics.constraint.joint = {}; +oimo.dynamics.constraint.joint.BasisTracker = class oimo_dynamics_constraint_joint_BasisTracker { + constructor(joint) { + this.joint = joint; + this.xX = 0; + this.xY = 0; + this.xZ = 0; + this.yX = 0; + this.yY = 0; + this.yZ = 0; + this.zX = 0; + this.zY = 0; + this.zZ = 0; + } +} +oimo.dynamics.constraint.joint.Joint = class oimo_dynamics_constraint_joint_Joint { + constructor(config,type) { + this._link1 = new oimo.dynamics.constraint.joint.JointLink(this); + this._link2 = new oimo.dynamics.constraint.joint.JointLink(this); + this._positionCorrectionAlgorithm = oimo.common.Setting.defaultJointPositionCorrectionAlgorithm; + this._type = type; + this._world = null; + this._b1 = config.rigidBody1; + this._b2 = config.rigidBody2; + this._allowCollision = config.allowCollision; + this._breakForce = config.breakForce; + this._breakTorque = config.breakTorque; + switch(config.solverType) { + case 0: + this._solver = new oimo.dynamics.constraint.solver.pgs.PgsJointConstraintSolver(this); + break; + case 1: + this._solver = new oimo.dynamics.constraint.solver.direct.DirectJointConstraintSolver(this); + break; + } + let v = config.localAnchor1; + this._localAnchor1X = v.x; + this._localAnchor1Y = v.y; + this._localAnchor1Z = v.z; + let v1 = config.localAnchor2; + this._localAnchor2X = v1.x; + this._localAnchor2Y = v1.y; + this._localAnchor2Z = v1.z; + this._relativeAnchor1X = 0; + this._relativeAnchor1Y = 0; + this._relativeAnchor1Z = 0; + this._relativeAnchor2X = 0; + this._relativeAnchor2Y = 0; + this._relativeAnchor2Z = 0; + this._anchor1X = 0; + this._anchor1Y = 0; + this._anchor1Z = 0; + this._anchor2X = 0; + this._anchor2Y = 0; + this._anchor2Z = 0; + this._localBasisX1X = 0; + this._localBasisX1Y = 0; + this._localBasisX1Z = 0; + this._localBasisY1X = 0; + this._localBasisY1Y = 0; + this._localBasisY1Z = 0; + this._localBasisZ1X = 0; + this._localBasisZ1Y = 0; + this._localBasisZ1Z = 0; + this._localBasisX2X = 0; + this._localBasisX2Y = 0; + this._localBasisX2Z = 0; + this._localBasisY2X = 0; + this._localBasisY2Y = 0; + this._localBasisY2Z = 0; + this._localBasisZ2X = 0; + this._localBasisZ2Y = 0; + this._localBasisZ2Z = 0; + this._impulses = new Array(oimo.common.Setting.maxJacobianRows); + let _g = 0; + let _g1 = oimo.common.Setting.maxJacobianRows; + while(_g < _g1) this._impulses[_g++] = new oimo.dynamics.constraint.joint.JointImpulse(); + } + buildLocalBasesFromX() { + if(this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z == 0) { + this._localBasisX1X = 1; + this._localBasisX1Y = 0; + this._localBasisX1Z = 0; + } else { + let l = this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX1X *= l; + this._localBasisX1Y *= l; + this._localBasisX1Z *= l; + } + if(this._localBasisX2X * this._localBasisX2X + this._localBasisX2Y * this._localBasisX2Y + this._localBasisX2Z * this._localBasisX2Z == 0) { + this._localBasisX2X = 1; + this._localBasisX2Y = 0; + this._localBasisX2Z = 0; + } else { + let l = this._localBasisX2X * this._localBasisX2X + this._localBasisX2Y * this._localBasisX2Y + this._localBasisX2Z * this._localBasisX2Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX2X *= l; + this._localBasisX2Y *= l; + this._localBasisX2Z *= l; + } + let slerpQX; + let slerpQY; + let slerpQZ; + let slerpQW; + let slerpM00; + let slerpM01; + let slerpM02; + let slerpM10; + let slerpM11; + let slerpM12; + let slerpM20; + let slerpM21; + let slerpM22; + let d = this._localBasisX1X * this._localBasisX2X + this._localBasisX1Y * this._localBasisX2Y + this._localBasisX1Z * this._localBasisX2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = this._localBasisX1X; + let y1 = this._localBasisX1Y; + let z1 = this._localBasisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + slerpQX = vX; + slerpQY = vY; + slerpQZ = vZ; + slerpQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = this._localBasisX1Y * this._localBasisX2Z - this._localBasisX1Z * this._localBasisX2Y; + cY = this._localBasisX1Z * this._localBasisX2X - this._localBasisX1X * this._localBasisX2Z; + cZ = this._localBasisX1X * this._localBasisX2Y - this._localBasisX1Y * this._localBasisX2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + slerpQX = cX; + slerpQY = cY; + slerpQZ = cZ; + slerpQW = w; + } + let x = slerpQX; + let y = slerpQY; + let z = slerpQZ; + let w = slerpQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + slerpM00 = 1 - yy - zz; + slerpM01 = xy - wz; + slerpM02 = xz + wy; + slerpM10 = xy + wz; + slerpM11 = 1 - xx - zz; + slerpM12 = yz - wx; + slerpM20 = xz - wy; + slerpM21 = yz + wx; + slerpM22 = 1 - xx - yy; + let x1 = this._localBasisX1X; + let y1 = this._localBasisX1Y; + let z1 = this._localBasisX1Z; + let x21 = x1 * x1; + let y21 = y1 * y1; + let z21 = z1 * z1; + let d1; + if(x21 < y21) { + if(x21 < z21) { + d1 = 1 / Math.sqrt(y21 + z21); + this._localBasisY1X = 0; + this._localBasisY1Y = z1 * d1; + this._localBasisY1Z = -y1 * d1; + } else { + d1 = 1 / Math.sqrt(x21 + y21); + this._localBasisY1X = y1 * d1; + this._localBasisY1Y = -x1 * d1; + this._localBasisY1Z = 0; + } + } else if(y21 < z21) { + d1 = 1 / Math.sqrt(z21 + x21); + this._localBasisY1X = -z1 * d1; + this._localBasisY1Y = 0; + this._localBasisY1Z = x1 * d1; + } else { + d1 = 1 / Math.sqrt(x21 + y21); + this._localBasisY1X = y1 * d1; + this._localBasisY1Y = -x1 * d1; + this._localBasisY1Z = 0; + } + this._localBasisZ1X = this._localBasisX1Y * this._localBasisY1Z - this._localBasisX1Z * this._localBasisY1Y; + this._localBasisZ1Y = this._localBasisX1Z * this._localBasisY1X - this._localBasisX1X * this._localBasisY1Z; + this._localBasisZ1Z = this._localBasisX1X * this._localBasisY1Y - this._localBasisX1Y * this._localBasisY1X; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = slerpM00 * this._localBasisX1X + slerpM01 * this._localBasisX1Y + slerpM02 * this._localBasisX1Z; + __tmp__Y = slerpM10 * this._localBasisX1X + slerpM11 * this._localBasisX1Y + slerpM12 * this._localBasisX1Z; + __tmp__Z = slerpM20 * this._localBasisX1X + slerpM21 * this._localBasisX1Y + slerpM22 * this._localBasisX1Z; + this._localBasisX2X = __tmp__X; + this._localBasisX2Y = __tmp__Y; + this._localBasisX2Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = slerpM00 * this._localBasisY1X + slerpM01 * this._localBasisY1Y + slerpM02 * this._localBasisY1Z; + __tmp__Y1 = slerpM10 * this._localBasisY1X + slerpM11 * this._localBasisY1Y + slerpM12 * this._localBasisY1Z; + __tmp__Z1 = slerpM20 * this._localBasisY1X + slerpM21 * this._localBasisY1Y + slerpM22 * this._localBasisY1Z; + this._localBasisY2X = __tmp__X1; + this._localBasisY2Y = __tmp__Y1; + this._localBasisY2Z = __tmp__Z1; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = slerpM00 * this._localBasisZ1X + slerpM01 * this._localBasisZ1Y + slerpM02 * this._localBasisZ1Z; + __tmp__Y2 = slerpM10 * this._localBasisZ1X + slerpM11 * this._localBasisZ1Y + slerpM12 * this._localBasisZ1Z; + __tmp__Z2 = slerpM20 * this._localBasisZ1X + slerpM21 * this._localBasisZ1Y + slerpM22 * this._localBasisZ1Z; + this._localBasisZ2X = __tmp__X2; + this._localBasisZ2Y = __tmp__Y2; + this._localBasisZ2Z = __tmp__Z2; + } + buildLocalBasesFromXY() { + if(this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z == 0) { + this._localBasisX1X = 1; + this._localBasisX1Y = 0; + this._localBasisX1Z = 0; + } else { + let l = this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX1X *= l; + this._localBasisX1Y *= l; + this._localBasisX1Z *= l; + } + if(this._localBasisX2X * this._localBasisX2X + this._localBasisX2Y * this._localBasisX2Y + this._localBasisX2Z * this._localBasisX2Z == 0) { + this._localBasisX2X = 1; + this._localBasisX2Y = 0; + this._localBasisX2Z = 0; + } else { + let l = this._localBasisX2X * this._localBasisX2X + this._localBasisX2Y * this._localBasisX2Y + this._localBasisX2Z * this._localBasisX2Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX2X *= l; + this._localBasisX2Y *= l; + this._localBasisX2Z *= l; + } + this._localBasisZ1X = this._localBasisX1Y * this._localBasisY1Z - this._localBasisX1Z * this._localBasisY1Y; + this._localBasisZ1Y = this._localBasisX1Z * this._localBasisY1X - this._localBasisX1X * this._localBasisY1Z; + this._localBasisZ1Z = this._localBasisX1X * this._localBasisY1Y - this._localBasisX1Y * this._localBasisY1X; + this._localBasisZ2X = this._localBasisX2Y * this._localBasisY2Z - this._localBasisX2Z * this._localBasisY2Y; + this._localBasisZ2Y = this._localBasisX2Z * this._localBasisY2X - this._localBasisX2X * this._localBasisY2Z; + this._localBasisZ2Z = this._localBasisX2X * this._localBasisY2Y - this._localBasisX2Y * this._localBasisY2X; + if(this._localBasisZ1X * this._localBasisZ1X + this._localBasisZ1Y * this._localBasisZ1Y + this._localBasisZ1Z * this._localBasisZ1Z == 0) { + let x1 = this._localBasisX1X; + let y1 = this._localBasisX1Y; + let z1 = this._localBasisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + this._localBasisY1X = 0; + this._localBasisY1Y = z1 * d; + this._localBasisY1Z = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY1X = y1 * d; + this._localBasisY1Y = -x1 * d; + this._localBasisY1Z = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + this._localBasisY1X = -z1 * d; + this._localBasisY1Y = 0; + this._localBasisY1Z = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY1X = y1 * d; + this._localBasisY1Y = -x1 * d; + this._localBasisY1Z = 0; + } + this._localBasisZ1X = this._localBasisX1Y * this._localBasisY1Z - this._localBasisX1Z * this._localBasisY1Y; + this._localBasisZ1Y = this._localBasisX1Z * this._localBasisY1X - this._localBasisX1X * this._localBasisY1Z; + this._localBasisZ1Z = this._localBasisX1X * this._localBasisY1Y - this._localBasisX1Y * this._localBasisY1X; + } else { + let l = this._localBasisZ1X * this._localBasisZ1X + this._localBasisZ1Y * this._localBasisZ1Y + this._localBasisZ1Z * this._localBasisZ1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisZ1X *= l; + this._localBasisZ1Y *= l; + this._localBasisZ1Z *= l; + this._localBasisY1X = this._localBasisZ1Y * this._localBasisX1Z - this._localBasisZ1Z * this._localBasisX1Y; + this._localBasisY1Y = this._localBasisZ1Z * this._localBasisX1X - this._localBasisZ1X * this._localBasisX1Z; + this._localBasisY1Z = this._localBasisZ1X * this._localBasisX1Y - this._localBasisZ1Y * this._localBasisX1X; + } + if(this._localBasisZ2X * this._localBasisZ2X + this._localBasisZ2Y * this._localBasisZ2Y + this._localBasisZ2Z * this._localBasisZ2Z == 0) { + let x1 = this._localBasisX2X; + let y1 = this._localBasisX2Y; + let z1 = this._localBasisX2Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + this._localBasisY2X = 0; + this._localBasisY2Y = z1 * d; + this._localBasisY2Z = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY2X = y1 * d; + this._localBasisY2Y = -x1 * d; + this._localBasisY2Z = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + this._localBasisY2X = -z1 * d; + this._localBasisY2Y = 0; + this._localBasisY2Z = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY2X = y1 * d; + this._localBasisY2Y = -x1 * d; + this._localBasisY2Z = 0; + } + this._localBasisZ2X = this._localBasisX2Y * this._localBasisY2Z - this._localBasisX2Z * this._localBasisY2Y; + this._localBasisZ2Y = this._localBasisX2Z * this._localBasisY2X - this._localBasisX2X * this._localBasisY2Z; + this._localBasisZ2Z = this._localBasisX2X * this._localBasisY2Y - this._localBasisX2Y * this._localBasisY2X; + } else { + let l = this._localBasisZ2X * this._localBasisZ2X + this._localBasisZ2Y * this._localBasisZ2Y + this._localBasisZ2Z * this._localBasisZ2Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisZ2X *= l; + this._localBasisZ2Y *= l; + this._localBasisZ2Z *= l; + this._localBasisY2X = this._localBasisZ2Y * this._localBasisX2Z - this._localBasisZ2Z * this._localBasisX2Y; + this._localBasisY2Y = this._localBasisZ2Z * this._localBasisX2X - this._localBasisZ2X * this._localBasisX2Z; + this._localBasisY2Z = this._localBasisZ2X * this._localBasisX2Y - this._localBasisZ2Y * this._localBasisX2X; + } + } + buildLocalBasesFromX1Z2() { + if(this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z == 0) { + this._localBasisX1X = 1; + this._localBasisX1Y = 0; + this._localBasisX1Z = 0; + } else { + let l = this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX1X *= l; + this._localBasisX1Y *= l; + this._localBasisX1Z *= l; + } + if(this._localBasisZ2X * this._localBasisZ2X + this._localBasisZ2Y * this._localBasisZ2Y + this._localBasisZ2Z * this._localBasisZ2Z == 0) { + this._localBasisZ2X = 0; + this._localBasisZ2Y = 0; + this._localBasisZ2Z = 1; + } else { + let l = this._localBasisZ2X * this._localBasisZ2X + this._localBasisZ2Y * this._localBasisZ2Y + this._localBasisZ2Z * this._localBasisZ2Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisZ2X *= l; + this._localBasisZ2Y *= l; + this._localBasisZ2Z *= l; + } + let tf1 = this._b1._transform; + let tf2 = this._b2._transform; + let worldX1X; + let worldX1Y; + let worldX1Z; + let worldZ1X; + let worldZ1Y; + let worldZ1Z; + let worldYX; + let worldYY; + let worldYZ; + let worldX2X; + let worldX2Y; + let worldX2Z; + let worldZ2X; + let worldZ2Y; + let worldZ2Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * this._localBasisX1X + tf1._rotation01 * this._localBasisX1Y + tf1._rotation02 * this._localBasisX1Z; + __tmp__Y = tf1._rotation10 * this._localBasisX1X + tf1._rotation11 * this._localBasisX1Y + tf1._rotation12 * this._localBasisX1Z; + __tmp__Z = tf1._rotation20 * this._localBasisX1X + tf1._rotation21 * this._localBasisX1Y + tf1._rotation22 * this._localBasisX1Z; + worldX1X = __tmp__X; + worldX1Y = __tmp__Y; + worldX1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * this._localBasisZ2X + tf2._rotation01 * this._localBasisZ2Y + tf2._rotation02 * this._localBasisZ2Z; + __tmp__Y1 = tf2._rotation10 * this._localBasisZ2X + tf2._rotation11 * this._localBasisZ2Y + tf2._rotation12 * this._localBasisZ2Z; + __tmp__Z1 = tf2._rotation20 * this._localBasisZ2X + tf2._rotation21 * this._localBasisZ2Y + tf2._rotation22 * this._localBasisZ2Z; + worldZ2X = __tmp__X1; + worldZ2Y = __tmp__Y1; + worldZ2Z = __tmp__Z1; + worldYX = worldZ2Y * worldX1Z - worldZ2Z * worldX1Y; + worldYY = worldZ2Z * worldX1X - worldZ2X * worldX1Z; + worldYZ = worldZ2X * worldX1Y - worldZ2Y * worldX1X; + if(worldYX * worldYX + worldYY * worldYY + worldYZ * worldYZ == 0) { + let x1 = worldX1X; + let y1 = worldX1Y; + let z1 = worldX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + worldYX = 0; + worldYY = z1 * d; + worldYZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + worldYX = y1 * d; + worldYY = -x1 * d; + worldYZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + worldYX = -z1 * d; + worldYY = 0; + worldYZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + worldYX = y1 * d; + worldYY = -x1 * d; + worldYZ = 0; + } + } + worldZ1X = worldX1Y * worldYZ - worldX1Z * worldYY; + worldZ1Y = worldX1Z * worldYX - worldX1X * worldYZ; + worldZ1Z = worldX1X * worldYY - worldX1Y * worldYX; + worldX2X = worldYY * worldZ2Z - worldYZ * worldZ2Y; + worldX2Y = worldYZ * worldZ2X - worldYX * worldZ2Z; + worldX2Z = worldYX * worldZ2Y - worldYY * worldZ2X; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = tf1._rotation00 * worldX1X + tf1._rotation10 * worldX1Y + tf1._rotation20 * worldX1Z; + __tmp__Y2 = tf1._rotation01 * worldX1X + tf1._rotation11 * worldX1Y + tf1._rotation21 * worldX1Z; + __tmp__Z2 = tf1._rotation02 * worldX1X + tf1._rotation12 * worldX1Y + tf1._rotation22 * worldX1Z; + this._localBasisX1X = __tmp__X2; + this._localBasisX1Y = __tmp__Y2; + this._localBasisX1Z = __tmp__Z2; + let __tmp__X3; + let __tmp__Y3; + let __tmp__Z3; + __tmp__X3 = tf1._rotation00 * worldYX + tf1._rotation10 * worldYY + tf1._rotation20 * worldYZ; + __tmp__Y3 = tf1._rotation01 * worldYX + tf1._rotation11 * worldYY + tf1._rotation21 * worldYZ; + __tmp__Z3 = tf1._rotation02 * worldYX + tf1._rotation12 * worldYY + tf1._rotation22 * worldYZ; + this._localBasisY1X = __tmp__X3; + this._localBasisY1Y = __tmp__Y3; + this._localBasisY1Z = __tmp__Z3; + let __tmp__X4; + let __tmp__Y4; + let __tmp__Z4; + __tmp__X4 = tf1._rotation00 * worldZ1X + tf1._rotation10 * worldZ1Y + tf1._rotation20 * worldZ1Z; + __tmp__Y4 = tf1._rotation01 * worldZ1X + tf1._rotation11 * worldZ1Y + tf1._rotation21 * worldZ1Z; + __tmp__Z4 = tf1._rotation02 * worldZ1X + tf1._rotation12 * worldZ1Y + tf1._rotation22 * worldZ1Z; + this._localBasisZ1X = __tmp__X4; + this._localBasisZ1Y = __tmp__Y4; + this._localBasisZ1Z = __tmp__Z4; + let __tmp__X5; + let __tmp__Y5; + let __tmp__Z5; + __tmp__X5 = tf2._rotation00 * worldX2X + tf2._rotation10 * worldX2Y + tf2._rotation20 * worldX2Z; + __tmp__Y5 = tf2._rotation01 * worldX2X + tf2._rotation11 * worldX2Y + tf2._rotation21 * worldX2Z; + __tmp__Z5 = tf2._rotation02 * worldX2X + tf2._rotation12 * worldX2Y + tf2._rotation22 * worldX2Z; + this._localBasisX2X = __tmp__X5; + this._localBasisX2Y = __tmp__Y5; + this._localBasisX2Z = __tmp__Z5; + let __tmp__X6; + let __tmp__Y6; + let __tmp__Z6; + __tmp__X6 = tf2._rotation00 * worldYX + tf2._rotation10 * worldYY + tf2._rotation20 * worldYZ; + __tmp__Y6 = tf2._rotation01 * worldYX + tf2._rotation11 * worldYY + tf2._rotation21 * worldYZ; + __tmp__Z6 = tf2._rotation02 * worldYX + tf2._rotation12 * worldYY + tf2._rotation22 * worldYZ; + this._localBasisY2X = __tmp__X6; + this._localBasisY2Y = __tmp__Y6; + this._localBasisY2Z = __tmp__Z6; + let __tmp__X7; + let __tmp__Y7; + let __tmp__Z7; + __tmp__X7 = tf2._rotation00 * worldZ2X + tf2._rotation10 * worldZ2Y + tf2._rotation20 * worldZ2Z; + __tmp__Y7 = tf2._rotation01 * worldZ2X + tf2._rotation11 * worldZ2Y + tf2._rotation21 * worldZ2Z; + __tmp__Z7 = tf2._rotation02 * worldZ2X + tf2._rotation12 * worldZ2Y + tf2._rotation22 * worldZ2Z; + this._localBasisZ2X = __tmp__X7; + this._localBasisZ2Y = __tmp__Y7; + this._localBasisZ2Z = __tmp__Z7; + } + buildLocalBasesFromXY1X2() { + if(this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z == 0) { + this._localBasisX1X = 1; + this._localBasisX1Y = 0; + this._localBasisX1Z = 0; + } else { + let l = this._localBasisX1X * this._localBasisX1X + this._localBasisX1Y * this._localBasisX1Y + this._localBasisX1Z * this._localBasisX1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisX1X *= l; + this._localBasisX1Y *= l; + this._localBasisX1Z *= l; + } + this._localBasisZ1X = this._localBasisX1Y * this._localBasisY1Z - this._localBasisX1Z * this._localBasisY1Y; + this._localBasisZ1Y = this._localBasisX1Z * this._localBasisY1X - this._localBasisX1X * this._localBasisY1Z; + this._localBasisZ1Z = this._localBasisX1X * this._localBasisY1Y - this._localBasisX1Y * this._localBasisY1X; + if(this._localBasisZ1X * this._localBasisZ1X + this._localBasisZ1Y * this._localBasisZ1Y + this._localBasisZ1Z * this._localBasisZ1Z == 0) { + let x1 = this._localBasisX1X; + let y1 = this._localBasisX1Y; + let z1 = this._localBasisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + this._localBasisY1X = 0; + this._localBasisY1Y = z1 * d; + this._localBasisY1Z = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY1X = y1 * d; + this._localBasisY1Y = -x1 * d; + this._localBasisY1Z = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + this._localBasisY1X = -z1 * d; + this._localBasisY1Y = 0; + this._localBasisY1Z = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + this._localBasisY1X = y1 * d; + this._localBasisY1Y = -x1 * d; + this._localBasisY1Z = 0; + } + this._localBasisZ1X = this._localBasisX1Y * this._localBasisY1Z - this._localBasisX1Z * this._localBasisY1Y; + this._localBasisZ1Y = this._localBasisX1Z * this._localBasisY1X - this._localBasisX1X * this._localBasisY1Z; + this._localBasisZ1Z = this._localBasisX1X * this._localBasisY1Y - this._localBasisX1Y * this._localBasisY1X; + } else { + let l = this._localBasisZ1X * this._localBasisZ1X + this._localBasisZ1Y * this._localBasisZ1Y + this._localBasisZ1Z * this._localBasisZ1Z; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._localBasisZ1X *= l; + this._localBasisZ1Y *= l; + this._localBasisZ1Z *= l; + this._localBasisY1X = this._localBasisZ1Y * this._localBasisX1Z - this._localBasisZ1Z * this._localBasisX1Y; + this._localBasisY1Y = this._localBasisZ1Z * this._localBasisX1X - this._localBasisZ1X * this._localBasisX1Z; + this._localBasisY1Z = this._localBasisZ1X * this._localBasisX1Y - this._localBasisZ1Y * this._localBasisX1X; + } + let slerpQX; + let slerpQY; + let slerpQZ; + let slerpQW; + let slerpM00; + let slerpM01; + let slerpM02; + let slerpM10; + let slerpM11; + let slerpM12; + let slerpM20; + let slerpM21; + let slerpM22; + let d = this._localBasisX1X * this._localBasisX2X + this._localBasisX1Y * this._localBasisX2Y + this._localBasisX1Z * this._localBasisX2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = this._localBasisX1X; + let y1 = this._localBasisX1Y; + let z1 = this._localBasisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + slerpQX = vX; + slerpQY = vY; + slerpQZ = vZ; + slerpQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = this._localBasisX1Y * this._localBasisX2Z - this._localBasisX1Z * this._localBasisX2Y; + cY = this._localBasisX1Z * this._localBasisX2X - this._localBasisX1X * this._localBasisX2Z; + cZ = this._localBasisX1X * this._localBasisX2Y - this._localBasisX1Y * this._localBasisX2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + slerpQX = cX; + slerpQY = cY; + slerpQZ = cZ; + slerpQW = w; + } + let x = slerpQX; + let y = slerpQY; + let z = slerpQZ; + let w = slerpQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + slerpM00 = 1 - yy - zz; + slerpM01 = xy - wz; + slerpM02 = xz + wy; + slerpM10 = xy + wz; + slerpM11 = 1 - xx - zz; + slerpM12 = yz - wx; + slerpM20 = xz - wy; + slerpM21 = yz + wx; + slerpM22 = 1 - xx - yy; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = slerpM00 * this._localBasisX1X + slerpM01 * this._localBasisX1Y + slerpM02 * this._localBasisX1Z; + __tmp__Y = slerpM10 * this._localBasisX1X + slerpM11 * this._localBasisX1Y + slerpM12 * this._localBasisX1Z; + __tmp__Z = slerpM20 * this._localBasisX1X + slerpM21 * this._localBasisX1Y + slerpM22 * this._localBasisX1Z; + this._localBasisX2X = __tmp__X; + this._localBasisX2Y = __tmp__Y; + this._localBasisX2Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = slerpM00 * this._localBasisY1X + slerpM01 * this._localBasisY1Y + slerpM02 * this._localBasisY1Z; + __tmp__Y1 = slerpM10 * this._localBasisY1X + slerpM11 * this._localBasisY1Y + slerpM12 * this._localBasisY1Z; + __tmp__Z1 = slerpM20 * this._localBasisY1X + slerpM21 * this._localBasisY1Y + slerpM22 * this._localBasisY1Z; + this._localBasisY2X = __tmp__X1; + this._localBasisY2Y = __tmp__Y1; + this._localBasisY2Z = __tmp__Z1; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = slerpM00 * this._localBasisZ1X + slerpM01 * this._localBasisZ1Y + slerpM02 * this._localBasisZ1Z; + __tmp__Y2 = slerpM10 * this._localBasisZ1X + slerpM11 * this._localBasisZ1Y + slerpM12 * this._localBasisZ1Z; + __tmp__Z2 = slerpM20 * this._localBasisZ1X + slerpM21 * this._localBasisZ1Y + slerpM22 * this._localBasisZ1Z; + this._localBasisZ2X = __tmp__X2; + this._localBasisZ2Y = __tmp__Y2; + this._localBasisZ2Z = __tmp__Z2; + } + setSolverInfoRowLinear(row,diff,lm,mass,sd,timeStep,isPositionPart) { + let cfmFactor; + let erp; + let slop = oimo.common.Setting.linearSlop; + if(isPositionPart) { + cfmFactor = 0; + erp = 1; + } else { + if(sd.frequency > 0) { + slop = 0; + let omega = 6.28318530717958 * sd.frequency; + let zeta = sd.dampingRatio; + if(zeta < oimo.common.Setting.minSpringDamperDampingRatio) { + zeta = oimo.common.Setting.minSpringDamperDampingRatio; + } + let h = timeStep.dt; + let c = 2 * zeta * omega; + let k = omega * omega; + if(sd.useSymplecticEuler) { + cfmFactor = 1 / (h * c); + erp = k / c; + } else { + cfmFactor = 1 / (h * (h * k + c)); + erp = k / (h * k + c); + } + } else { + cfmFactor = 0; + erp = this.getErp(timeStep,false); + } + if(lm.motorForce > 0) { + row.motorSpeed = lm.motorSpeed; + row.motorMaxImpulse = lm.motorForce * timeStep.dt; + } else { + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + } + } + let lower = lm.lowerLimit; + let upper = lm.upperLimit; + let minImp; + let maxImp; + let error; + if(lower > upper) { + minImp = 0; + maxImp = 0; + error = 0; + } else if(lower == upper) { + minImp = -1e65536; + maxImp = 1e65536; + error = diff - lower; + } else if(diff < lower) { + minImp = -1e65536; + maxImp = 0; + error = diff - lower + slop; + if(error > 0) { + error = 0; + } + } else if(diff > upper) { + minImp = 0; + maxImp = 1e65536; + error = diff - upper - slop; + if(error < 0) { + error = 0; + } + } else { + minImp = 0; + maxImp = 0; + error = 0; + } + row.minImpulse = minImp; + row.maxImpulse = maxImp; + row.cfm = cfmFactor * (mass == 0 ? 0 : 1 / mass); + row.rhs = error * erp; + } + setSolverInfoRowAngular(row,diff,lm,mass,sd,timeStep,isPositionPart) { + let cfmFactor; + let erp; + let slop = oimo.common.Setting.angularSlop; + if(isPositionPart) { + cfmFactor = 0; + erp = 1; + } else { + if(sd.frequency > 0) { + slop = 0; + let omega = 6.28318530717958 * sd.frequency; + let zeta = sd.dampingRatio; + if(zeta < oimo.common.Setting.minSpringDamperDampingRatio) { + zeta = oimo.common.Setting.minSpringDamperDampingRatio; + } + let h = timeStep.dt; + let c = 2 * zeta * omega; + let k = omega * omega; + if(sd.useSymplecticEuler) { + cfmFactor = 1 / (h * c); + erp = k / c; + } else { + cfmFactor = 1 / (h * (h * k + c)); + erp = k / (h * k + c); + } + } else { + cfmFactor = 0; + erp = this.getErp(timeStep,false); + } + if(lm.motorTorque > 0) { + row.motorSpeed = lm.motorSpeed; + row.motorMaxImpulse = lm.motorTorque * timeStep.dt; + } else { + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + } + } + let lower = lm.lowerLimit; + let upper = lm.upperLimit; + let mid = (lower + upper) * 0.5; + diff -= mid; + diff = ((diff + 3.14159265358979) % 6.28318530717958 + 6.28318530717958) % 6.28318530717958 - 3.14159265358979; + diff += mid; + let minImp; + let maxImp; + let error; + if(lower > upper) { + minImp = 0; + maxImp = 0; + error = 0; + } else if(lower == upper) { + minImp = -1e65536; + maxImp = 1e65536; + error = diff - lower; + } else if(diff < lower) { + minImp = -1e65536; + maxImp = 0; + error = diff - lower + slop; + if(error > 0) { + error = 0; + } + } else if(diff > upper) { + minImp = 0; + maxImp = 1e65536; + error = diff - upper - slop; + if(error < 0) { + error = 0; + } + } else { + minImp = 0; + maxImp = 0; + error = 0; + } + row.minImpulse = minImp; + row.maxImpulse = maxImp; + row.cfm = cfmFactor * (mass == 0 ? 0 : 1 / mass); + row.rhs = error * erp; + } + getErp(timeStep,isPositionPart) { + if(isPositionPart) { + return 1; + } else if(this._positionCorrectionAlgorithm == oimo.dynamics.constraint.PositionCorrectionAlgorithm.BAUMGARTE) { + return timeStep.invDt * oimo.common.Setting.velocityBaumgarte; + } else { + return 0; + } + } + computeEffectiveInertiaMoment(axisX,axisY,axisZ) { + let ia1X; + let ia1Y; + let ia1Z; + let ia2X; + let ia2Y; + let ia2Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._b1._invInertia00 * axisX + this._b1._invInertia01 * axisY + this._b1._invInertia02 * axisZ; + __tmp__Y = this._b1._invInertia10 * axisX + this._b1._invInertia11 * axisY + this._b1._invInertia12 * axisZ; + __tmp__Z = this._b1._invInertia20 * axisX + this._b1._invInertia21 * axisY + this._b1._invInertia22 * axisZ; + ia1X = __tmp__X; + ia1Y = __tmp__Y; + ia1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = this._b2._invInertia00 * axisX + this._b2._invInertia01 * axisY + this._b2._invInertia02 * axisZ; + __tmp__Y1 = this._b2._invInertia10 * axisX + this._b2._invInertia11 * axisY + this._b2._invInertia12 * axisZ; + __tmp__Z1 = this._b2._invInertia20 * axisX + this._b2._invInertia21 * axisY + this._b2._invInertia22 * axisZ; + ia2X = __tmp__X1; + ia2Y = __tmp__Y1; + ia2Z = __tmp__Z1; + let invI1 = ia1X * axisX + ia1Y * axisY + ia1Z * axisZ; + let invI2 = ia2X * axisX + ia2Y * axisY + ia2Z * axisZ; + if(invI1 > 0) { + let dot = axisX * this._relativeAnchor1X + axisY * this._relativeAnchor1Y + axisZ * this._relativeAnchor1Z; + let projsq = this._relativeAnchor1X * this._relativeAnchor1X + this._relativeAnchor1Y * this._relativeAnchor1Y + this._relativeAnchor1Z * this._relativeAnchor1Z - dot * dot; + if(projsq > 0) { + if(this._b1._invMass > 0) { + invI1 = 1 / (1 / invI1 + this._b1._mass * projsq); + } else { + invI1 = 0; + } + } + } + if(invI2 > 0) { + let dot = axisX * this._relativeAnchor2X + axisY * this._relativeAnchor2Y + axisZ * this._relativeAnchor2Z; + let projsq = this._relativeAnchor2X * this._relativeAnchor2X + this._relativeAnchor2Y * this._relativeAnchor2Y + this._relativeAnchor2Z * this._relativeAnchor2Z - dot * dot; + if(projsq > 0) { + if(this._b2._invMass > 0) { + invI2 = 1 / (1 / invI2 + this._b2._mass * projsq); + } else { + invI2 = 0; + } + } + } + if(invI1 + invI2 == 0) { + return 0; + } else { + return 1 / (invI1 + invI2); + } + } + computeEffectiveInertiaMoment2(axis1X,axis1Y,axis1Z,axis2X,axis2Y,axis2Z) { + let ia1X; + let ia1Y; + let ia1Z; + let ia2X; + let ia2Y; + let ia2Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._b1._invInertia00 * axis1X + this._b1._invInertia01 * axis1Y + this._b1._invInertia02 * axis1Z; + __tmp__Y = this._b1._invInertia10 * axis1X + this._b1._invInertia11 * axis1Y + this._b1._invInertia12 * axis1Z; + __tmp__Z = this._b1._invInertia20 * axis1X + this._b1._invInertia21 * axis1Y + this._b1._invInertia22 * axis1Z; + ia1X = __tmp__X; + ia1Y = __tmp__Y; + ia1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = this._b2._invInertia00 * axis2X + this._b2._invInertia01 * axis2Y + this._b2._invInertia02 * axis2Z; + __tmp__Y1 = this._b2._invInertia10 * axis2X + this._b2._invInertia11 * axis2Y + this._b2._invInertia12 * axis2Z; + __tmp__Z1 = this._b2._invInertia20 * axis2X + this._b2._invInertia21 * axis2Y + this._b2._invInertia22 * axis2Z; + ia2X = __tmp__X1; + ia2Y = __tmp__Y1; + ia2Z = __tmp__Z1; + let invI1 = ia1X * axis1X + ia1Y * axis1Y + ia1Z * axis1Z; + let invI2 = ia2X * axis2X + ia2Y * axis2Y + ia2Z * axis2Z; + if(invI1 > 0) { + let rsq = this._relativeAnchor1X * this._relativeAnchor1X + this._relativeAnchor1Y * this._relativeAnchor1Y + this._relativeAnchor1Z * this._relativeAnchor1Z; + let dot = axis1X * this._relativeAnchor1X + axis1Y * this._relativeAnchor1Y + axis1Z * this._relativeAnchor1Z; + let projsq = rsq * rsq - dot * dot; + if(projsq > 0) { + if(this._b1._invMass > 0) { + invI1 = 1 / (1 / invI1 + this._b1._mass * projsq); + } else { + invI1 = 0; + } + } + } + if(invI2 > 0) { + let rsq = this._relativeAnchor2X * this._relativeAnchor2X + this._relativeAnchor2Y * this._relativeAnchor2Y + this._relativeAnchor2Z * this._relativeAnchor2Z; + let dot = axis2X * this._relativeAnchor2X + axis2Y * this._relativeAnchor2Y + axis2Z * this._relativeAnchor2Z; + let projsq = rsq * rsq - dot * dot; + if(projsq > 0) { + if(this._b2._invMass > 0) { + invI2 = 1 / (1 / invI2 + this._b2._mass * projsq); + } else { + invI2 = 0; + } + } + } + if(invI1 + invI2 == 0) { + return 0; + } else { + return 1 / (invI1 + invI2); + } + } + _syncAnchors() { + let tf1 = this._b1._transform; + let tf2 = this._b2._transform; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * this._localAnchor1X + tf1._rotation01 * this._localAnchor1Y + tf1._rotation02 * this._localAnchor1Z; + __tmp__Y = tf1._rotation10 * this._localAnchor1X + tf1._rotation11 * this._localAnchor1Y + tf1._rotation12 * this._localAnchor1Z; + __tmp__Z = tf1._rotation20 * this._localAnchor1X + tf1._rotation21 * this._localAnchor1Y + tf1._rotation22 * this._localAnchor1Z; + this._relativeAnchor1X = __tmp__X; + this._relativeAnchor1Y = __tmp__Y; + this._relativeAnchor1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * this._localAnchor2X + tf2._rotation01 * this._localAnchor2Y + tf2._rotation02 * this._localAnchor2Z; + __tmp__Y1 = tf2._rotation10 * this._localAnchor2X + tf2._rotation11 * this._localAnchor2Y + tf2._rotation12 * this._localAnchor2Z; + __tmp__Z1 = tf2._rotation20 * this._localAnchor2X + tf2._rotation21 * this._localAnchor2Y + tf2._rotation22 * this._localAnchor2Z; + this._relativeAnchor2X = __tmp__X1; + this._relativeAnchor2Y = __tmp__Y1; + this._relativeAnchor2Z = __tmp__Z1; + this._anchor1X = this._relativeAnchor1X + tf1._positionX; + this._anchor1Y = this._relativeAnchor1Y + tf1._positionY; + this._anchor1Z = this._relativeAnchor1Z + tf1._positionZ; + this._anchor2X = this._relativeAnchor2X + tf2._positionX; + this._anchor2Y = this._relativeAnchor2Y + tf2._positionY; + this._anchor2Z = this._relativeAnchor2Z + tf2._positionZ; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = tf1._rotation00 * this._localBasisX1X + tf1._rotation01 * this._localBasisX1Y + tf1._rotation02 * this._localBasisX1Z; + __tmp__Y2 = tf1._rotation10 * this._localBasisX1X + tf1._rotation11 * this._localBasisX1Y + tf1._rotation12 * this._localBasisX1Z; + __tmp__Z2 = tf1._rotation20 * this._localBasisX1X + tf1._rotation21 * this._localBasisX1Y + tf1._rotation22 * this._localBasisX1Z; + this._basisX1X = __tmp__X2; + this._basisX1Y = __tmp__Y2; + this._basisX1Z = __tmp__Z2; + let __tmp__X3; + let __tmp__Y3; + let __tmp__Z3; + __tmp__X3 = tf1._rotation00 * this._localBasisY1X + tf1._rotation01 * this._localBasisY1Y + tf1._rotation02 * this._localBasisY1Z; + __tmp__Y3 = tf1._rotation10 * this._localBasisY1X + tf1._rotation11 * this._localBasisY1Y + tf1._rotation12 * this._localBasisY1Z; + __tmp__Z3 = tf1._rotation20 * this._localBasisY1X + tf1._rotation21 * this._localBasisY1Y + tf1._rotation22 * this._localBasisY1Z; + this._basisY1X = __tmp__X3; + this._basisY1Y = __tmp__Y3; + this._basisY1Z = __tmp__Z3; + let __tmp__X4; + let __tmp__Y4; + let __tmp__Z4; + __tmp__X4 = tf1._rotation00 * this._localBasisZ1X + tf1._rotation01 * this._localBasisZ1Y + tf1._rotation02 * this._localBasisZ1Z; + __tmp__Y4 = tf1._rotation10 * this._localBasisZ1X + tf1._rotation11 * this._localBasisZ1Y + tf1._rotation12 * this._localBasisZ1Z; + __tmp__Z4 = tf1._rotation20 * this._localBasisZ1X + tf1._rotation21 * this._localBasisZ1Y + tf1._rotation22 * this._localBasisZ1Z; + this._basisZ1X = __tmp__X4; + this._basisZ1Y = __tmp__Y4; + this._basisZ1Z = __tmp__Z4; + let __tmp__X5; + let __tmp__Y5; + let __tmp__Z5; + __tmp__X5 = tf2._rotation00 * this._localBasisX2X + tf2._rotation01 * this._localBasisX2Y + tf2._rotation02 * this._localBasisX2Z; + __tmp__Y5 = tf2._rotation10 * this._localBasisX2X + tf2._rotation11 * this._localBasisX2Y + tf2._rotation12 * this._localBasisX2Z; + __tmp__Z5 = tf2._rotation20 * this._localBasisX2X + tf2._rotation21 * this._localBasisX2Y + tf2._rotation22 * this._localBasisX2Z; + this._basisX2X = __tmp__X5; + this._basisX2Y = __tmp__Y5; + this._basisX2Z = __tmp__Z5; + let __tmp__X6; + let __tmp__Y6; + let __tmp__Z6; + __tmp__X6 = tf2._rotation00 * this._localBasisY2X + tf2._rotation01 * this._localBasisY2Y + tf2._rotation02 * this._localBasisY2Z; + __tmp__Y6 = tf2._rotation10 * this._localBasisY2X + tf2._rotation11 * this._localBasisY2Y + tf2._rotation12 * this._localBasisY2Z; + __tmp__Z6 = tf2._rotation20 * this._localBasisY2X + tf2._rotation21 * this._localBasisY2Y + tf2._rotation22 * this._localBasisY2Z; + this._basisY2X = __tmp__X6; + this._basisY2Y = __tmp__Y6; + this._basisY2Z = __tmp__Z6; + let __tmp__X7; + let __tmp__Y7; + let __tmp__Z7; + __tmp__X7 = tf2._rotation00 * this._localBasisZ2X + tf2._rotation01 * this._localBasisZ2Y + tf2._rotation02 * this._localBasisZ2Z; + __tmp__Y7 = tf2._rotation10 * this._localBasisZ2X + tf2._rotation11 * this._localBasisZ2Y + tf2._rotation12 * this._localBasisZ2Z; + __tmp__Z7 = tf2._rotation20 * this._localBasisZ2X + tf2._rotation21 * this._localBasisZ2Y + tf2._rotation22 * this._localBasisZ2Z; + this._basisZ2X = __tmp__X7; + this._basisZ2Y = __tmp__Y7; + this._basisZ2Z = __tmp__Z7; + } + _getVelocitySolverInfo(timeStep,info) { + info.b1 = this._b1; + info.b2 = this._b2; + info.numRows = 0; + } + _getPositionSolverInfo(info) { + info.b1 = this._b1; + info.b2 = this._b2; + info.numRows = 0; + } + _checkDestruction() { + let torqueSq = this._appliedTorqueX * this._appliedTorqueX + this._appliedTorqueY * this._appliedTorqueY + this._appliedTorqueZ * this._appliedTorqueZ; + if(this._breakForce > 0 && this._appliedForceX * this._appliedForceX + this._appliedForceY * this._appliedForceY + this._appliedForceZ * this._appliedForceZ > this._breakForce * this._breakForce) { + this._world.removeJoint(this); + return; + } + if(this._breakTorque > 0 && torqueSq > this._breakTorque * this._breakTorque) { + this._world.removeJoint(this); + return; + } + } + getRigidBody1() { + return this._b1; + } + getRigidBody2() { + return this._b2; + } + getType() { + return this._type; + } + getAnchor1() { + let v = new oimo.common.Vec3(); + v.x = this._anchor1X; + v.y = this._anchor1Y; + v.z = this._anchor1Z; + return v; + } + getAnchor2() { + let v = new oimo.common.Vec3(); + v.x = this._anchor2X; + v.y = this._anchor2Y; + v.z = this._anchor2Z; + return v; + } + getAnchor1To(anchor) { + anchor.x = this._anchor1X; + anchor.y = this._anchor1Y; + anchor.z = this._anchor1Z; + } + getAnchor2To(anchor) { + anchor.x = this._anchor2X; + anchor.y = this._anchor2Y; + anchor.z = this._anchor2Z; + } + getLocalAnchor1() { + let v = new oimo.common.Vec3(); + v.x = this._localAnchor1X; + v.y = this._localAnchor1Y; + v.z = this._localAnchor1Z; + return v; + } + getLocalAnchor2() { + let v = new oimo.common.Vec3(); + v.x = this._localAnchor2X; + v.y = this._localAnchor2Y; + v.z = this._localAnchor2Z; + return v; + } + getLocalAnchor1To(localAnchor) { + localAnchor.x = this._localAnchor1X; + localAnchor.y = this._localAnchor1Y; + localAnchor.z = this._localAnchor1Z; + } + getLocalAnchor2To(localAnchor) { + localAnchor.x = this._localAnchor2X; + localAnchor.y = this._localAnchor2Y; + localAnchor.z = this._localAnchor2Z; + } + getBasis1() { + let m = new oimo.common.Mat3(); + let b00; + let b01; + let b02; + let b10; + let b11; + let b12; + let b20; + let b21; + let b22; + b00 = this._basisX1X; + b01 = this._basisY1X; + b02 = this._basisZ1X; + b10 = this._basisX1Y; + b11 = this._basisY1Y; + b12 = this._basisZ1Y; + b20 = this._basisX1Z; + b21 = this._basisY1Z; + b22 = this._basisZ1Z; + m.e00 = b00; + m.e01 = b01; + m.e02 = b02; + m.e10 = b10; + m.e11 = b11; + m.e12 = b12; + m.e20 = b20; + m.e21 = b21; + m.e22 = b22; + return m; + } + getBasis2() { + let m = new oimo.common.Mat3(); + let b00; + let b01; + let b02; + let b10; + let b11; + let b12; + let b20; + let b21; + let b22; + b00 = this._basisX2X; + b01 = this._basisY2X; + b02 = this._basisZ2X; + b10 = this._basisX2Y; + b11 = this._basisY2Y; + b12 = this._basisZ2Y; + b20 = this._basisX2Z; + b21 = this._basisY2Z; + b22 = this._basisZ2Z; + m.e00 = b00; + m.e01 = b01; + m.e02 = b02; + m.e10 = b10; + m.e11 = b11; + m.e12 = b12; + m.e20 = b20; + m.e21 = b21; + m.e22 = b22; + return m; + } + getBasis1To(basis) { + let b00; + let b01; + let b02; + let b10; + let b11; + let b12; + let b20; + let b21; + let b22; + b00 = this._basisX1X; + b01 = this._basisY1X; + b02 = this._basisZ1X; + b10 = this._basisX1Y; + b11 = this._basisY1Y; + b12 = this._basisZ1Y; + b20 = this._basisX1Z; + b21 = this._basisY1Z; + b22 = this._basisZ1Z; + basis.e00 = b00; + basis.e01 = b01; + basis.e02 = b02; + basis.e10 = b10; + basis.e11 = b11; + basis.e12 = b12; + basis.e20 = b20; + basis.e21 = b21; + basis.e22 = b22; + } + getBasis2To(basis) { + let b00; + let b01; + let b02; + let b10; + let b11; + let b12; + let b20; + let b21; + let b22; + b00 = this._basisX2X; + b01 = this._basisY2X; + b02 = this._basisZ2X; + b10 = this._basisX2Y; + b11 = this._basisY2Y; + b12 = this._basisZ2Y; + b20 = this._basisX2Z; + b21 = this._basisY2Z; + b22 = this._basisZ2Z; + basis.e00 = b00; + basis.e01 = b01; + basis.e02 = b02; + basis.e10 = b10; + basis.e11 = b11; + basis.e12 = b12; + basis.e20 = b20; + basis.e21 = b21; + basis.e22 = b22; + } + getAllowCollision() { + return this._allowCollision; + } + setAllowCollision(allowCollision) { + this._allowCollision = allowCollision; + } + getBreakForce() { + return this._breakForce; + } + setBreakForce(breakForce) { + this._breakForce = breakForce; + } + getBreakTorque() { + return this._breakTorque; + } + setBreakTorque(breakTorque) { + this._breakTorque = breakTorque; + } + getPositionCorrectionAlgorithm() { + return this._positionCorrectionAlgorithm; + } + setPositionCorrectionAlgorithm(positionCorrectionAlgorithm) { + switch(positionCorrectionAlgorithm) { + case 0:case 1:case 2: + break; + default: + throw new Error("invalid position correction algorithm id: " + positionCorrectionAlgorithm); + } + this._positionCorrectionAlgorithm = positionCorrectionAlgorithm; + } + getAppliedForce() { + let v = new oimo.common.Vec3(); + v.x = this._appliedForceX; + v.y = this._appliedForceY; + v.z = this._appliedForceZ; + return v; + } + getAppliedForceTo(appliedForce) { + appliedForce.x = this._appliedForceX; + appliedForce.y = this._appliedForceY; + appliedForce.z = this._appliedForceZ; + } + getAppliedTorque() { + let v = new oimo.common.Vec3(); + v.x = this._appliedTorqueX; + v.y = this._appliedTorqueY; + v.z = this._appliedTorqueZ; + return v; + } + getAppliedTorqueTo(appliedTorque) { + appliedTorque.x = this._appliedTorqueX; + appliedTorque.y = this._appliedTorqueY; + appliedTorque.z = this._appliedTorqueZ; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.constraint.joint.CylindricalJoint = class oimo_dynamics_constraint_joint_CylindricalJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,2); + let v = config.localAxis1; + this._localBasisX1X = v.x; + this._localBasisX1Y = v.y; + this._localBasisX1Z = v.z; + let v1 = config.localAxis2; + this._localBasisX2X = v1.x; + this._localBasisX2Y = v1.y; + this._localBasisX2Z = v1.z; + this.buildLocalBasesFromX(); + this.angle = 0; + this.angularErrorY = 0; + this.angularErrorZ = 0; + this.translation = 0; + this.linearErrorY = 0; + this.linearErrorZ = 0; + this._basis = new oimo.dynamics.constraint.joint.BasisTracker(this); + this._translSd = config.translationalSpringDamper.clone(); + this._translLm = config.translationalLimitMotor.clone(); + this._rotSd = config.rotationalSpringDamper.clone(); + this._rotLm = config.rotationalLimitMotor.clone(); + } + getInfo(info,timeStep,isPositionPart) { + let erp = this.getErp(timeStep,isPositionPart); + let linRhsY = this.linearErrorY * erp; + let linRhsZ = this.linearErrorZ * erp; + let angRhsY = this.angularErrorY * erp; + let angRhsZ = this.angularErrorZ * erp; + let j; + let translationalMotorMass = 1 / (this._b1._invMass + this._b2._invMass); + let rotationalMotorMass = this.computeEffectiveInertiaMoment(this._basis.xX,this._basis.xY,this._basis.xZ); + if(this._translSd.frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowLinear(row,this.translation,this._translLm,translationalMotorMass,this._translSd,timeStep,isPositionPart); + j = row.jacobian; + j.lin1X = this._basis.xX; + j.lin1Y = this._basis.xY; + j.lin1Z = this._basis.xZ; + j.lin2X = this._basis.xX; + j.lin2Y = this._basis.xY; + j.lin2Z = this._basis.xZ; + j.ang1X = this._relativeAnchor1Y * this._basis.xZ - this._relativeAnchor1Z * this._basis.xY; + j.ang1Y = this._relativeAnchor1Z * this._basis.xX - this._relativeAnchor1X * this._basis.xZ; + j.ang1Z = this._relativeAnchor1X * this._basis.xY - this._relativeAnchor1Y * this._basis.xX; + j.ang2X = this._relativeAnchor2Y * this._basis.xZ - this._relativeAnchor2Z * this._basis.xY; + j.ang2Y = this._relativeAnchor2Z * this._basis.xX - this._relativeAnchor2X * this._basis.xZ; + j.ang2Z = this._relativeAnchor2X * this._basis.xY - this._relativeAnchor2Y * this._basis.xX; + } + let impulse = this._impulses[1]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linRhsY; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + j = row.jacobian; + j.lin1X = this._basis.yX; + j.lin1Y = this._basis.yY; + j.lin1Z = this._basis.yZ; + j.lin2X = this._basis.yX; + j.lin2Y = this._basis.yY; + j.lin2Z = this._basis.yZ; + j.ang1X = this._relativeAnchor1Y * this._basis.yZ - this._relativeAnchor1Z * this._basis.yY; + j.ang1Y = this._relativeAnchor1Z * this._basis.yX - this._relativeAnchor1X * this._basis.yZ; + j.ang1Z = this._relativeAnchor1X * this._basis.yY - this._relativeAnchor1Y * this._basis.yX; + j.ang2X = this._relativeAnchor2Y * this._basis.yZ - this._relativeAnchor2Z * this._basis.yY; + j.ang2Y = this._relativeAnchor2Z * this._basis.yX - this._relativeAnchor2X * this._basis.yZ; + j.ang2Z = this._relativeAnchor2X * this._basis.yY - this._relativeAnchor2Y * this._basis.yX; + let impulse1 = this._impulses[2]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linRhsZ; + row1.cfm = 0; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = this._basis.zX; + j.lin1Y = this._basis.zY; + j.lin1Z = this._basis.zZ; + j.lin2X = this._basis.zX; + j.lin2Y = this._basis.zY; + j.lin2Z = this._basis.zZ; + j.ang1X = this._relativeAnchor1Y * this._basis.zZ - this._relativeAnchor1Z * this._basis.zY; + j.ang1Y = this._relativeAnchor1Z * this._basis.zX - this._relativeAnchor1X * this._basis.zZ; + j.ang1Z = this._relativeAnchor1X * this._basis.zY - this._relativeAnchor1Y * this._basis.zX; + j.ang2X = this._relativeAnchor2Y * this._basis.zZ - this._relativeAnchor2Z * this._basis.zY; + j.ang2Y = this._relativeAnchor2Z * this._basis.zX - this._relativeAnchor2X * this._basis.zZ; + j.ang2Z = this._relativeAnchor2X * this._basis.zY - this._relativeAnchor2Y * this._basis.zX; + if(this._rotSd.frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[3]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this.angle,this._rotLm,rotationalMotorMass,this._rotSd,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._basis.xX; + j.ang1Y = this._basis.xY; + j.ang1Z = this._basis.xZ; + j.ang2X = this._basis.xX; + j.ang2Y = this._basis.xY; + j.ang2Z = this._basis.xZ; + } + let impulse2 = this._impulses[4]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = angRhsY; + row2.cfm = 0; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.ang1X = this._basis.yX; + j.ang1Y = this._basis.yY; + j.ang1Z = this._basis.yZ; + j.ang2X = this._basis.yX; + j.ang2Y = this._basis.yY; + j.ang2Z = this._basis.yZ; + let impulse3 = this._impulses[5]; + let row3 = info.rows[info.numRows++]; + let _this3 = row3.jacobian; + _this3.lin1X = 0; + _this3.lin1Y = 0; + _this3.lin1Z = 0; + _this3.lin2X = 0; + _this3.lin2Y = 0; + _this3.lin2Z = 0; + _this3.ang1X = 0; + _this3.ang1Y = 0; + _this3.ang1Z = 0; + _this3.ang2X = 0; + _this3.ang2Y = 0; + _this3.ang2Z = 0; + row3.rhs = 0; + row3.cfm = 0; + row3.minImpulse = 0; + row3.maxImpulse = 0; + row3.motorSpeed = 0; + row3.motorMaxImpulse = 0; + row3.impulse = null; + row3.impulse = impulse3; + row3.rhs = angRhsZ; + row3.cfm = 0; + row3.minImpulse = -1e65536; + row3.maxImpulse = 1e65536; + j = row3.jacobian; + j.ang1X = this._basis.zX; + j.ang1Y = this._basis.zY; + j.ang1Z = this._basis.zZ; + j.ang2X = this._basis.zX; + j.ang2Y = this._basis.zY; + j.ang2Z = this._basis.zZ; + } + _syncAnchors() { + super._syncAnchors(); + let _this = this._basis; + let invM1 = _this.joint._b1._invMass; + let invM2 = _this.joint._b2._invMass; + let qX; + let qY; + let qZ; + let qW; + let idQX; + let idQY; + let idQZ; + let idQW; + let slerpQX; + let slerpQY; + let slerpQZ; + let slerpQW; + let slerpM00; + let slerpM01; + let slerpM02; + let slerpM10; + let slerpM11; + let slerpM12; + let slerpM20; + let slerpM21; + let slerpM22; + let newXX; + let newXY; + let newXZ; + let newYX; + let newYY; + let newYZ; + let newZX; + let newZY; + let newZZ; + let prevXX; + let prevXY; + let prevXZ; + let prevYX; + let prevYY; + let prevYZ; + let d = _this.joint._basisX1X * _this.joint._basisX2X + _this.joint._basisX1Y * _this.joint._basisX2Y + _this.joint._basisX1Z * _this.joint._basisX2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = _this.joint._basisX1X; + let y1 = _this.joint._basisX1Y; + let z1 = _this.joint._basisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + qX = vX; + qY = vY; + qZ = vZ; + qW = 0; + } else { + let cX; + let cY; + let cZ; + cX = _this.joint._basisX1Y * _this.joint._basisX2Z - _this.joint._basisX1Z * _this.joint._basisX2Y; + cY = _this.joint._basisX1Z * _this.joint._basisX2X - _this.joint._basisX1X * _this.joint._basisX2Z; + cZ = _this.joint._basisX1X * _this.joint._basisX2Y - _this.joint._basisX1Y * _this.joint._basisX2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + qX = cX; + qY = cY; + qZ = cZ; + qW = w; + } + idQX = 0; + idQY = 0; + idQZ = 0; + idQW = 1; + let q1X; + let q1Y; + let q1Z; + let q1W; + let q2X; + let q2Y; + let q2Z; + let q2W; + q1X = idQX; + q1Y = idQY; + q1Z = idQZ; + q1W = idQW; + q2X = qX; + q2Y = qY; + q2Z = qZ; + q2W = qW; + let d1 = q1X * q2X + q1Y * q2Y + q1Z * q2Z + q1W * q2W; + if(d1 < 0) { + d1 = -d1; + q2X = -q2X; + q2Y = -q2Y; + q2Z = -q2Z; + q2W = -q2W; + } + if(d1 > 0.999999) { + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = q2X - q1X; + dqY = q2Y - q1Y; + dqZ = q2Z - q1Z; + dqW = q2W - q1W; + q2X = q1X + dqX * (invM1 / (invM1 + invM2)); + q2Y = q1Y + dqY * (invM1 / (invM1 + invM2)); + q2Z = q1Z + dqZ * (invM1 / (invM1 + invM2)); + q2W = q1W + dqW * (invM1 / (invM1 + invM2)); + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + slerpQX = q2X * l; + slerpQY = q2Y * l; + slerpQZ = q2Z * l; + slerpQW = q2W * l; + } else { + let theta = invM1 / (invM1 + invM2) * Math.acos(d1); + q2X += q1X * -d1; + q2Y += q1Y * -d1; + q2Z += q1Z * -d1; + q2W += q1W * -d1; + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + q2X *= l; + q2Y *= l; + q2Z *= l; + q2W *= l; + let sin = Math.sin(theta); + let cos = Math.cos(theta); + q1X *= cos; + q1Y *= cos; + q1Z *= cos; + q1W *= cos; + slerpQX = q1X + q2X * sin; + slerpQY = q1Y + q2Y * sin; + slerpQZ = q1Z + q2Z * sin; + slerpQW = q1W + q2W * sin; + } + let x = slerpQX; + let y = slerpQY; + let z = slerpQZ; + let w = slerpQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + slerpM00 = 1 - yy - zz; + slerpM01 = xy - wz; + slerpM02 = xz + wy; + slerpM10 = xy + wz; + slerpM11 = 1 - xx - zz; + slerpM12 = yz - wx; + slerpM20 = xz - wy; + slerpM21 = yz + wx; + slerpM22 = 1 - xx - yy; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = slerpM00 * _this.joint._basisX1X + slerpM01 * _this.joint._basisX1Y + slerpM02 * _this.joint._basisX1Z; + __tmp__Y = slerpM10 * _this.joint._basisX1X + slerpM11 * _this.joint._basisX1Y + slerpM12 * _this.joint._basisX1Z; + __tmp__Z = slerpM20 * _this.joint._basisX1X + slerpM21 * _this.joint._basisX1Y + slerpM22 * _this.joint._basisX1Z; + newXX = __tmp__X; + newXY = __tmp__Y; + newXZ = __tmp__Z; + prevXX = _this.xX; + prevXY = _this.xY; + prevXZ = _this.xZ; + prevYX = _this.yX; + prevYY = _this.yY; + prevYZ = _this.yZ; + let d2 = prevXX * newXX + prevXY * newXY + prevXZ * newXZ; + if(d2 < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = prevXX; + let y1 = prevXY; + let z1 = prevXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + slerpQX = vX; + slerpQY = vY; + slerpQZ = vZ; + slerpQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = prevXY * newXZ - prevXZ * newXY; + cY = prevXZ * newXX - prevXX * newXZ; + cZ = prevXX * newXY - prevXY * newXX; + let w = Math.sqrt((1 + d2) * 0.5); + d2 = 0.5 / w; + cX *= d2; + cY *= d2; + cZ *= d2; + slerpQX = cX; + slerpQY = cY; + slerpQZ = cZ; + slerpQW = w; + } + let x1 = slerpQX; + let y1 = slerpQY; + let z1 = slerpQZ; + let w1 = slerpQW; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + slerpM00 = 1 - yy1 - zz1; + slerpM01 = xy1 - wz1; + slerpM02 = xz1 + wy1; + slerpM10 = xy1 + wz1; + slerpM11 = 1 - xx1 - zz1; + slerpM12 = yz1 - wx1; + slerpM20 = xz1 - wy1; + slerpM21 = yz1 + wx1; + slerpM22 = 1 - xx1 - yy1; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = slerpM00 * prevYX + slerpM01 * prevYY + slerpM02 * prevYZ; + __tmp__Y1 = slerpM10 * prevYX + slerpM11 * prevYY + slerpM12 * prevYZ; + __tmp__Z1 = slerpM20 * prevYX + slerpM21 * prevYY + slerpM22 * prevYZ; + newYX = __tmp__X1; + newYY = __tmp__Y1; + newYZ = __tmp__Z1; + newZX = newXY * newYZ - newXZ * newYY; + newZY = newXZ * newYX - newXX * newYZ; + newZZ = newXX * newYY - newXY * newYX; + if(newZX * newZX + newZY * newZY + newZZ * newZZ > 1e-6) { + let l = newZX * newZX + newZY * newZY + newZZ * newZZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + newZX *= l; + newZY *= l; + newZZ *= l; + } else { + let x1 = newXX; + let y1 = newXY; + let z1 = newXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + newZX = 0; + newZY = z1 * d; + newZZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + newZX = -z1 * d; + newZY = 0; + newZZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } + newYX = newZY * newXZ - newZZ * newXY; + newYY = newZZ * newXX - newZX * newXZ; + newYZ = newZX * newXY - newZY * newXX; + _this.xX = newXX; + _this.xY = newXY; + _this.xZ = newXZ; + _this.yX = newYX; + _this.yY = newYY; + _this.yZ = newYZ; + _this.zX = newZX; + _this.zY = newZY; + _this.zZ = newZZ; + let angErrorX; + let angErrorY; + let angErrorZ; + angErrorX = this._basisX1Y * this._basisX2Z - this._basisX1Z * this._basisX2Y; + angErrorY = this._basisX1Z * this._basisX2X - this._basisX1X * this._basisX2Z; + angErrorZ = this._basisX1X * this._basisX2Y - this._basisX1Y * this._basisX2X; + let cos = this._basisX1X * this._basisX2X + this._basisX1Y * this._basisX2Y + this._basisX1Z * this._basisX2Z; + let theta = cos <= -1 ? 3.14159265358979 : cos >= 1 ? 0 : Math.acos(cos); + let l = angErrorX * angErrorX + angErrorY * angErrorY + angErrorZ * angErrorZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + angErrorX *= l; + angErrorY *= l; + angErrorZ *= l; + angErrorX *= theta; + angErrorY *= theta; + angErrorZ *= theta; + this.angularErrorY = angErrorX * this._basis.yX + angErrorY * this._basis.yY + angErrorZ * this._basis.yZ; + this.angularErrorZ = angErrorX * this._basis.zX + angErrorY * this._basis.zY + angErrorZ * this._basis.zZ; + let perpCrossX; + let perpCrossY; + let perpCrossZ; + perpCrossX = this._basisY1Y * this._basisY2Z - this._basisY1Z * this._basisY2Y; + perpCrossY = this._basisY1Z * this._basisY2X - this._basisY1X * this._basisY2Z; + perpCrossZ = this._basisY1X * this._basisY2Y - this._basisY1Y * this._basisY2X; + cos = this._basisY1X * this._basisY2X + this._basisY1Y * this._basisY2Y + this._basisY1Z * this._basisY2Z; + this.angle = cos <= -1 ? 3.14159265358979 : cos >= 1 ? 0 : Math.acos(cos); + if(perpCrossX * this._basis.xX + perpCrossY * this._basis.xY + perpCrossZ * this._basis.xZ < 0) { + this.angle = -this.angle; + } + let anchorDiffX; + let anchorDiffY; + let anchorDiffZ; + anchorDiffX = this._anchor2X - this._anchor1X; + anchorDiffY = this._anchor2Y - this._anchor1Y; + anchorDiffZ = this._anchor2Z - this._anchor1Z; + this.translation = anchorDiffX * this._basis.xX + anchorDiffY * this._basis.xY + anchorDiffZ * this._basis.xZ; + this.linearErrorY = anchorDiffX * this._basis.yX + anchorDiffY * this._basis.yY + anchorDiffZ * this._basis.yZ; + this.linearErrorZ = anchorDiffX * this._basis.zX + anchorDiffY * this._basis.zY + anchorDiffZ * this._basis.zZ; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._basisX2X; + v.y = this._basisX2Y; + v.z = this._basisX2Z; + return v; + } + getAxis1To(axis) { + axis.x = this._basisX1X; + axis.y = this._basisX1Y; + axis.z = this._basisX1Z; + } + getAxis2To(axis) { + axis.x = this._basisX2X; + axis.y = this._basisX2Y; + axis.z = this._basisX2Z; + } + getLocalAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX1X; + v.y = this._localBasisX1Y; + v.z = this._localBasisX1Z; + return v; + } + getLocalAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX2X; + v.y = this._localBasisX2Y; + v.z = this._localBasisX2Z; + return v; + } + getLocalAxis1To(axis) { + axis.x = this._localBasisX1X; + axis.y = this._localBasisX1Y; + axis.z = this._localBasisX1Z; + } + getLocalAxis2To(axis) { + axis.x = this._localBasisX2X; + axis.y = this._localBasisX2Y; + axis.z = this._localBasisX2Z; + } + getTranslationalSpringDamper() { + return this._translSd; + } + getRotationalSpringDamper() { + return this._rotSd; + } + getTranslationalLimitMotor() { + return this._translLm; + } + getRotationalLimitMotor() { + return this._rotLm; + } + getAngle() { + return this.angle; + } + getTranslation() { + return this.translation; + } +} +oimo.dynamics.constraint.joint.JointConfig = class oimo_dynamics_constraint_joint_JointConfig { + constructor() { + this.rigidBody1 = null; + this.rigidBody2 = null; + this.localAnchor1 = new oimo.common.Vec3(); + this.localAnchor2 = new oimo.common.Vec3(); + this.allowCollision = false; + this.solverType = oimo.common.Setting.defaultJointConstraintSolverType; + this.positionCorrectionAlgorithm = oimo.common.Setting.defaultJointPositionCorrectionAlgorithm; + this.breakForce = 0; + this.breakTorque = 0; + } + _init(rb1,rb2,worldAnchor) { + this.rigidBody1 = rb1; + this.rigidBody2 = rb2; + let _this = this.rigidBody1; + let localPoint = this.localAnchor1; + let vX; + let vY; + let vZ; + vX = worldAnchor.x; + vY = worldAnchor.y; + vZ = worldAnchor.z; + vX -= _this._transform._positionX; + vY -= _this._transform._positionY; + vZ -= _this._transform._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = _this._transform._rotation00 * vX + _this._transform._rotation10 * vY + _this._transform._rotation20 * vZ; + __tmp__Y = _this._transform._rotation01 * vX + _this._transform._rotation11 * vY + _this._transform._rotation21 * vZ; + __tmp__Z = _this._transform._rotation02 * vX + _this._transform._rotation12 * vY + _this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localPoint.x = vX; + localPoint.y = vY; + localPoint.z = vZ; + let _this1 = this.rigidBody2; + let localPoint1 = this.localAnchor2; + let vX1; + let vY1; + let vZ1; + vX1 = worldAnchor.x; + vY1 = worldAnchor.y; + vZ1 = worldAnchor.z; + vX1 -= _this1._transform._positionX; + vY1 -= _this1._transform._positionY; + vZ1 -= _this1._transform._positionZ; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = _this1._transform._rotation00 * vX1 + _this1._transform._rotation10 * vY1 + _this1._transform._rotation20 * vZ1; + __tmp__Y1 = _this1._transform._rotation01 * vX1 + _this1._transform._rotation11 * vY1 + _this1._transform._rotation21 * vZ1; + __tmp__Z1 = _this1._transform._rotation02 * vX1 + _this1._transform._rotation12 * vY1 + _this1._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localPoint1.x = vX1; + localPoint1.y = vY1; + localPoint1.z = vZ1; + } +} +oimo.dynamics.constraint.joint.CylindricalJointConfig = class oimo_dynamics_constraint_joint_CylindricalJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localAxis1 = new oimo.common.Vec3(1,0,0); + this.localAxis2 = new oimo.common.Vec3(1,0,0); + this.translationalLimitMotor = new oimo.dynamics.constraint.joint.TranslationalLimitMotor(); + this.translationalSpringDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + this.rotationalLimitMotor = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + this.rotationalSpringDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + } + init(rigidBody1,rigidBody2,worldAnchor,worldAxis) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let localVector = this.localAxis1; + let vX; + let vY; + let vZ; + vX = worldAxis.x; + vY = worldAxis.y; + vZ = worldAxis.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rigidBody1._transform._rotation00 * vX + rigidBody1._transform._rotation10 * vY + rigidBody1._transform._rotation20 * vZ; + __tmp__Y = rigidBody1._transform._rotation01 * vX + rigidBody1._transform._rotation11 * vY + rigidBody1._transform._rotation21 * vZ; + __tmp__Z = rigidBody1._transform._rotation02 * vX + rigidBody1._transform._rotation12 * vY + rigidBody1._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + let localVector1 = this.localAxis2; + let vX1; + let vY1; + let vZ1; + vX1 = worldAxis.x; + vY1 = worldAxis.y; + vZ1 = worldAxis.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = rigidBody2._transform._rotation00 * vX1 + rigidBody2._transform._rotation10 * vY1 + rigidBody2._transform._rotation20 * vZ1; + __tmp__Y1 = rigidBody2._transform._rotation01 * vX1 + rigidBody2._transform._rotation11 * vY1 + rigidBody2._transform._rotation21 * vZ1; + __tmp__Z1 = rigidBody2._transform._rotation02 * vX1 + rigidBody2._transform._rotation12 * vY1 + rigidBody2._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localVector1.x = vX1; + localVector1.y = vY1; + localVector1.z = vZ1; + return this; + } +} +oimo.dynamics.constraint.joint.GenericJoint = class oimo_dynamics_constraint_joint_GenericJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,oimo.dynamics.constraint.joint.JointType.GENERIC); + let tmp; + let _this = config.localBasis1; + if(!(_this.e00 * (_this.e11 * _this.e22 - _this.e12 * _this.e21) - _this.e01 * (_this.e10 * _this.e22 - _this.e12 * _this.e20) + _this.e02 * (_this.e10 * _this.e21 - _this.e11 * _this.e20) < 0)) { + let _this = config.localBasis2; + tmp = _this.e00 * (_this.e11 * _this.e22 - _this.e12 * _this.e21) - _this.e01 * (_this.e10 * _this.e22 - _this.e12 * _this.e20) + _this.e02 * (_this.e10 * _this.e21 - _this.e11 * _this.e20) < 0; + } else { + tmp = true; + } + if(tmp) { + console.log("src/oimo/dynamics/constraint/joint/GenericJoint.hx:50:","[warning] joint basis must be right handed"); + } + let lb100; + let lb101; + let lb102; + let lb110; + let lb111; + let lb112; + let lb120; + let lb121; + let lb122; + let lb200; + let lb201; + let lb202; + let lb210; + let lb211; + let lb212; + let lb220; + let lb221; + let lb222; + let m = config.localBasis1; + lb100 = m.e00; + lb101 = m.e01; + lb102 = m.e02; + lb110 = m.e10; + lb111 = m.e11; + lb112 = m.e12; + lb120 = m.e20; + lb121 = m.e21; + lb122 = m.e22; + let m1 = config.localBasis2; + lb200 = m1.e00; + lb201 = m1.e01; + lb202 = m1.e02; + lb210 = m1.e10; + lb211 = m1.e11; + lb212 = m1.e12; + lb220 = m1.e20; + lb221 = m1.e21; + lb222 = m1.e22; + this._localBasisX1X = lb100; + this._localBasisX1Y = lb110; + this._localBasisX1Z = lb120; + this._localBasisY1X = lb101; + this._localBasisY1Y = lb111; + this._localBasisY1Z = lb121; + this._localBasisZ1X = lb102; + this._localBasisZ1Y = lb112; + this._localBasisZ1Z = lb122; + this._localBasisX2X = lb200; + this._localBasisX2Y = lb210; + this._localBasisX2Z = lb220; + this._localBasisY2X = lb201; + this._localBasisY2Y = lb211; + this._localBasisY2Z = lb221; + this._localBasisZ2X = lb202; + this._localBasisZ2Y = lb212; + this._localBasisZ2Z = lb222; + this._angleX = 0; + this._angleY = 0; + this._angleZ = 0; + this.translationX = 0; + this.translationY = 0; + this.translationZ = 0; + this.xSingular = false; + this.ySingular = false; + this.zSingular = false; + this._translLms = new Array(3); + this._translSds = new Array(3); + this._rotLms = new Array(3); + this._rotSds = new Array(3); + this._translLms[0] = config.translationalLimitMotors[0].clone(); + this._translLms[1] = config.translationalLimitMotors[1].clone(); + this._translLms[2] = config.translationalLimitMotors[2].clone(); + this._translSds[0] = config.translationalSpringDampers[0].clone(); + this._translSds[1] = config.translationalSpringDampers[1].clone(); + this._translSds[2] = config.translationalSpringDampers[2].clone(); + this._rotLms[0] = config.rotationalLimitMotors[0].clone(); + this._rotLms[1] = config.rotationalLimitMotors[1].clone(); + this._rotLms[2] = config.rotationalLimitMotors[2].clone(); + this._rotSds[0] = config.rotationalSpringDampers[0].clone(); + this._rotSds[1] = config.rotationalSpringDampers[1].clone(); + this._rotSds[2] = config.rotationalSpringDampers[2].clone(); + } + getInfo(info,timeStep,isPositionPart) { + let j; + let translMotorMass = 1 / (this._b1._invMass + this._b2._invMass); + let motorMassX = this.computeEffectiveInertiaMoment(this._axisXX,this._axisXY,this._axisXZ); + let motorMassY = this.computeEffectiveInertiaMoment(this._axisYX,this._axisYY,this._axisYZ); + let motorMassZ = this.computeEffectiveInertiaMoment(this._axisZX,this._axisZY,this._axisZZ); + if(this._translSds[0].frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowLinear(row,this.translationX,this._translLms[0],translMotorMass,this._translSds[0],timeStep,isPositionPart); + j = row.jacobian; + j.lin1X = this._basisX1X; + j.lin1Y = this._basisX1Y; + j.lin1Z = this._basisX1Z; + j.lin2X = this._basisX1X; + j.lin2Y = this._basisX1Y; + j.lin2Z = this._basisX1Z; + j.ang1X = this._relativeAnchor1Y * this._basisX1Z - this._relativeAnchor1Z * this._basisX1Y; + j.ang1Y = this._relativeAnchor1Z * this._basisX1X - this._relativeAnchor1X * this._basisX1Z; + j.ang1Z = this._relativeAnchor1X * this._basisX1Y - this._relativeAnchor1Y * this._basisX1X; + j.ang2X = this._relativeAnchor2Y * this._basisX1Z - this._relativeAnchor2Z * this._basisX1Y; + j.ang2Y = this._relativeAnchor2Z * this._basisX1X - this._relativeAnchor2X * this._basisX1Z; + j.ang2Z = this._relativeAnchor2X * this._basisX1Y - this._relativeAnchor2Y * this._basisX1X; + } + if(this._translSds[1].frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[1]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowLinear(row,this.translationY,this._translLms[1],translMotorMass,this._translSds[1],timeStep,isPositionPart); + j = row.jacobian; + j.lin1X = this._basisY1X; + j.lin1Y = this._basisY1Y; + j.lin1Z = this._basisY1Z; + j.lin2X = this._basisY1X; + j.lin2Y = this._basisY1Y; + j.lin2Z = this._basisY1Z; + j.ang1X = this._relativeAnchor1Y * this._basisY1Z - this._relativeAnchor1Z * this._basisY1Y; + j.ang1Y = this._relativeAnchor1Z * this._basisY1X - this._relativeAnchor1X * this._basisY1Z; + j.ang1Z = this._relativeAnchor1X * this._basisY1Y - this._relativeAnchor1Y * this._basisY1X; + j.ang2X = this._relativeAnchor2Y * this._basisY1Z - this._relativeAnchor2Z * this._basisY1Y; + j.ang2Y = this._relativeAnchor2Z * this._basisY1X - this._relativeAnchor2X * this._basisY1Z; + j.ang2Z = this._relativeAnchor2X * this._basisY1Y - this._relativeAnchor2Y * this._basisY1X; + } + if(this._translSds[2].frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[2]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowLinear(row,this.translationZ,this._translLms[2],translMotorMass,this._translSds[2],timeStep,isPositionPart); + j = row.jacobian; + j.lin1X = this._basisZ1X; + j.lin1Y = this._basisZ1Y; + j.lin1Z = this._basisZ1Z; + j.lin2X = this._basisZ1X; + j.lin2Y = this._basisZ1Y; + j.lin2Z = this._basisZ1Z; + j.ang1X = this._relativeAnchor1Y * this._basisZ1Z - this._relativeAnchor1Z * this._basisZ1Y; + j.ang1Y = this._relativeAnchor1Z * this._basisZ1X - this._relativeAnchor1X * this._basisZ1Z; + j.ang1Z = this._relativeAnchor1X * this._basisZ1Y - this._relativeAnchor1Y * this._basisZ1X; + j.ang2X = this._relativeAnchor2Y * this._basisZ1Z - this._relativeAnchor2Z * this._basisZ1Y; + j.ang2Y = this._relativeAnchor2Z * this._basisZ1X - this._relativeAnchor2X * this._basisZ1Z; + j.ang2Z = this._relativeAnchor2X * this._basisZ1Y - this._relativeAnchor2Y * this._basisZ1X; + } + if(!this.xSingular && (this._rotSds[0].frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[3]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._angleX,this._rotLms[0],motorMassX,this._rotSds[0],timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._axisXX; + j.ang1Y = this._axisXY; + j.ang1Z = this._axisXZ; + j.ang2X = this._axisXX; + j.ang2Y = this._axisXY; + j.ang2Z = this._axisXZ; + } + if(!this.ySingular && (this._rotSds[1].frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[4]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._angleY,this._rotLms[1],motorMassY,this._rotSds[1],timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._axisYX; + j.ang1Y = this._axisYY; + j.ang1Z = this._axisYZ; + j.ang2X = this._axisYX; + j.ang2Y = this._axisYY; + j.ang2Z = this._axisYZ; + } + if(!this.zSingular && (this._rotSds[2].frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[5]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._angleZ,this._rotLms[2],motorMassZ,this._rotSds[2],timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._axisZX; + j.ang1Y = this._axisZY; + j.ang1Z = this._axisZZ; + j.ang2X = this._axisZX; + j.ang2Y = this._axisZY; + j.ang2Z = this._axisZZ; + } + } + _syncAnchors() { + super._syncAnchors(); + let angleAxisXX; + let angleAxisXY; + let angleAxisXZ; + let angleAxisYX; + let angleAxisYY; + let angleAxisYZ; + let angleAxisZX; + let angleAxisZY; + let angleAxisZZ; + angleAxisXX = this._basisX1X; + angleAxisXY = this._basisX1Y; + angleAxisXZ = this._basisX1Z; + angleAxisZX = this._basisZ2X; + angleAxisZY = this._basisZ2Y; + angleAxisZZ = this._basisZ2Z; + angleAxisYX = angleAxisZY * angleAxisXZ - angleAxisZZ * angleAxisXY; + angleAxisYY = angleAxisZZ * angleAxisXX - angleAxisZX * angleAxisXZ; + angleAxisYZ = angleAxisZX * angleAxisXY - angleAxisZY * angleAxisXX; + this._axisXX = angleAxisYY * angleAxisZZ - angleAxisYZ * angleAxisZY; + this._axisXY = angleAxisYZ * angleAxisZX - angleAxisYX * angleAxisZZ; + this._axisXZ = angleAxisYX * angleAxisZY - angleAxisYY * angleAxisZX; + this._axisYX = angleAxisYX; + this._axisYY = angleAxisYY; + this._axisYZ = angleAxisYZ; + this._axisZX = angleAxisXY * angleAxisYZ - angleAxisXZ * angleAxisYY; + this._axisZY = angleAxisXZ * angleAxisYX - angleAxisXX * angleAxisYZ; + this._axisZZ = angleAxisXX * angleAxisYY - angleAxisXY * angleAxisYX; + let l = this._axisXX * this._axisXX + this._axisXY * this._axisXY + this._axisXZ * this._axisXZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._axisXX *= l; + this._axisXY *= l; + this._axisXZ *= l; + let l1 = this._axisYX * this._axisYX + this._axisYY * this._axisYY + this._axisYZ * this._axisYZ; + if(l1 > 0) { + l1 = 1 / Math.sqrt(l1); + } + this._axisYX *= l1; + this._axisYY *= l1; + this._axisYZ *= l1; + let l2 = this._axisZX * this._axisZX + this._axisZY * this._axisZY + this._axisZZ * this._axisZZ; + if(l2 > 0) { + l2 = 1 / Math.sqrt(l2); + } + this._axisZX *= l2; + this._axisZY *= l2; + this._axisZZ *= l2; + this.xSingular = this._axisXX * this._axisXX + this._axisXY * this._axisXY + this._axisXZ * this._axisXZ == 0; + this.ySingular = this._axisYX * this._axisYX + this._axisYY * this._axisYY + this._axisYZ * this._axisYZ == 0; + this.zSingular = this._axisZX * this._axisZX + this._axisZY * this._axisZY + this._axisZZ * this._axisZZ == 0; + let rot100; + let rot101; + let rot102; + let rot110; + let rot111; + let rot112; + let rot120; + let rot121; + let rot122; + let rot200; + let rot201; + let rot202; + let rot210; + let rot211; + let rot212; + let rot220; + let rot221; + let rot222; + rot100 = this._basisX1X; + rot101 = this._basisY1X; + rot102 = this._basisZ1X; + rot110 = this._basisX1Y; + rot111 = this._basisY1Y; + rot112 = this._basisZ1Y; + rot120 = this._basisX1Z; + rot121 = this._basisY1Z; + rot122 = this._basisZ1Z; + rot200 = this._basisX2X; + rot201 = this._basisY2X; + rot202 = this._basisZ2X; + rot210 = this._basisX2Y; + rot211 = this._basisY2Y; + rot212 = this._basisZ2Y; + rot220 = this._basisX2Z; + rot221 = this._basisY2Z; + rot222 = this._basisZ2Z; + let relRot00; + let relRot01; + let relRot02; + let relRot11; + let relRot12; + let relRot21; + let relRot22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__11; + let __tmp__12; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot100 * rot200 + rot110 * rot210 + rot120 * rot220; + __tmp__01 = rot100 * rot201 + rot110 * rot211 + rot120 * rot221; + __tmp__02 = rot100 * rot202 + rot110 * rot212 + rot120 * rot222; + __tmp__11 = rot101 * rot201 + rot111 * rot211 + rot121 * rot221; + __tmp__12 = rot101 * rot202 + rot111 * rot212 + rot121 * rot222; + __tmp__21 = rot102 * rot201 + rot112 * rot211 + rot122 * rot221; + __tmp__22 = rot102 * rot202 + rot112 * rot212 + rot122 * rot222; + relRot00 = __tmp__00; + relRot01 = __tmp__01; + relRot02 = __tmp__02; + relRot11 = __tmp__11; + relRot12 = __tmp__12; + relRot21 = __tmp__21; + relRot22 = __tmp__22; + let anglesX; + let anglesY; + let anglesZ; + let sy = relRot02; + if(sy <= -1) { + let xSubZ = Math.atan2(relRot21,relRot11); + anglesX = xSubZ * 0.5; + anglesY = -1.570796326794895; + anglesZ = -xSubZ * 0.5; + } else if(sy >= 1) { + let xAddZ = Math.atan2(relRot21,relRot11); + anglesX = xAddZ * 0.5; + anglesY = 1.570796326794895; + anglesZ = xAddZ * 0.5; + } else { + anglesX = Math.atan2(-relRot12,relRot22); + anglesY = Math.asin(sy); + anglesZ = Math.atan2(-relRot01,relRot00); + } + this._angleX = anglesX; + this._angleY = anglesY; + this._angleZ = anglesZ; + let anchorDiffX; + let anchorDiffY; + let anchorDiffZ; + anchorDiffX = this._anchor2X - this._anchor1X; + anchorDiffY = this._anchor2Y - this._anchor1Y; + anchorDiffZ = this._anchor2Z - this._anchor1Z; + this.translationX = anchorDiffX * this._basisX1X + anchorDiffY * this._basisX1Y + anchorDiffZ * this._basisX1Z; + this.translationY = anchorDiffX * this._basisY1X + anchorDiffY * this._basisY1Y + anchorDiffZ * this._basisY1Z; + this.translationZ = anchorDiffX * this._basisZ1X + anchorDiffY * this._basisZ1Y + anchorDiffZ * this._basisZ1Z; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxisX() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxisY() { + let v = new oimo.common.Vec3(); + v.x = this._axisYX; + v.y = this._axisYY; + v.z = this._axisYZ; + return v; + } + getAxisZ() { + let v = new oimo.common.Vec3(); + v.x = this._basisZ2X; + v.y = this._basisZ2Y; + v.z = this._basisZ2Z; + return v; + } + getTranslationalSpringDampers() { + return this._translSds.slice(0); + } + getRotationalSpringDampers() { + return this._translSds.slice(0); + } + getTranslationalLimitMotors() { + return this._translLms.slice(0); + } + getRotationalLimitMotors() { + return this._rotLms.slice(0); + } + getAngles() { + return new oimo.common.Vec3(this._angleX,this._angleY,this._angleZ); + } + getTranslations() { + return new oimo.common.Vec3(this.translationX,this.translationY,this.translationZ); + } +} +oimo.dynamics.constraint.joint.GenericJointConfig = class oimo_dynamics_constraint_joint_GenericJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localBasis1 = new oimo.common.Mat3(); + this.localBasis2 = new oimo.common.Mat3(); + let _g = []; + _g.push(new oimo.dynamics.constraint.joint.TranslationalLimitMotor().setLimits(0,0)); + _g.push(new oimo.dynamics.constraint.joint.TranslationalLimitMotor().setLimits(0,0)); + _g.push(new oimo.dynamics.constraint.joint.TranslationalLimitMotor().setLimits(0,0)); + this.translationalLimitMotors = _g; + let _g1 = []; + _g1.push(new oimo.dynamics.constraint.joint.RotationalLimitMotor().setLimits(0,0)); + _g1.push(new oimo.dynamics.constraint.joint.RotationalLimitMotor().setLimits(0,0)); + _g1.push(new oimo.dynamics.constraint.joint.RotationalLimitMotor().setLimits(0,0)); + this.rotationalLimitMotors = _g1; + this.translationalSpringDampers = [new oimo.dynamics.constraint.joint.SpringDamper(),new oimo.dynamics.constraint.joint.SpringDamper(),new oimo.dynamics.constraint.joint.SpringDamper()]; + this.rotationalSpringDampers = [new oimo.dynamics.constraint.joint.SpringDamper(),new oimo.dynamics.constraint.joint.SpringDamper(),new oimo.dynamics.constraint.joint.SpringDamper()]; + } + init(rigidBody1,rigidBody2,worldAnchor,worldBasis1,worldBasis2) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let tf1 = rigidBody1._transform; + let tf2 = rigidBody2._transform; + let wb100; + let wb101; + let wb102; + let wb110; + let wb111; + let wb112; + let wb120; + let wb121; + let wb122; + let wb200; + let wb201; + let wb202; + let wb210; + let wb211; + let wb212; + let wb220; + let wb221; + let wb222; + let lb100; + let lb101; + let lb102; + let lb110; + let lb111; + let lb112; + let lb120; + let lb121; + let lb122; + let lb200; + let lb201; + let lb202; + let lb210; + let lb211; + let lb212; + let lb220; + let lb221; + let lb222; + wb100 = worldBasis1.e00; + wb101 = worldBasis1.e01; + wb102 = worldBasis1.e02; + wb110 = worldBasis1.e10; + wb111 = worldBasis1.e11; + wb112 = worldBasis1.e12; + wb120 = worldBasis1.e20; + wb121 = worldBasis1.e21; + wb122 = worldBasis1.e22; + wb200 = worldBasis2.e00; + wb201 = worldBasis2.e01; + wb202 = worldBasis2.e02; + wb210 = worldBasis2.e10; + wb211 = worldBasis2.e11; + wb212 = worldBasis2.e12; + wb220 = worldBasis2.e20; + wb221 = worldBasis2.e21; + wb222 = worldBasis2.e22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * wb100 + tf1._rotation10 * wb110 + tf1._rotation20 * wb120; + __tmp__01 = tf1._rotation00 * wb101 + tf1._rotation10 * wb111 + tf1._rotation20 * wb121; + __tmp__02 = tf1._rotation00 * wb102 + tf1._rotation10 * wb112 + tf1._rotation20 * wb122; + __tmp__10 = tf1._rotation01 * wb100 + tf1._rotation11 * wb110 + tf1._rotation21 * wb120; + __tmp__11 = tf1._rotation01 * wb101 + tf1._rotation11 * wb111 + tf1._rotation21 * wb121; + __tmp__12 = tf1._rotation01 * wb102 + tf1._rotation11 * wb112 + tf1._rotation21 * wb122; + __tmp__20 = tf1._rotation02 * wb100 + tf1._rotation12 * wb110 + tf1._rotation22 * wb120; + __tmp__21 = tf1._rotation02 * wb101 + tf1._rotation12 * wb111 + tf1._rotation22 * wb121; + __tmp__22 = tf1._rotation02 * wb102 + tf1._rotation12 * wb112 + tf1._rotation22 * wb122; + lb100 = __tmp__00; + lb101 = __tmp__01; + lb102 = __tmp__02; + lb110 = __tmp__10; + lb111 = __tmp__11; + lb112 = __tmp__12; + lb120 = __tmp__20; + lb121 = __tmp__21; + lb122 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * wb200 + tf2._rotation10 * wb210 + tf2._rotation20 * wb220; + __tmp__011 = tf2._rotation00 * wb201 + tf2._rotation10 * wb211 + tf2._rotation20 * wb221; + __tmp__021 = tf2._rotation00 * wb202 + tf2._rotation10 * wb212 + tf2._rotation20 * wb222; + __tmp__101 = tf2._rotation01 * wb200 + tf2._rotation11 * wb210 + tf2._rotation21 * wb220; + __tmp__111 = tf2._rotation01 * wb201 + tf2._rotation11 * wb211 + tf2._rotation21 * wb221; + __tmp__121 = tf2._rotation01 * wb202 + tf2._rotation11 * wb212 + tf2._rotation21 * wb222; + __tmp__201 = tf2._rotation02 * wb200 + tf2._rotation12 * wb210 + tf2._rotation22 * wb220; + __tmp__211 = tf2._rotation02 * wb201 + tf2._rotation12 * wb211 + tf2._rotation22 * wb221; + __tmp__221 = tf2._rotation02 * wb202 + tf2._rotation12 * wb212 + tf2._rotation22 * wb222; + lb200 = __tmp__001; + lb201 = __tmp__011; + lb202 = __tmp__021; + lb210 = __tmp__101; + lb211 = __tmp__111; + lb212 = __tmp__121; + lb220 = __tmp__201; + lb221 = __tmp__211; + lb222 = __tmp__221; + let m = this.localBasis1; + m.e00 = lb100; + m.e01 = lb101; + m.e02 = lb102; + m.e10 = lb110; + m.e11 = lb111; + m.e12 = lb112; + m.e20 = lb120; + m.e21 = lb121; + m.e22 = lb122; + let m1 = this.localBasis2; + m1.e00 = lb200; + m1.e01 = lb201; + m1.e02 = lb202; + m1.e10 = lb210; + m1.e11 = lb211; + m1.e12 = lb212; + m1.e20 = lb220; + m1.e21 = lb221; + m1.e22 = lb222; + return this; + } +} +oimo.dynamics.constraint.joint.JointImpulse = class oimo_dynamics_constraint_joint_JointImpulse { + constructor() { + this.impulse = 0; + this.impulseM = 0; + this.impulseP = 0; + } +} +oimo.dynamics.constraint.joint.JointLink = class oimo_dynamics_constraint_joint_JointLink { + constructor(joint) { + this._joint = joint; + } + getContact() { + return this._joint; + } + getOther() { + return this._other; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.constraint.joint.JointMacro = class oimo_dynamics_constraint_joint_JointMacro { +} +oimo.dynamics.constraint.joint.JointType = class oimo_dynamics_constraint_joint_JointType { +} +oimo.dynamics.constraint.joint.PrismaticJoint = class oimo_dynamics_constraint_joint_PrismaticJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,oimo.dynamics.constraint.joint.JointType.PRISMATIC); + let v = config.localAxis1; + this._localBasisX1X = v.x; + this._localBasisX1Y = v.y; + this._localBasisX1Z = v.z; + let v1 = config.localAxis2; + this._localBasisX2X = v1.x; + this._localBasisX2Y = v1.y; + this._localBasisX2Z = v1.z; + this.buildLocalBasesFromX(); + this._basis = new oimo.dynamics.constraint.joint.BasisTracker(this); + this.translation = 0; + this.linearErrorY = 0; + this.linearErrorZ = 0; + this.angularErrorX = 0; + this.angularErrorY = 0; + this.angularErrorZ = 0; + this._sd = config.springDamper.clone(); + this._lm = config.limitMotor.clone(); + } + getInfo(info,timeStep,isPositionPart) { + let erp = this.getErp(timeStep,isPositionPart); + let linRhsY = this.linearErrorY * erp; + let linRhsZ = this.linearErrorZ * erp; + let angRhsX = this.angularErrorX * erp; + let angRhsY = this.angularErrorY * erp; + let angRhsZ = this.angularErrorZ * erp; + let j; + if(this._sd.frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowLinear(row,this.translation,this._lm,1 / (this._b1._invMass + this._b2._invMass),this._sd,timeStep,isPositionPart); + j = row.jacobian; + j.lin1X = this._basis.xX; + j.lin1Y = this._basis.xY; + j.lin1Z = this._basis.xZ; + j.lin2X = this._basis.xX; + j.lin2Y = this._basis.xY; + j.lin2Z = this._basis.xZ; + j.ang1X = this._relativeAnchor1Y * this._basis.xZ - this._relativeAnchor1Z * this._basis.xY; + j.ang1Y = this._relativeAnchor1Z * this._basis.xX - this._relativeAnchor1X * this._basis.xZ; + j.ang1Z = this._relativeAnchor1X * this._basis.xY - this._relativeAnchor1Y * this._basis.xX; + j.ang2X = this._relativeAnchor2Y * this._basis.xZ - this._relativeAnchor2Z * this._basis.xY; + j.ang2Y = this._relativeAnchor2Z * this._basis.xX - this._relativeAnchor2X * this._basis.xZ; + j.ang2Z = this._relativeAnchor2X * this._basis.xY - this._relativeAnchor2Y * this._basis.xX; + } + let impulse = this._impulses[1]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linRhsY; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + j = row.jacobian; + j.lin1X = this._basis.yX; + j.lin1Y = this._basis.yY; + j.lin1Z = this._basis.yZ; + j.lin2X = this._basis.yX; + j.lin2Y = this._basis.yY; + j.lin2Z = this._basis.yZ; + j.ang1X = this._relativeAnchor1Y * this._basis.yZ - this._relativeAnchor1Z * this._basis.yY; + j.ang1Y = this._relativeAnchor1Z * this._basis.yX - this._relativeAnchor1X * this._basis.yZ; + j.ang1Z = this._relativeAnchor1X * this._basis.yY - this._relativeAnchor1Y * this._basis.yX; + j.ang2X = this._relativeAnchor2Y * this._basis.yZ - this._relativeAnchor2Z * this._basis.yY; + j.ang2Y = this._relativeAnchor2Z * this._basis.yX - this._relativeAnchor2X * this._basis.yZ; + j.ang2Z = this._relativeAnchor2X * this._basis.yY - this._relativeAnchor2Y * this._basis.yX; + let impulse1 = this._impulses[2]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linRhsZ; + row1.cfm = 0; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = this._basis.zX; + j.lin1Y = this._basis.zY; + j.lin1Z = this._basis.zZ; + j.lin2X = this._basis.zX; + j.lin2Y = this._basis.zY; + j.lin2Z = this._basis.zZ; + j.ang1X = this._relativeAnchor1Y * this._basis.zZ - this._relativeAnchor1Z * this._basis.zY; + j.ang1Y = this._relativeAnchor1Z * this._basis.zX - this._relativeAnchor1X * this._basis.zZ; + j.ang1Z = this._relativeAnchor1X * this._basis.zY - this._relativeAnchor1Y * this._basis.zX; + j.ang2X = this._relativeAnchor2Y * this._basis.zZ - this._relativeAnchor2Z * this._basis.zY; + j.ang2Y = this._relativeAnchor2Z * this._basis.zX - this._relativeAnchor2X * this._basis.zZ; + j.ang2Z = this._relativeAnchor2X * this._basis.zY - this._relativeAnchor2Y * this._basis.zX; + let impulse2 = this._impulses[3]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = angRhsX; + row2.cfm = 0; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.ang1X = 1; + j.ang1Y = 0; + j.ang1Z = 0; + j.ang2X = 1; + j.ang2Y = 0; + j.ang2Z = 0; + let impulse3 = this._impulses[4]; + let row3 = info.rows[info.numRows++]; + let _this3 = row3.jacobian; + _this3.lin1X = 0; + _this3.lin1Y = 0; + _this3.lin1Z = 0; + _this3.lin2X = 0; + _this3.lin2Y = 0; + _this3.lin2Z = 0; + _this3.ang1X = 0; + _this3.ang1Y = 0; + _this3.ang1Z = 0; + _this3.ang2X = 0; + _this3.ang2Y = 0; + _this3.ang2Z = 0; + row3.rhs = 0; + row3.cfm = 0; + row3.minImpulse = 0; + row3.maxImpulse = 0; + row3.motorSpeed = 0; + row3.motorMaxImpulse = 0; + row3.impulse = null; + row3.impulse = impulse3; + row3.rhs = angRhsY; + row3.cfm = 0; + row3.minImpulse = -1e65536; + row3.maxImpulse = 1e65536; + j = row3.jacobian; + j.ang1X = 0; + j.ang1Y = 1; + j.ang1Z = 0; + j.ang2X = 0; + j.ang2Y = 1; + j.ang2Z = 0; + let impulse4 = this._impulses[5]; + let row4 = info.rows[info.numRows++]; + let _this4 = row4.jacobian; + _this4.lin1X = 0; + _this4.lin1Y = 0; + _this4.lin1Z = 0; + _this4.lin2X = 0; + _this4.lin2Y = 0; + _this4.lin2Z = 0; + _this4.ang1X = 0; + _this4.ang1Y = 0; + _this4.ang1Z = 0; + _this4.ang2X = 0; + _this4.ang2Y = 0; + _this4.ang2Z = 0; + row4.rhs = 0; + row4.cfm = 0; + row4.minImpulse = 0; + row4.maxImpulse = 0; + row4.motorSpeed = 0; + row4.motorMaxImpulse = 0; + row4.impulse = null; + row4.impulse = impulse4; + row4.rhs = angRhsZ; + row4.cfm = 0; + row4.minImpulse = -1e65536; + row4.maxImpulse = 1e65536; + j = row4.jacobian; + j.ang1X = 0; + j.ang1Y = 0; + j.ang1Z = 1; + j.ang2X = 0; + j.ang2Y = 0; + j.ang2Z = 1; + } + _syncAnchors() { + super._syncAnchors(); + let _this = this._basis; + let invM1 = _this.joint._b1._invMass; + let invM2 = _this.joint._b2._invMass; + let qX; + let qY; + let qZ; + let qW; + let idQX; + let idQY; + let idQZ; + let idQW; + let slerpQX; + let slerpQY; + let slerpQZ; + let slerpQW; + let slerpM00; + let slerpM01; + let slerpM02; + let slerpM10; + let slerpM11; + let slerpM12; + let slerpM20; + let slerpM21; + let slerpM22; + let newXX; + let newXY; + let newXZ; + let newYX; + let newYY; + let newYZ; + let newZX; + let newZY; + let newZZ; + let prevXX; + let prevXY; + let prevXZ; + let prevYX; + let prevYY; + let prevYZ; + let d = _this.joint._basisX1X * _this.joint._basisX2X + _this.joint._basisX1Y * _this.joint._basisX2Y + _this.joint._basisX1Z * _this.joint._basisX2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = _this.joint._basisX1X; + let y1 = _this.joint._basisX1Y; + let z1 = _this.joint._basisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + qX = vX; + qY = vY; + qZ = vZ; + qW = 0; + } else { + let cX; + let cY; + let cZ; + cX = _this.joint._basisX1Y * _this.joint._basisX2Z - _this.joint._basisX1Z * _this.joint._basisX2Y; + cY = _this.joint._basisX1Z * _this.joint._basisX2X - _this.joint._basisX1X * _this.joint._basisX2Z; + cZ = _this.joint._basisX1X * _this.joint._basisX2Y - _this.joint._basisX1Y * _this.joint._basisX2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + qX = cX; + qY = cY; + qZ = cZ; + qW = w; + } + idQX = 0; + idQY = 0; + idQZ = 0; + idQW = 1; + let q1X; + let q1Y; + let q1Z; + let q1W; + let q2X; + let q2Y; + let q2Z; + let q2W; + q1X = idQX; + q1Y = idQY; + q1Z = idQZ; + q1W = idQW; + q2X = qX; + q2Y = qY; + q2Z = qZ; + q2W = qW; + let d1 = q1X * q2X + q1Y * q2Y + q1Z * q2Z + q1W * q2W; + if(d1 < 0) { + d1 = -d1; + q2X = -q2X; + q2Y = -q2Y; + q2Z = -q2Z; + q2W = -q2W; + } + if(d1 > 0.999999) { + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = q2X - q1X; + dqY = q2Y - q1Y; + dqZ = q2Z - q1Z; + dqW = q2W - q1W; + q2X = q1X + dqX * (invM1 / (invM1 + invM2)); + q2Y = q1Y + dqY * (invM1 / (invM1 + invM2)); + q2Z = q1Z + dqZ * (invM1 / (invM1 + invM2)); + q2W = q1W + dqW * (invM1 / (invM1 + invM2)); + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + slerpQX = q2X * l; + slerpQY = q2Y * l; + slerpQZ = q2Z * l; + slerpQW = q2W * l; + } else { + let theta = invM1 / (invM1 + invM2) * Math.acos(d1); + q2X += q1X * -d1; + q2Y += q1Y * -d1; + q2Z += q1Z * -d1; + q2W += q1W * -d1; + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + q2X *= l; + q2Y *= l; + q2Z *= l; + q2W *= l; + let sin = Math.sin(theta); + let cos = Math.cos(theta); + q1X *= cos; + q1Y *= cos; + q1Z *= cos; + q1W *= cos; + slerpQX = q1X + q2X * sin; + slerpQY = q1Y + q2Y * sin; + slerpQZ = q1Z + q2Z * sin; + slerpQW = q1W + q2W * sin; + } + let x = slerpQX; + let y = slerpQY; + let z = slerpQZ; + let w = slerpQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + slerpM00 = 1 - yy - zz; + slerpM01 = xy - wz; + slerpM02 = xz + wy; + slerpM10 = xy + wz; + slerpM11 = 1 - xx - zz; + slerpM12 = yz - wx; + slerpM20 = xz - wy; + slerpM21 = yz + wx; + slerpM22 = 1 - xx - yy; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = slerpM00 * _this.joint._basisX1X + slerpM01 * _this.joint._basisX1Y + slerpM02 * _this.joint._basisX1Z; + __tmp__Y = slerpM10 * _this.joint._basisX1X + slerpM11 * _this.joint._basisX1Y + slerpM12 * _this.joint._basisX1Z; + __tmp__Z = slerpM20 * _this.joint._basisX1X + slerpM21 * _this.joint._basisX1Y + slerpM22 * _this.joint._basisX1Z; + newXX = __tmp__X; + newXY = __tmp__Y; + newXZ = __tmp__Z; + prevXX = _this.xX; + prevXY = _this.xY; + prevXZ = _this.xZ; + prevYX = _this.yX; + prevYY = _this.yY; + prevYZ = _this.yZ; + let d2 = prevXX * newXX + prevXY * newXY + prevXZ * newXZ; + if(d2 < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = prevXX; + let y1 = prevXY; + let z1 = prevXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + slerpQX = vX; + slerpQY = vY; + slerpQZ = vZ; + slerpQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = prevXY * newXZ - prevXZ * newXY; + cY = prevXZ * newXX - prevXX * newXZ; + cZ = prevXX * newXY - prevXY * newXX; + let w = Math.sqrt((1 + d2) * 0.5); + d2 = 0.5 / w; + cX *= d2; + cY *= d2; + cZ *= d2; + slerpQX = cX; + slerpQY = cY; + slerpQZ = cZ; + slerpQW = w; + } + let x1 = slerpQX; + let y1 = slerpQY; + let z1 = slerpQZ; + let w1 = slerpQW; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + slerpM00 = 1 - yy1 - zz1; + slerpM01 = xy1 - wz1; + slerpM02 = xz1 + wy1; + slerpM10 = xy1 + wz1; + slerpM11 = 1 - xx1 - zz1; + slerpM12 = yz1 - wx1; + slerpM20 = xz1 - wy1; + slerpM21 = yz1 + wx1; + slerpM22 = 1 - xx1 - yy1; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = slerpM00 * prevYX + slerpM01 * prevYY + slerpM02 * prevYZ; + __tmp__Y1 = slerpM10 * prevYX + slerpM11 * prevYY + slerpM12 * prevYZ; + __tmp__Z1 = slerpM20 * prevYX + slerpM21 * prevYY + slerpM22 * prevYZ; + newYX = __tmp__X1; + newYY = __tmp__Y1; + newYZ = __tmp__Z1; + newZX = newXY * newYZ - newXZ * newYY; + newZY = newXZ * newYX - newXX * newYZ; + newZZ = newXX * newYY - newXY * newYX; + if(newZX * newZX + newZY * newZY + newZZ * newZZ > 1e-6) { + let l = newZX * newZX + newZY * newZY + newZZ * newZZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + newZX *= l; + newZY *= l; + newZZ *= l; + } else { + let x1 = newXX; + let y1 = newXY; + let z1 = newXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + newZX = 0; + newZY = z1 * d; + newZZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + newZX = -z1 * d; + newZY = 0; + newZZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } + newYX = newZY * newXZ - newZZ * newXY; + newYY = newZZ * newXX - newZX * newXZ; + newYZ = newZX * newXY - newZY * newXX; + _this.xX = newXX; + _this.xY = newXY; + _this.xZ = newXZ; + _this.yX = newYX; + _this.yY = newYY; + _this.yZ = newYZ; + _this.zX = newZX; + _this.zY = newZY; + _this.zZ = newZZ; + let rot100; + let rot101; + let rot102; + let rot110; + let rot111; + let rot112; + let rot120; + let rot121; + let rot122; + let rot200; + let rot201; + let rot202; + let rot210; + let rot211; + let rot212; + let rot220; + let rot221; + let rot222; + rot100 = this._basisX1X; + rot101 = this._basisY1X; + rot102 = this._basisZ1X; + rot110 = this._basisX1Y; + rot111 = this._basisY1Y; + rot112 = this._basisZ1Y; + rot120 = this._basisX1Z; + rot121 = this._basisY1Z; + rot122 = this._basisZ1Z; + rot200 = this._basisX2X; + rot201 = this._basisY2X; + rot202 = this._basisZ2X; + rot210 = this._basisX2Y; + rot211 = this._basisY2Y; + rot212 = this._basisZ2Y; + rot220 = this._basisX2Z; + rot221 = this._basisY2Z; + rot222 = this._basisZ2Z; + let relRot00; + let relRot01; + let relRot02; + let relRot10; + let relRot11; + let relRot12; + let relRot20; + let relRot21; + let relRot22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot200 * rot100 + rot201 * rot101 + rot202 * rot102; + __tmp__01 = rot200 * rot110 + rot201 * rot111 + rot202 * rot112; + __tmp__02 = rot200 * rot120 + rot201 * rot121 + rot202 * rot122; + __tmp__10 = rot210 * rot100 + rot211 * rot101 + rot212 * rot102; + __tmp__11 = rot210 * rot110 + rot211 * rot111 + rot212 * rot112; + __tmp__12 = rot210 * rot120 + rot211 * rot121 + rot212 * rot122; + __tmp__20 = rot220 * rot100 + rot221 * rot101 + rot222 * rot102; + __tmp__21 = rot220 * rot110 + rot221 * rot111 + rot222 * rot112; + __tmp__22 = rot220 * rot120 + rot221 * rot121 + rot222 * rot122; + relRot00 = __tmp__00; + relRot01 = __tmp__01; + relRot02 = __tmp__02; + relRot10 = __tmp__10; + relRot11 = __tmp__11; + relRot12 = __tmp__12; + relRot20 = __tmp__20; + relRot21 = __tmp__21; + relRot22 = __tmp__22; + let relQX; + let relQY; + let relQZ; + let relQW; + let e00 = relRot00; + let e11 = relRot11; + let e22 = relRot22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + relQW = 0.5 * s; + s = 0.5 / s; + relQX = (relRot21 - relRot12) * s; + relQY = (relRot02 - relRot20) * s; + relQZ = (relRot10 - relRot01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + relQX = 0.5 * s; + s = 0.5 / s; + relQY = (relRot01 + relRot10) * s; + relQZ = (relRot02 + relRot20) * s; + relQW = (relRot21 - relRot12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + relQZ = 0.5 * s; + s = 0.5 / s; + relQX = (relRot02 + relRot20) * s; + relQY = (relRot12 + relRot21) * s; + relQW = (relRot10 - relRot01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + relQY = 0.5 * s; + s = 0.5 / s; + relQX = (relRot01 + relRot10) * s; + relQZ = (relRot12 + relRot21) * s; + relQW = (relRot02 - relRot20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + relQZ = 0.5 * s; + s = 0.5 / s; + relQX = (relRot02 + relRot20) * s; + relQY = (relRot12 + relRot21) * s; + relQW = (relRot10 - relRot01) * s; + } + let cosHalfTheta = relQW; + let theta = (cosHalfTheta <= -1 ? 3.14159265358979 : cosHalfTheta >= 1 ? 0 : Math.acos(cosHalfTheta)) * 2; + this.angularErrorX = relQX; + this.angularErrorY = relQY; + this.angularErrorZ = relQZ; + let l = this.angularErrorX * this.angularErrorX + this.angularErrorY * this.angularErrorY + this.angularErrorZ * this.angularErrorZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this.angularErrorX *= l; + this.angularErrorY *= l; + this.angularErrorZ *= l; + this.angularErrorX *= theta; + this.angularErrorY *= theta; + this.angularErrorZ *= theta; + let anchorDiffX; + let anchorDiffY; + let anchorDiffZ; + anchorDiffX = this._anchor2X - this._anchor1X; + anchorDiffY = this._anchor2Y - this._anchor1Y; + anchorDiffZ = this._anchor2Z - this._anchor1Z; + this.translation = anchorDiffX * this._basis.xX + anchorDiffY * this._basis.xY + anchorDiffZ * this._basis.xZ; + this.linearErrorY = anchorDiffX * this._basis.yX + anchorDiffY * this._basis.yY + anchorDiffZ * this._basis.yZ; + this.linearErrorZ = anchorDiffX * this._basis.zX + anchorDiffY * this._basis.zY + anchorDiffZ * this._basis.zZ; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._basisX2X; + v.y = this._basisX2Y; + v.z = this._basisX2Z; + return v; + } + getAxis1To(axis) { + axis.x = this._basisX1X; + axis.y = this._basisX1Y; + axis.z = this._basisX1Z; + } + getAxis2To(axis) { + axis.x = this._basisX2X; + axis.y = this._basisX2Y; + axis.z = this._basisX2Z; + } + getLocalAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX1X; + v.y = this._localBasisX1Y; + v.z = this._localBasisX1Z; + return v; + } + getLocalAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX2X; + v.y = this._localBasisX2Y; + v.z = this._localBasisX2Z; + return v; + } + getLocalAxis1To(axis) { + axis.x = this._localBasisX1X; + axis.y = this._localBasisX1Y; + axis.z = this._localBasisX1Z; + } + getLocalAxis2To(axis) { + axis.x = this._localBasisX2X; + axis.y = this._localBasisX2Y; + axis.z = this._localBasisX2Z; + } + getSpringDamper() { + return this._sd; + } + getLimitMotor() { + return this._lm; + } + getTranslation() { + return this.translation; + } +} +oimo.dynamics.constraint.joint.PrismaticJointConfig = class oimo_dynamics_constraint_joint_PrismaticJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localAxis1 = new oimo.common.Vec3(1,0,0); + this.localAxis2 = new oimo.common.Vec3(1,0,0); + this.limitMotor = new oimo.dynamics.constraint.joint.TranslationalLimitMotor(); + this.springDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + } + init(rigidBody1,rigidBody2,worldAnchor,worldAxis) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let localVector = this.localAxis1; + let vX; + let vY; + let vZ; + vX = worldAxis.x; + vY = worldAxis.y; + vZ = worldAxis.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rigidBody1._transform._rotation00 * vX + rigidBody1._transform._rotation10 * vY + rigidBody1._transform._rotation20 * vZ; + __tmp__Y = rigidBody1._transform._rotation01 * vX + rigidBody1._transform._rotation11 * vY + rigidBody1._transform._rotation21 * vZ; + __tmp__Z = rigidBody1._transform._rotation02 * vX + rigidBody1._transform._rotation12 * vY + rigidBody1._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + let localVector1 = this.localAxis2; + let vX1; + let vY1; + let vZ1; + vX1 = worldAxis.x; + vY1 = worldAxis.y; + vZ1 = worldAxis.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = rigidBody2._transform._rotation00 * vX1 + rigidBody2._transform._rotation10 * vY1 + rigidBody2._transform._rotation20 * vZ1; + __tmp__Y1 = rigidBody2._transform._rotation01 * vX1 + rigidBody2._transform._rotation11 * vY1 + rigidBody2._transform._rotation21 * vZ1; + __tmp__Z1 = rigidBody2._transform._rotation02 * vX1 + rigidBody2._transform._rotation12 * vY1 + rigidBody2._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localVector1.x = vX1; + localVector1.y = vY1; + localVector1.z = vZ1; + return this; + } +} +oimo.dynamics.constraint.joint.RagdollJoint = class oimo_dynamics_constraint_joint_RagdollJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,oimo.dynamics.constraint.joint.JointType.RAGDOLL); + let v = config.localTwistAxis1; + this._localBasisX1X = v.x; + this._localBasisX1Y = v.y; + this._localBasisX1Z = v.z; + let v1 = config.localSwingAxis1; + this._localBasisY1X = v1.x; + this._localBasisY1Y = v1.y; + this._localBasisY1Z = v1.z; + let v2 = config.localTwistAxis2; + this._localBasisX2X = v2.x; + this._localBasisX2Y = v2.y; + this._localBasisX2Z = v2.z; + this.buildLocalBasesFromXY1X2(); + this._twistSd = config.twistSpringDamper.clone(); + this._twistLm = config.twistLimitMotor.clone(); + this._swingSd = config.swingSpringDamper.clone(); + this._maxSwingAngle1 = config.maxSwingAngle1; + this._maxSwingAngle2 = config.maxSwingAngle2; + if(this._maxSwingAngle1 < oimo.common.Setting.minRagdollMaxSwingAngle) { + this._maxSwingAngle1 = oimo.common.Setting.minRagdollMaxSwingAngle; + } + if(this._maxSwingAngle2 < oimo.common.Setting.minRagdollMaxSwingAngle) { + this._maxSwingAngle2 = oimo.common.Setting.minRagdollMaxSwingAngle; + } + this.dummySwingLm = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + this.dummySwingLm.lowerLimit = -1; + this.dummySwingLm.upperLimit = 0; + this._swingAngle = 0; + this._twistAngle = 0; + this.swingError = 0; + this.swingAxisX = 0; + this.swingAxisY = 0; + this.swingAxisZ = 0; + this.twistAxisX = 0; + this.twistAxisY = 0; + this.twistAxisZ = 0; + } + getInfo(info,timeStep,isPositionPart) { + let erp = this.getErp(timeStep,isPositionPart); + let linearRhsX; + let linearRhsY; + let linearRhsZ; + linearRhsX = this.linearErrorX * erp; + linearRhsY = this.linearErrorY * erp; + linearRhsZ = this.linearErrorZ * erp; + let crossR100; + let crossR101; + let crossR102; + let crossR110; + let crossR111; + let crossR112; + let crossR120; + let crossR121; + let crossR122; + let crossR200; + let crossR201; + let crossR202; + let crossR210; + let crossR211; + let crossR212; + let crossR220; + let crossR221; + let crossR222; + crossR100 = 0; + crossR101 = -this._relativeAnchor1Z; + crossR102 = this._relativeAnchor1Y; + crossR110 = this._relativeAnchor1Z; + crossR111 = 0; + crossR112 = -this._relativeAnchor1X; + crossR120 = -this._relativeAnchor1Y; + crossR121 = this._relativeAnchor1X; + crossR122 = 0; + crossR200 = 0; + crossR201 = -this._relativeAnchor2Z; + crossR202 = this._relativeAnchor2Y; + crossR210 = this._relativeAnchor2Z; + crossR211 = 0; + crossR212 = -this._relativeAnchor2X; + crossR220 = -this._relativeAnchor2Y; + crossR221 = this._relativeAnchor2X; + crossR222 = 0; + crossR100 = -crossR100; + crossR101 = -crossR101; + crossR102 = -crossR102; + crossR110 = -crossR110; + crossR111 = -crossR111; + crossR112 = -crossR112; + crossR120 = -crossR120; + crossR121 = -crossR121; + crossR122 = -crossR122; + crossR200 = -crossR200; + crossR201 = -crossR201; + crossR202 = -crossR202; + crossR210 = -crossR210; + crossR211 = -crossR211; + crossR212 = -crossR212; + crossR220 = -crossR220; + crossR221 = -crossR221; + crossR222 = -crossR222; + let swingMass = this.computeEffectiveInertiaMoment(this.swingAxisX,this.swingAxisY,this.swingAxisZ); + let twistMass = this.computeEffectiveInertiaMoment(this._basisX2X,this._basisX2Y,this._basisX2Z); + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linearRhsX; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + let j = row.jacobian; + j.lin1X = 1; + j.lin1Y = 0; + j.lin1Z = 0; + j.lin2X = 1; + j.lin2Y = 0; + j.lin2Z = 0; + j.ang1X = crossR100; + j.ang1Y = crossR101; + j.ang1Z = crossR102; + j.ang2X = crossR200; + j.ang2Y = crossR201; + j.ang2Z = crossR202; + let impulse1 = this._impulses[1]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linearRhsY; + row1.cfm = 0; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = 0; + j.lin1Y = 1; + j.lin1Z = 0; + j.lin2X = 0; + j.lin2Y = 1; + j.lin2Z = 0; + j.ang1X = crossR110; + j.ang1Y = crossR111; + j.ang1Z = crossR112; + j.ang2X = crossR210; + j.ang2Y = crossR211; + j.ang2Z = crossR212; + let impulse2 = this._impulses[2]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = linearRhsZ; + row2.cfm = 0; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.lin1X = 0; + j.lin1Y = 0; + j.lin1Z = 1; + j.lin2X = 0; + j.lin2Y = 0; + j.lin2Z = 1; + j.ang1X = crossR120; + j.ang1Y = crossR121; + j.ang1Z = crossR122; + j.ang2X = crossR220; + j.ang2Y = crossR221; + j.ang2Z = crossR222; + if(this.swingError > 0 && (this._swingSd.frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[3]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this.swingError,this.dummySwingLm,swingMass,this._swingSd,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this.swingAxisX; + j.ang1Y = this.swingAxisY; + j.ang1Z = this.swingAxisZ; + j.ang2X = this.swingAxisX; + j.ang2Y = this.swingAxisY; + j.ang2Z = this.swingAxisZ; + } + if(this._twistSd.frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[4]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._twistAngle,this._twistLm,twistMass,this._twistSd,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this.twistAxisX; + j.ang1Y = this.twistAxisY; + j.ang1Z = this.twistAxisZ; + j.ang2X = this.twistAxisX; + j.ang2Y = this.twistAxisY; + j.ang2Z = this.twistAxisZ; + } + } + _syncAnchors() { + super._syncAnchors(); + let axis1X; + let axis1Y; + let axis1Z; + let axis2X; + let axis2Y; + let axis2Z; + axis1X = this._basisX1X; + axis1Y = this._basisX1Y; + axis1Z = this._basisX1Z; + axis2X = this._basisX2X; + axis2Y = this._basisX2Y; + axis2Z = this._basisX2Z; + let basis1Mat00; + let basis1Mat01; + let basis1Mat02; + let basis1Mat10; + let basis1Mat11; + let basis1Mat12; + let basis1Mat20; + let basis1Mat21; + let basis1Mat22; + basis1Mat00 = this._basisX1X; + basis1Mat01 = this._basisY1X; + basis1Mat02 = this._basisZ1X; + basis1Mat10 = this._basisX1Y; + basis1Mat11 = this._basisY1Y; + basis1Mat12 = this._basisZ1Y; + basis1Mat20 = this._basisX1Z; + basis1Mat21 = this._basisY1Z; + basis1Mat22 = this._basisZ1Z; + let swingQX; + let swingQY; + let swingQZ; + let swingQW; + let swingM00; + let swingM01; + let swingM02; + let swingM10; + let swingM11; + let swingM12; + let swingM20; + let swingM21; + let swingM22; + let swingVX; + let swingVY; + let swingVZ; + let d = axis1X * axis2X + axis1Y * axis2Y + axis1Z * axis2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = axis1X; + let y1 = axis1Y; + let z1 = axis1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + swingQX = vX; + swingQY = vY; + swingQZ = vZ; + swingQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = axis1Y * axis2Z - axis1Z * axis2Y; + cY = axis1Z * axis2X - axis1X * axis2Z; + cZ = axis1X * axis2Y - axis1Y * axis2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + swingQX = cX; + swingQY = cY; + swingQZ = cZ; + swingQW = w; + } + let x = swingQX; + let y = swingQY; + let z = swingQZ; + let w = swingQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + swingM00 = 1 - yy - zz; + swingM01 = xy - wz; + swingM02 = xz + wy; + swingM10 = xy + wz; + swingM11 = 1 - xx - zz; + swingM12 = yz - wx; + swingM20 = xz - wy; + swingM21 = yz + wx; + swingM22 = 1 - xx - yy; + this._swingAngle = (swingQW <= -1 ? 3.14159265358979 : swingQW >= 1 ? 0 : Math.acos(swingQW)) * 2; + swingVX = swingQX; + swingVY = swingQY; + swingVZ = swingQZ; + let basisY2In1X; + let basisY2In1Y; + let basisY2In1Z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = swingM00 * this._basisY2X + swingM10 * this._basisY2Y + swingM20 * this._basisY2Z; + __tmp__Y = swingM01 * this._basisY2X + swingM11 * this._basisY2Y + swingM21 * this._basisY2Z; + __tmp__Z = swingM02 * this._basisY2X + swingM12 * this._basisY2Y + swingM22 * this._basisY2Z; + basisY2In1X = __tmp__X; + basisY2In1Y = __tmp__Y; + basisY2In1Z = __tmp__Z; + this._twistAngle = Math.atan2(this._basisZ1X * basisY2In1X + this._basisZ1Y * basisY2In1Y + this._basisZ1Z * basisY2In1Z,this._basisY1X * basisY2In1X + this._basisY1Y * basisY2In1Y + this._basisY1Z * basisY2In1Z); + this.twistAxisX = this._basisX1X + this._basisX2X; + this.twistAxisY = this._basisX1Y + this._basisX2Y; + this.twistAxisZ = this._basisX1Z + this._basisX2Z; + let l = this.twistAxisX * this.twistAxisX + this.twistAxisY * this.twistAxisY + this.twistAxisZ * this.twistAxisZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this.twistAxisX *= l; + this.twistAxisY *= l; + this.twistAxisZ *= l; + let invLen = Math.sqrt(swingVX * swingVX + swingVY * swingVY + swingVZ * swingVZ); + if(invLen > 0) { + invLen = 1 / invLen; + } + swingVX *= invLen * this._swingAngle; + swingVY *= invLen * this._swingAngle; + swingVZ *= invLen * this._swingAngle; + + let __tmp__Y1; + let __tmp__Z1; + + __tmp__Y1 = basis1Mat01 * swingVX + basis1Mat11 * swingVY + basis1Mat21 * swingVZ; + __tmp__Z1 = basis1Mat02 * swingVX + basis1Mat12 * swingVY + basis1Mat22 * swingVZ; + + swingVY = __tmp__Y1; + swingVZ = __tmp__Z1; + let x1 = swingVY; + let y1 = swingVZ; + let a = this._maxSwingAngle1; + let b = this._maxSwingAngle2; + let invA2 = 1 / (a * a); + let invB2 = 1 / (b * b); + let w1 = x1 * x1 * invA2 + y1 * y1 * invB2; + if(w1 == 0) { + this.swingAxisX = 0; + this.swingAxisY = 0; + this.swingAxisZ = 0; + this.swingError = 0; + } else { + let t = Math.sqrt(1 / w1); + let x0 = x1 * t; + let y0 = y1 * t; + let nx = x0 * invA2; + let ny = y0 * invB2; + invLen = 1 / Math.sqrt(nx * nx + ny * ny); + nx *= invLen; + ny *= invLen; + let depth = (x1 - x0) * nx + (y1 - y0) * ny; + if(depth > 0) { + this.swingError = depth; + this.swingAxisX = 0; + this.swingAxisY = nx; + this.swingAxisZ = ny; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = basis1Mat00 * this.swingAxisX + basis1Mat01 * this.swingAxisY + basis1Mat02 * this.swingAxisZ; + __tmp__Y = basis1Mat10 * this.swingAxisX + basis1Mat11 * this.swingAxisY + basis1Mat12 * this.swingAxisZ; + __tmp__Z = basis1Mat20 * this.swingAxisX + basis1Mat21 * this.swingAxisY + basis1Mat22 * this.swingAxisZ; + this.swingAxisX = __tmp__X; + this.swingAxisY = __tmp__Y; + this.swingAxisZ = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = swingM00 * this.swingAxisX + swingM01 * this.swingAxisY + swingM02 * this.swingAxisZ; + __tmp__Y1 = swingM10 * this.swingAxisX + swingM11 * this.swingAxisY + swingM12 * this.swingAxisZ; + __tmp__Z1 = swingM20 * this.swingAxisX + swingM21 * this.swingAxisY + swingM22 * this.swingAxisZ; + this.swingAxisX = __tmp__X1; + this.swingAxisY = __tmp__Y1; + this.swingAxisZ = __tmp__Z1; + } else { + this.swingError = 0; + } + } + this.linearErrorX = this._anchor2X - this._anchor1X; + this.linearErrorY = this._anchor2Y - this._anchor1Y; + this.linearErrorZ = this._anchor2Z - this._anchor1Z; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._basisX2X; + v.y = this._basisX2Y; + v.z = this._basisX2Z; + return v; + } + getAxis1To(axis) { + axis.x = this._basisX1X; + axis.y = this._basisX1Y; + axis.z = this._basisX1Z; + } + getAxis2To(axis) { + axis.x = this._basisX2X; + axis.y = this._basisX2Y; + axis.z = this._basisX2Z; + } + getLocalAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX1X; + v.y = this._localBasisX1Y; + v.z = this._localBasisX1Z; + return v; + } + getLocalAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX2X; + v.y = this._localBasisX2Y; + v.z = this._localBasisX2Z; + return v; + } + getLocalAxis1To(axis) { + axis.x = this._localBasisX1X; + axis.y = this._localBasisX1Y; + axis.z = this._localBasisX1Z; + } + getLocalAxis2To(axis) { + axis.x = this._localBasisX2X; + axis.y = this._localBasisX2Y; + axis.z = this._localBasisX2Z; + } + getTwistSpringDamper() { + return this._twistSd; + } + getTwistLimitMotor() { + return this._twistLm; + } + getSwingSpringDamper() { + return this._swingSd; + } + getSwingAxis() { + let v = new oimo.common.Vec3(); + v.x = this.swingAxisX; + v.y = this.swingAxisY; + v.z = this.swingAxisZ; + return v; + } + getSwingAxisTo(axis) { + axis.x = this.swingAxisX; + axis.y = this.swingAxisY; + axis.z = this.swingAxisZ; + } + getSwingAngle() { + return this._swingAngle; + } + getTwistAngle() { + return this._twistAngle; + } +} +oimo.dynamics.constraint.joint.RagdollJointConfig = class oimo_dynamics_constraint_joint_RagdollJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localTwistAxis1 = new oimo.common.Vec3(1,0,0); + this.localTwistAxis2 = new oimo.common.Vec3(1,0,0); + this.localSwingAxis1 = new oimo.common.Vec3(0,1,0); + this.twistSpringDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + this.swingSpringDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + this.twistLimitMotor = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + this.maxSwingAngle1 = 3.14159265358979; + this.maxSwingAngle2 = 3.14159265358979; + } + init(rigidBody1,rigidBody2,worldAnchor,worldTwistAxis,worldSwingAxis) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let localVector = this.localTwistAxis1; + let vX; + let vY; + let vZ; + vX = worldTwistAxis.x; + vY = worldTwistAxis.y; + vZ = worldTwistAxis.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rigidBody1._transform._rotation00 * vX + rigidBody1._transform._rotation10 * vY + rigidBody1._transform._rotation20 * vZ; + __tmp__Y = rigidBody1._transform._rotation01 * vX + rigidBody1._transform._rotation11 * vY + rigidBody1._transform._rotation21 * vZ; + __tmp__Z = rigidBody1._transform._rotation02 * vX + rigidBody1._transform._rotation12 * vY + rigidBody1._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + let localVector1 = this.localTwistAxis2; + let vX1; + let vY1; + let vZ1; + vX1 = worldTwistAxis.x; + vY1 = worldTwistAxis.y; + vZ1 = worldTwistAxis.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = rigidBody2._transform._rotation00 * vX1 + rigidBody2._transform._rotation10 * vY1 + rigidBody2._transform._rotation20 * vZ1; + __tmp__Y1 = rigidBody2._transform._rotation01 * vX1 + rigidBody2._transform._rotation11 * vY1 + rigidBody2._transform._rotation21 * vZ1; + __tmp__Z1 = rigidBody2._transform._rotation02 * vX1 + rigidBody2._transform._rotation12 * vY1 + rigidBody2._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localVector1.x = vX1; + localVector1.y = vY1; + localVector1.z = vZ1; + let localVector2 = this.localSwingAxis1; + let vX2; + let vY2; + let vZ2; + vX2 = worldSwingAxis.x; + vY2 = worldSwingAxis.y; + vZ2 = worldSwingAxis.z; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = rigidBody1._transform._rotation00 * vX2 + rigidBody1._transform._rotation10 * vY2 + rigidBody1._transform._rotation20 * vZ2; + __tmp__Y2 = rigidBody1._transform._rotation01 * vX2 + rigidBody1._transform._rotation11 * vY2 + rigidBody1._transform._rotation21 * vZ2; + __tmp__Z2 = rigidBody1._transform._rotation02 * vX2 + rigidBody1._transform._rotation12 * vY2 + rigidBody1._transform._rotation22 * vZ2; + vX2 = __tmp__X2; + vY2 = __tmp__Y2; + vZ2 = __tmp__Z2; + localVector2.x = vX2; + localVector2.y = vY2; + localVector2.z = vZ2; + return this; + } +} +oimo.dynamics.constraint.joint.RevoluteJoint = class oimo_dynamics_constraint_joint_RevoluteJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,1); + let v = config.localAxis1; + this._localBasisX1X = v.x; + this._localBasisX1Y = v.y; + this._localBasisX1Z = v.z; + let v1 = config.localAxis2; + this._localBasisX2X = v1.x; + this._localBasisX2Y = v1.y; + this._localBasisX2Z = v1.z; + this.buildLocalBasesFromX(); + this.angle = 0; + this.angularErrorY = 0; + this.angularErrorZ = 0; + this._basis = new oimo.dynamics.constraint.joint.BasisTracker(this); + this._sd = config.springDamper.clone(); + this._lm = config.limitMotor.clone(); + } + getInfo(info,timeStep,isPositionPart) { + let erp = this.getErp(timeStep,isPositionPart); + let linearRhsX; + let linearRhsY; + let linearRhsZ; + linearRhsX = this.linearErrorX * erp; + linearRhsY = this.linearErrorY * erp; + linearRhsZ = this.linearErrorZ * erp; + let angRhsY = this.angularErrorY * erp; + let angRhsZ = this.angularErrorZ * erp; + let crossR100; + let crossR101; + let crossR102; + let crossR110; + let crossR111; + let crossR112; + let crossR120; + let crossR121; + let crossR122; + let crossR200; + let crossR201; + let crossR202; + let crossR210; + let crossR211; + let crossR212; + let crossR220; + let crossR221; + let crossR222; + crossR100 = 0; + crossR101 = -this._relativeAnchor1Z; + crossR102 = this._relativeAnchor1Y; + crossR110 = this._relativeAnchor1Z; + crossR111 = 0; + crossR112 = -this._relativeAnchor1X; + crossR120 = -this._relativeAnchor1Y; + crossR121 = this._relativeAnchor1X; + crossR122 = 0; + crossR200 = 0; + crossR201 = -this._relativeAnchor2Z; + crossR202 = this._relativeAnchor2Y; + crossR210 = this._relativeAnchor2Z; + crossR211 = 0; + crossR212 = -this._relativeAnchor2X; + crossR220 = -this._relativeAnchor2Y; + crossR221 = this._relativeAnchor2X; + crossR222 = 0; + crossR100 = -crossR100; + crossR101 = -crossR101; + crossR102 = -crossR102; + crossR110 = -crossR110; + crossR111 = -crossR111; + crossR112 = -crossR112; + crossR120 = -crossR120; + crossR121 = -crossR121; + crossR122 = -crossR122; + crossR200 = -crossR200; + crossR201 = -crossR201; + crossR202 = -crossR202; + crossR210 = -crossR210; + crossR211 = -crossR211; + crossR212 = -crossR212; + crossR220 = -crossR220; + crossR221 = -crossR221; + crossR222 = -crossR222; + let motorMass = this.computeEffectiveInertiaMoment(this._basis.xX,this._basis.xY,this._basis.xZ); + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linearRhsX; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + let j = row.jacobian; + j.lin1X = 1; + j.lin1Y = 0; + j.lin1Z = 0; + j.lin2X = 1; + j.lin2Y = 0; + j.lin2Z = 0; + j.ang1X = crossR100; + j.ang1Y = crossR101; + j.ang1Z = crossR102; + j.ang2X = crossR200; + j.ang2Y = crossR201; + j.ang2Z = crossR202; + let impulse1 = this._impulses[1]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linearRhsY; + row1.cfm = 0; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = 0; + j.lin1Y = 1; + j.lin1Z = 0; + j.lin2X = 0; + j.lin2Y = 1; + j.lin2Z = 0; + j.ang1X = crossR110; + j.ang1Y = crossR111; + j.ang1Z = crossR112; + j.ang2X = crossR210; + j.ang2Y = crossR211; + j.ang2Z = crossR212; + let impulse2 = this._impulses[2]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = linearRhsZ; + row2.cfm = 0; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.lin1X = 0; + j.lin1Y = 0; + j.lin1Z = 1; + j.lin2X = 0; + j.lin2Y = 0; + j.lin2Z = 1; + j.ang1X = crossR120; + j.ang1Y = crossR121; + j.ang1Z = crossR122; + j.ang2X = crossR220; + j.ang2Y = crossR221; + j.ang2Z = crossR222; + if(this._sd.frequency <= 0 || !isPositionPart) { + let impulse = this._impulses[3]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this.angle,this._lm,motorMass,this._sd,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._basis.xX; + j.ang1Y = this._basis.xY; + j.ang1Z = this._basis.xZ; + j.ang2X = this._basis.xX; + j.ang2Y = this._basis.xY; + j.ang2Z = this._basis.xZ; + } + let impulse3 = this._impulses[4]; + let row3 = info.rows[info.numRows++]; + let _this3 = row3.jacobian; + _this3.lin1X = 0; + _this3.lin1Y = 0; + _this3.lin1Z = 0; + _this3.lin2X = 0; + _this3.lin2Y = 0; + _this3.lin2Z = 0; + _this3.ang1X = 0; + _this3.ang1Y = 0; + _this3.ang1Z = 0; + _this3.ang2X = 0; + _this3.ang2Y = 0; + _this3.ang2Z = 0; + row3.rhs = 0; + row3.cfm = 0; + row3.minImpulse = 0; + row3.maxImpulse = 0; + row3.motorSpeed = 0; + row3.motorMaxImpulse = 0; + row3.impulse = null; + row3.impulse = impulse3; + row3.rhs = angRhsY; + row3.cfm = 0; + row3.minImpulse = -1e65536; + row3.maxImpulse = 1e65536; + j = row3.jacobian; + j.ang1X = this._basis.yX; + j.ang1Y = this._basis.yY; + j.ang1Z = this._basis.yZ; + j.ang2X = this._basis.yX; + j.ang2Y = this._basis.yY; + j.ang2Z = this._basis.yZ; + let impulse4 = this._impulses[5]; + let row4 = info.rows[info.numRows++]; + let _this4 = row4.jacobian; + _this4.lin1X = 0; + _this4.lin1Y = 0; + _this4.lin1Z = 0; + _this4.lin2X = 0; + _this4.lin2Y = 0; + _this4.lin2Z = 0; + _this4.ang1X = 0; + _this4.ang1Y = 0; + _this4.ang1Z = 0; + _this4.ang2X = 0; + _this4.ang2Y = 0; + _this4.ang2Z = 0; + row4.rhs = 0; + row4.cfm = 0; + row4.minImpulse = 0; + row4.maxImpulse = 0; + row4.motorSpeed = 0; + row4.motorMaxImpulse = 0; + row4.impulse = null; + row4.impulse = impulse4; + row4.rhs = angRhsZ; + row4.cfm = 0; + row4.minImpulse = -1e65536; + row4.maxImpulse = 1e65536; + j = row4.jacobian; + j.ang1X = this._basis.zX; + j.ang1Y = this._basis.zY; + j.ang1Z = this._basis.zZ; + j.ang2X = this._basis.zX; + j.ang2Y = this._basis.zY; + j.ang2Z = this._basis.zZ; + } + _syncAnchors() { + super._syncAnchors(); + let _this = this._basis; + let invM1 = _this.joint._b1._invMass; + let invM2 = _this.joint._b2._invMass; + let qX; + let qY; + let qZ; + let qW; + let idQX; + let idQY; + let idQZ; + let idQW; + let slerpQX; + let slerpQY; + let slerpQZ; + let slerpQW; + let slerpM00; + let slerpM01; + let slerpM02; + let slerpM10; + let slerpM11; + let slerpM12; + let slerpM20; + let slerpM21; + let slerpM22; + let newXX; + let newXY; + let newXZ; + let newYX; + let newYY; + let newYZ; + let newZX; + let newZY; + let newZZ; + let prevXX; + let prevXY; + let prevXZ; + let prevYX; + let prevYY; + let prevYZ; + let d = _this.joint._basisX1X * _this.joint._basisX2X + _this.joint._basisX1Y * _this.joint._basisX2Y + _this.joint._basisX1Z * _this.joint._basisX2Z; + if(d < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = _this.joint._basisX1X; + let y1 = _this.joint._basisX1Y; + let z1 = _this.joint._basisX1Z; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + qX = vX; + qY = vY; + qZ = vZ; + qW = 0; + } else { + let cX; + let cY; + let cZ; + cX = _this.joint._basisX1Y * _this.joint._basisX2Z - _this.joint._basisX1Z * _this.joint._basisX2Y; + cY = _this.joint._basisX1Z * _this.joint._basisX2X - _this.joint._basisX1X * _this.joint._basisX2Z; + cZ = _this.joint._basisX1X * _this.joint._basisX2Y - _this.joint._basisX1Y * _this.joint._basisX2X; + let w = Math.sqrt((1 + d) * 0.5); + d = 0.5 / w; + cX *= d; + cY *= d; + cZ *= d; + qX = cX; + qY = cY; + qZ = cZ; + qW = w; + } + idQX = 0; + idQY = 0; + idQZ = 0; + idQW = 1; + let q1X; + let q1Y; + let q1Z; + let q1W; + let q2X; + let q2Y; + let q2Z; + let q2W; + q1X = idQX; + q1Y = idQY; + q1Z = idQZ; + q1W = idQW; + q2X = qX; + q2Y = qY; + q2Z = qZ; + q2W = qW; + let d1 = q1X * q2X + q1Y * q2Y + q1Z * q2Z + q1W * q2W; + if(d1 < 0) { + d1 = -d1; + q2X = -q2X; + q2Y = -q2Y; + q2Z = -q2Z; + q2W = -q2W; + } + if(d1 > 0.999999) { + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = q2X - q1X; + dqY = q2Y - q1Y; + dqZ = q2Z - q1Z; + dqW = q2W - q1W; + q2X = q1X + dqX * (invM1 / (invM1 + invM2)); + q2Y = q1Y + dqY * (invM1 / (invM1 + invM2)); + q2Z = q1Z + dqZ * (invM1 / (invM1 + invM2)); + q2W = q1W + dqW * (invM1 / (invM1 + invM2)); + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + slerpQX = q2X * l; + slerpQY = q2Y * l; + slerpQZ = q2Z * l; + slerpQW = q2W * l; + } else { + let theta = invM1 / (invM1 + invM2) * Math.acos(d1); + q2X += q1X * -d1; + q2Y += q1Y * -d1; + q2Z += q1Z * -d1; + q2W += q1W * -d1; + let l = q2X * q2X + q2Y * q2Y + q2Z * q2Z + q2W * q2W; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + q2X *= l; + q2Y *= l; + q2Z *= l; + q2W *= l; + let sin = Math.sin(theta); + let cos = Math.cos(theta); + q1X *= cos; + q1Y *= cos; + q1Z *= cos; + q1W *= cos; + slerpQX = q1X + q2X * sin; + slerpQY = q1Y + q2Y * sin; + slerpQZ = q1Z + q2Z * sin; + slerpQW = q1W + q2W * sin; + } + let x = slerpQX; + let y = slerpQY; + let z = slerpQZ; + let w = slerpQW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + slerpM00 = 1 - yy - zz; + slerpM01 = xy - wz; + slerpM02 = xz + wy; + slerpM10 = xy + wz; + slerpM11 = 1 - xx - zz; + slerpM12 = yz - wx; + slerpM20 = xz - wy; + slerpM21 = yz + wx; + slerpM22 = 1 - xx - yy; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = slerpM00 * _this.joint._basisX1X + slerpM01 * _this.joint._basisX1Y + slerpM02 * _this.joint._basisX1Z; + __tmp__Y = slerpM10 * _this.joint._basisX1X + slerpM11 * _this.joint._basisX1Y + slerpM12 * _this.joint._basisX1Z; + __tmp__Z = slerpM20 * _this.joint._basisX1X + slerpM21 * _this.joint._basisX1Y + slerpM22 * _this.joint._basisX1Z; + newXX = __tmp__X; + newXY = __tmp__Y; + newXZ = __tmp__Z; + prevXX = _this.xX; + prevXY = _this.xY; + prevXZ = _this.xZ; + prevYX = _this.yX; + prevYY = _this.yY; + prevYZ = _this.yZ; + let d2 = prevXX * newXX + prevXY * newXY + prevXZ * newXZ; + if(d2 < -0.999999999) { + let vX; + let vY; + let vZ; + let x1 = prevXX; + let y1 = prevXY; + let z1 = prevXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + vX = 0; + vY = z1 * d; + vZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + vX = -z1 * d; + vY = 0; + vZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + vX = y1 * d; + vY = -x1 * d; + vZ = 0; + } + slerpQX = vX; + slerpQY = vY; + slerpQZ = vZ; + slerpQW = 0; + } else { + let cX; + let cY; + let cZ; + cX = prevXY * newXZ - prevXZ * newXY; + cY = prevXZ * newXX - prevXX * newXZ; + cZ = prevXX * newXY - prevXY * newXX; + let w = Math.sqrt((1 + d2) * 0.5); + d2 = 0.5 / w; + cX *= d2; + cY *= d2; + cZ *= d2; + slerpQX = cX; + slerpQY = cY; + slerpQZ = cZ; + slerpQW = w; + } + let x1 = slerpQX; + let y1 = slerpQY; + let z1 = slerpQZ; + let w1 = slerpQW; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + slerpM00 = 1 - yy1 - zz1; + slerpM01 = xy1 - wz1; + slerpM02 = xz1 + wy1; + slerpM10 = xy1 + wz1; + slerpM11 = 1 - xx1 - zz1; + slerpM12 = yz1 - wx1; + slerpM20 = xz1 - wy1; + slerpM21 = yz1 + wx1; + slerpM22 = 1 - xx1 - yy1; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = slerpM00 * prevYX + slerpM01 * prevYY + slerpM02 * prevYZ; + __tmp__Y1 = slerpM10 * prevYX + slerpM11 * prevYY + slerpM12 * prevYZ; + __tmp__Z1 = slerpM20 * prevYX + slerpM21 * prevYY + slerpM22 * prevYZ; + newYX = __tmp__X1; + newYY = __tmp__Y1; + newYZ = __tmp__Z1; + newZX = newXY * newYZ - newXZ * newYY; + newZY = newXZ * newYX - newXX * newYZ; + newZZ = newXX * newYY - newXY * newYX; + if(newZX * newZX + newZY * newZY + newZZ * newZZ > 1e-6) { + let l = newZX * newZX + newZY * newZY + newZZ * newZZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + newZX *= l; + newZY *= l; + newZZ *= l; + } else { + let x1 = newXX; + let y1 = newXY; + let z1 = newXZ; + let x2 = x1 * x1; + let y2 = y1 * y1; + let z2 = z1 * z1; + let d; + if(x2 < y2) { + if(x2 < z2) { + d = 1 / Math.sqrt(y2 + z2); + newZX = 0; + newZY = z1 * d; + newZZ = -y1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } else if(y2 < z2) { + d = 1 / Math.sqrt(z2 + x2); + newZX = -z1 * d; + newZY = 0; + newZZ = x1 * d; + } else { + d = 1 / Math.sqrt(x2 + y2); + newZX = y1 * d; + newZY = -x1 * d; + newZZ = 0; + } + } + newYX = newZY * newXZ - newZZ * newXY; + newYY = newZZ * newXX - newZX * newXZ; + newYZ = newZX * newXY - newZY * newXX; + _this.xX = newXX; + _this.xY = newXY; + _this.xZ = newXZ; + _this.yX = newYX; + _this.yY = newYY; + _this.yZ = newYZ; + _this.zX = newZX; + _this.zY = newZY; + _this.zZ = newZZ; + let angErrorX; + let angErrorY; + let angErrorZ; + angErrorX = this._basisX1Y * this._basisX2Z - this._basisX1Z * this._basisX2Y; + angErrorY = this._basisX1Z * this._basisX2X - this._basisX1X * this._basisX2Z; + angErrorZ = this._basisX1X * this._basisX2Y - this._basisX1Y * this._basisX2X; + let cos = this._basisX1X * this._basisX2X + this._basisX1Y * this._basisX2Y + this._basisX1Z * this._basisX2Z; + let theta = cos <= -1 ? 3.14159265358979 : cos >= 1 ? 0 : Math.acos(cos); + let l = angErrorX * angErrorX + angErrorY * angErrorY + angErrorZ * angErrorZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + angErrorX *= l; + angErrorY *= l; + angErrorZ *= l; + angErrorX *= theta; + angErrorY *= theta; + angErrorZ *= theta; + this.angularErrorY = angErrorX * this._basis.yX + angErrorY * this._basis.yY + angErrorZ * this._basis.yZ; + this.angularErrorZ = angErrorX * this._basis.zX + angErrorY * this._basis.zY + angErrorZ * this._basis.zZ; + let perpCrossX; + let perpCrossY; + let perpCrossZ; + perpCrossX = this._basisY1Y * this._basisY2Z - this._basisY1Z * this._basisY2Y; + perpCrossY = this._basisY1Z * this._basisY2X - this._basisY1X * this._basisY2Z; + perpCrossZ = this._basisY1X * this._basisY2Y - this._basisY1Y * this._basisY2X; + cos = this._basisY1X * this._basisY2X + this._basisY1Y * this._basisY2Y + this._basisY1Z * this._basisY2Z; + this.angle = cos <= -1 ? 3.14159265358979 : cos >= 1 ? 0 : Math.acos(cos); + if(perpCrossX * this._basis.xX + perpCrossY * this._basis.xY + perpCrossZ * this._basis.xZ < 0) { + this.angle = -this.angle; + } + this.linearErrorX = this._anchor2X - this._anchor1X; + this.linearErrorY = this._anchor2Y - this._anchor1Y; + this.linearErrorZ = this._anchor2Z - this._anchor1Z; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._basisX2X; + v.y = this._basisX2Y; + v.z = this._basisX2Z; + return v; + } + getAxis1To(axis) { + axis.x = this._basisX1X; + axis.y = this._basisX1Y; + axis.z = this._basisX1Z; + } + getAxis2To(axis) { + axis.x = this._basisX2X; + axis.y = this._basisX2Y; + axis.z = this._basisX2Z; + } + getLocalAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX1X; + v.y = this._localBasisX1Y; + v.z = this._localBasisX1Z; + return v; + } + getLocalAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX2X; + v.y = this._localBasisX2Y; + v.z = this._localBasisX2Z; + return v; + } + getLocalAxis1To(axis) { + axis.x = this._localBasisX1X; + axis.y = this._localBasisX1Y; + axis.z = this._localBasisX1Z; + } + getLocalAxis2To(axis) { + axis.x = this._localBasisX2X; + axis.y = this._localBasisX2Y; + axis.z = this._localBasisX2Z; + } + getSpringDamper() { + return this._sd; + } + getLimitMotor() { + return this._lm; + } + getAngle() { + return this.angle; + } +} +oimo.dynamics.constraint.joint.RevoluteJointConfig = class oimo_dynamics_constraint_joint_RevoluteJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localAxis1 = new oimo.common.Vec3(1,0,0); + this.localAxis2 = new oimo.common.Vec3(1,0,0); + this.springDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + this.limitMotor = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + } + init(rigidBody1,rigidBody2,worldAnchor,worldAxis) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let localVector = this.localAxis1; + let vX; + let vY; + let vZ; + vX = worldAxis.x; + vY = worldAxis.y; + vZ = worldAxis.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rigidBody1._transform._rotation00 * vX + rigidBody1._transform._rotation10 * vY + rigidBody1._transform._rotation20 * vZ; + __tmp__Y = rigidBody1._transform._rotation01 * vX + rigidBody1._transform._rotation11 * vY + rigidBody1._transform._rotation21 * vZ; + __tmp__Z = rigidBody1._transform._rotation02 * vX + rigidBody1._transform._rotation12 * vY + rigidBody1._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + let localVector1 = this.localAxis2; + let vX1; + let vY1; + let vZ1; + vX1 = worldAxis.x; + vY1 = worldAxis.y; + vZ1 = worldAxis.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = rigidBody2._transform._rotation00 * vX1 + rigidBody2._transform._rotation10 * vY1 + rigidBody2._transform._rotation20 * vZ1; + __tmp__Y1 = rigidBody2._transform._rotation01 * vX1 + rigidBody2._transform._rotation11 * vY1 + rigidBody2._transform._rotation21 * vZ1; + __tmp__Z1 = rigidBody2._transform._rotation02 * vX1 + rigidBody2._transform._rotation12 * vY1 + rigidBody2._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localVector1.x = vX1; + localVector1.y = vY1; + localVector1.z = vZ1; + return this; + } +} +oimo.dynamics.constraint.joint.RotationalLimitMotor = class oimo_dynamics_constraint_joint_RotationalLimitMotor { + constructor() { + this.lowerLimit = 1; + this.upperLimit = 0; + this.motorTorque = 0; + } + setLimits(lower,upper) { + this.lowerLimit = lower; + this.upperLimit = upper; + return this; + } + setMotor(speed,torque) { + this.motorSpeed = speed; + this.motorTorque = torque; + return this; + } + clone() { + let lm = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + lm.lowerLimit = this.lowerLimit; + lm.upperLimit = this.upperLimit; + lm.motorSpeed = this.motorSpeed; + lm.motorTorque = this.motorTorque; + return lm; + } +} +oimo.dynamics.constraint.joint.SphericalJoint = class oimo_dynamics_constraint_joint_SphericalJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,0); + this._sd = config.springDamper.clone(); + } + getInfo(info,timeStep,isPositionPart) { + if(this._sd.frequency > 0 && isPositionPart) { + return; + } + let errorX; + let errorY; + let errorZ; + errorX = this._anchor2X - this._anchor1X; + errorY = this._anchor2Y - this._anchor1Y; + errorZ = this._anchor2Z - this._anchor1Z; + let cfm; + let erp; + if(this._sd.frequency > 0) { + let omega = 6.28318530717958 * this._sd.frequency; + let zeta = this._sd.dampingRatio; + if(zeta < oimo.common.Setting.minSpringDamperDampingRatio) { + zeta = oimo.common.Setting.minSpringDamperDampingRatio; + } + let h = timeStep.dt; + let c = 2 * zeta * omega; + let k = omega * omega; + if(this._sd.useSymplecticEuler) { + cfm = 1 / (h * c); + erp = k / c; + } else { + cfm = 1 / (h * (h * k + c)); + erp = k / (h * k + c); + } + cfm *= this._b1._invMass + this._b2._invMass; + } else { + cfm = 0; + erp = this.getErp(timeStep,isPositionPart); + } + let linearRhsX; + let linearRhsY; + let linearRhsZ; + linearRhsX = errorX * erp; + linearRhsY = errorY * erp; + linearRhsZ = errorZ * erp; + let crossR100; + let crossR101; + let crossR102; + let crossR110; + let crossR111; + let crossR112; + let crossR120; + let crossR121; + let crossR122; + let crossR200; + let crossR201; + let crossR202; + let crossR210; + let crossR211; + let crossR212; + let crossR220; + let crossR221; + let crossR222; + crossR100 = 0; + crossR101 = -this._relativeAnchor1Z; + crossR102 = this._relativeAnchor1Y; + crossR110 = this._relativeAnchor1Z; + crossR111 = 0; + crossR112 = -this._relativeAnchor1X; + crossR120 = -this._relativeAnchor1Y; + crossR121 = this._relativeAnchor1X; + crossR122 = 0; + crossR200 = 0; + crossR201 = -this._relativeAnchor2Z; + crossR202 = this._relativeAnchor2Y; + crossR210 = this._relativeAnchor2Z; + crossR211 = 0; + crossR212 = -this._relativeAnchor2X; + crossR220 = -this._relativeAnchor2Y; + crossR221 = this._relativeAnchor2X; + crossR222 = 0; + crossR100 = -crossR100; + crossR101 = -crossR101; + crossR102 = -crossR102; + crossR110 = -crossR110; + crossR111 = -crossR111; + crossR112 = -crossR112; + crossR120 = -crossR120; + crossR121 = -crossR121; + crossR122 = -crossR122; + crossR200 = -crossR200; + crossR201 = -crossR201; + crossR202 = -crossR202; + crossR210 = -crossR210; + crossR211 = -crossR211; + crossR212 = -crossR212; + crossR220 = -crossR220; + crossR221 = -crossR221; + crossR222 = -crossR222; + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linearRhsX; + row.cfm = cfm; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + let j = row.jacobian; + j.lin1X = 1; + j.lin1Y = 0; + j.lin1Z = 0; + j.lin2X = 1; + j.lin2Y = 0; + j.lin2Z = 0; + j.ang1X = crossR100; + j.ang1Y = crossR101; + j.ang1Z = crossR102; + j.ang2X = crossR200; + j.ang2Y = crossR201; + j.ang2Z = crossR202; + let impulse1 = this._impulses[1]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linearRhsY; + row1.cfm = cfm; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = 0; + j.lin1Y = 1; + j.lin1Z = 0; + j.lin2X = 0; + j.lin2Y = 1; + j.lin2Z = 0; + j.ang1X = crossR110; + j.ang1Y = crossR111; + j.ang1Z = crossR112; + j.ang2X = crossR210; + j.ang2Y = crossR211; + j.ang2Z = crossR212; + let impulse2 = this._impulses[2]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = linearRhsZ; + row2.cfm = cfm; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.lin1X = 0; + j.lin1Y = 0; + j.lin1Z = 1; + j.lin2X = 0; + j.lin2Y = 0; + j.lin2Z = 1; + j.ang1X = crossR120; + j.ang1Y = crossR121; + j.ang1Z = crossR122; + j.ang2X = crossR220; + j.ang2Y = crossR221; + j.ang2Z = crossR222; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getSpringDamper() { + return this._sd; + } +} +oimo.dynamics.constraint.joint.SphericalJointConfig = class oimo_dynamics_constraint_joint_SphericalJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.springDamper = new oimo.dynamics.constraint.joint.SpringDamper(); + } + init(rigidBody1,rigidBody2,worldAnchor) { + this._init(rigidBody1,rigidBody2,worldAnchor); + return this; + } +} +oimo.dynamics.constraint.joint.SpringDamper = class oimo_dynamics_constraint_joint_SpringDamper { + constructor() { + this.frequency = 0; + this.dampingRatio = 0; + this.useSymplecticEuler = false; + } + setSpring(frequency,dampingRatio) { + this.frequency = frequency; + this.dampingRatio = dampingRatio; + return this; + } + setSymplecticEuler(useSymplecticEuler) { + this.useSymplecticEuler = useSymplecticEuler; + return this; + } + clone() { + let sd = new oimo.dynamics.constraint.joint.SpringDamper(); + sd.frequency = this.frequency; + sd.dampingRatio = this.dampingRatio; + sd.useSymplecticEuler = this.useSymplecticEuler; + return sd; + } +} +oimo.dynamics.constraint.joint.TranslationalLimitMotor = class oimo_dynamics_constraint_joint_TranslationalLimitMotor { + constructor() { + this.lowerLimit = 1; + this.upperLimit = 0; + this.motorForce = 0; + } + setLimits(lower,upper) { + this.lowerLimit = lower; + this.upperLimit = upper; + return this; + } + setMotor(speed,force) { + this.motorSpeed = speed; + this.motorForce = force; + return this; + } + clone() { + let lm = new oimo.dynamics.constraint.joint.TranslationalLimitMotor(); + lm.lowerLimit = this.lowerLimit; + lm.upperLimit = this.upperLimit; + lm.motorSpeed = this.motorSpeed; + lm.motorForce = this.motorForce; + return lm; + } +} +oimo.dynamics.constraint.joint.UniversalJoint = class oimo_dynamics_constraint_joint_UniversalJoint extends oimo.dynamics.constraint.joint.Joint { + constructor(config) { + super(config,oimo.dynamics.constraint.joint.JointType.UNIVERSAL); + let v = config.localAxis1; + this._localBasisX1X = v.x; + this._localBasisX1Y = v.y; + this._localBasisX1Z = v.z; + let v1 = config.localAxis2; + this._localBasisZ2X = v1.x; + this._localBasisZ2Y = v1.y; + this._localBasisZ2Z = v1.z; + this.buildLocalBasesFromX1Z2(); + this._angleX = 0; + this._angleY = 0; + this._angleZ = 0; + this.xSingular = false; + this.ySingular = false; + this.zSingular = false; + this._sd1 = config.springDamper1.clone(); + this._sd2 = config.springDamper2.clone(); + this._lm1 = config.limitMotor1.clone(); + this._lm2 = config.limitMotor2.clone(); + } + getInfo(info,timeStep,isPositionPart) { + let erp = this.getErp(timeStep,isPositionPart); + let linearRhsX; + let linearRhsY; + let linearRhsZ; + linearRhsX = this.linearErrorX * erp; + linearRhsY = this.linearErrorY * erp; + linearRhsZ = this.linearErrorZ * erp; + let angRhsY = this._angleY * erp; + let crossR100; + let crossR101; + let crossR102; + let crossR110; + let crossR111; + let crossR112; + let crossR120; + let crossR121; + let crossR122; + let crossR200; + let crossR201; + let crossR202; + let crossR210; + let crossR211; + let crossR212; + let crossR220; + let crossR221; + let crossR222; + crossR100 = 0; + crossR101 = -this._relativeAnchor1Z; + crossR102 = this._relativeAnchor1Y; + crossR110 = this._relativeAnchor1Z; + crossR111 = 0; + crossR112 = -this._relativeAnchor1X; + crossR120 = -this._relativeAnchor1Y; + crossR121 = this._relativeAnchor1X; + crossR122 = 0; + crossR200 = 0; + crossR201 = -this._relativeAnchor2Z; + crossR202 = this._relativeAnchor2Y; + crossR210 = this._relativeAnchor2Z; + crossR211 = 0; + crossR212 = -this._relativeAnchor2X; + crossR220 = -this._relativeAnchor2Y; + crossR221 = this._relativeAnchor2X; + crossR222 = 0; + crossR100 = -crossR100; + crossR101 = -crossR101; + crossR102 = -crossR102; + crossR110 = -crossR110; + crossR111 = -crossR111; + crossR112 = -crossR112; + crossR120 = -crossR120; + crossR121 = -crossR121; + crossR122 = -crossR122; + crossR200 = -crossR200; + crossR201 = -crossR201; + crossR202 = -crossR202; + crossR210 = -crossR210; + crossR211 = -crossR211; + crossR212 = -crossR212; + crossR220 = -crossR220; + crossR221 = -crossR221; + crossR222 = -crossR222; + let motorMassX = this.computeEffectiveInertiaMoment(this._axisXX,this._axisXY,this._axisXZ); + let motorMassZ = this.computeEffectiveInertiaMoment(this._axisZX,this._axisZY,this._axisZZ); + let impulse = this._impulses[0]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = linearRhsX; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + let j = row.jacobian; + j.lin1X = 1; + j.lin1Y = 0; + j.lin1Z = 0; + j.lin2X = 1; + j.lin2Y = 0; + j.lin2Z = 0; + j.ang1X = crossR100; + j.ang1Y = crossR101; + j.ang1Z = crossR102; + j.ang2X = crossR200; + j.ang2Y = crossR201; + j.ang2Z = crossR202; + let impulse1 = this._impulses[1]; + let row1 = info.rows[info.numRows++]; + let _this1 = row1.jacobian; + _this1.lin1X = 0; + _this1.lin1Y = 0; + _this1.lin1Z = 0; + _this1.lin2X = 0; + _this1.lin2Y = 0; + _this1.lin2Z = 0; + _this1.ang1X = 0; + _this1.ang1Y = 0; + _this1.ang1Z = 0; + _this1.ang2X = 0; + _this1.ang2Y = 0; + _this1.ang2Z = 0; + row1.rhs = 0; + row1.cfm = 0; + row1.minImpulse = 0; + row1.maxImpulse = 0; + row1.motorSpeed = 0; + row1.motorMaxImpulse = 0; + row1.impulse = null; + row1.impulse = impulse1; + row1.rhs = linearRhsY; + row1.cfm = 0; + row1.minImpulse = -1e65536; + row1.maxImpulse = 1e65536; + j = row1.jacobian; + j.lin1X = 0; + j.lin1Y = 1; + j.lin1Z = 0; + j.lin2X = 0; + j.lin2Y = 1; + j.lin2Z = 0; + j.ang1X = crossR110; + j.ang1Y = crossR111; + j.ang1Z = crossR112; + j.ang2X = crossR210; + j.ang2Y = crossR211; + j.ang2Z = crossR212; + let impulse2 = this._impulses[2]; + let row2 = info.rows[info.numRows++]; + let _this2 = row2.jacobian; + _this2.lin1X = 0; + _this2.lin1Y = 0; + _this2.lin1Z = 0; + _this2.lin2X = 0; + _this2.lin2Y = 0; + _this2.lin2Z = 0; + _this2.ang1X = 0; + _this2.ang1Y = 0; + _this2.ang1Z = 0; + _this2.ang2X = 0; + _this2.ang2Y = 0; + _this2.ang2Z = 0; + row2.rhs = 0; + row2.cfm = 0; + row2.minImpulse = 0; + row2.maxImpulse = 0; + row2.motorSpeed = 0; + row2.motorMaxImpulse = 0; + row2.impulse = null; + row2.impulse = impulse2; + row2.rhs = linearRhsZ; + row2.cfm = 0; + row2.minImpulse = -1e65536; + row2.maxImpulse = 1e65536; + j = row2.jacobian; + j.lin1X = 0; + j.lin1Y = 0; + j.lin1Z = 1; + j.lin2X = 0; + j.lin2Y = 0; + j.lin2Z = 1; + j.ang1X = crossR120; + j.ang1Y = crossR121; + j.ang1Z = crossR122; + j.ang2X = crossR220; + j.ang2Y = crossR221; + j.ang2Z = crossR222; + if(!this.xSingular && (this._sd1.frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[3]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._angleX,this._lm1,motorMassX,this._sd1,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._axisXX; + j.ang1Y = this._axisXY; + j.ang1Z = this._axisXZ; + j.ang2X = this._axisXX; + j.ang2Y = this._axisXY; + j.ang2Z = this._axisXZ; + } + if(!this.ySingular) { + let impulse = this._impulses[4]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + row.rhs = angRhsY; + row.cfm = 0; + row.minImpulse = -1e65536; + row.maxImpulse = 1e65536; + j = row.jacobian; + j.ang1X = this._axisYX; + j.ang1Y = this._axisYY; + j.ang1Z = this._axisYZ; + j.ang2X = this._axisYX; + j.ang2Y = this._axisYY; + j.ang2Z = this._axisYZ; + } + if(!this.zSingular && (this._sd2.frequency <= 0 || !isPositionPart)) { + let impulse = this._impulses[5]; + let row = info.rows[info.numRows++]; + let _this = row.jacobian; + _this.lin1X = 0; + _this.lin1Y = 0; + _this.lin1Z = 0; + _this.lin2X = 0; + _this.lin2Y = 0; + _this.lin2Z = 0; + _this.ang1X = 0; + _this.ang1Y = 0; + _this.ang1Z = 0; + _this.ang2X = 0; + _this.ang2Y = 0; + _this.ang2Z = 0; + row.rhs = 0; + row.cfm = 0; + row.minImpulse = 0; + row.maxImpulse = 0; + row.motorSpeed = 0; + row.motorMaxImpulse = 0; + row.impulse = null; + row.impulse = impulse; + this.setSolverInfoRowAngular(row,this._angleZ,this._lm2,motorMassZ,this._sd2,timeStep,isPositionPart); + j = row.jacobian; + j.ang1X = this._axisZX; + j.ang1Y = this._axisZY; + j.ang1Z = this._axisZZ; + j.ang2X = this._axisZX; + j.ang2Y = this._axisZY; + j.ang2Z = this._axisZZ; + } + } + _syncAnchors() { + super._syncAnchors(); + let angleAxisXX; + let angleAxisXY; + let angleAxisXZ; + let angleAxisYX; + let angleAxisYY; + let angleAxisYZ; + let angleAxisZX; + let angleAxisZY; + let angleAxisZZ; + angleAxisXX = this._basisX1X; + angleAxisXY = this._basisX1Y; + angleAxisXZ = this._basisX1Z; + angleAxisZX = this._basisZ2X; + angleAxisZY = this._basisZ2Y; + angleAxisZZ = this._basisZ2Z; + angleAxisYX = angleAxisZY * angleAxisXZ - angleAxisZZ * angleAxisXY; + angleAxisYY = angleAxisZZ * angleAxisXX - angleAxisZX * angleAxisXZ; + angleAxisYZ = angleAxisZX * angleAxisXY - angleAxisZY * angleAxisXX; + this._axisXX = angleAxisYY * angleAxisZZ - angleAxisYZ * angleAxisZY; + this._axisXY = angleAxisYZ * angleAxisZX - angleAxisYX * angleAxisZZ; + this._axisXZ = angleAxisYX * angleAxisZY - angleAxisYY * angleAxisZX; + this._axisYX = angleAxisYX; + this._axisYY = angleAxisYY; + this._axisYZ = angleAxisYZ; + this._axisZX = angleAxisXY * angleAxisYZ - angleAxisXZ * angleAxisYY; + this._axisZY = angleAxisXZ * angleAxisYX - angleAxisXX * angleAxisYZ; + this._axisZZ = angleAxisXX * angleAxisYY - angleAxisXY * angleAxisYX; + let l = this._axisXX * this._axisXX + this._axisXY * this._axisXY + this._axisXZ * this._axisXZ; + if(l > 0) { + l = 1 / Math.sqrt(l); + } + this._axisXX *= l; + this._axisXY *= l; + this._axisXZ *= l; + let l1 = this._axisYX * this._axisYX + this._axisYY * this._axisYY + this._axisYZ * this._axisYZ; + if(l1 > 0) { + l1 = 1 / Math.sqrt(l1); + } + this._axisYX *= l1; + this._axisYY *= l1; + this._axisYZ *= l1; + let l2 = this._axisZX * this._axisZX + this._axisZY * this._axisZY + this._axisZZ * this._axisZZ; + if(l2 > 0) { + l2 = 1 / Math.sqrt(l2); + } + this._axisZX *= l2; + this._axisZY *= l2; + this._axisZZ *= l2; + this.xSingular = this._axisXX * this._axisXX + this._axisXY * this._axisXY + this._axisXZ * this._axisXZ == 0; + this.ySingular = this._axisYX * this._axisYX + this._axisYY * this._axisYY + this._axisYZ * this._axisYZ == 0; + this.zSingular = this._axisZX * this._axisZX + this._axisZY * this._axisZY + this._axisZZ * this._axisZZ == 0; + let rot100; + let rot101; + let rot102; + let rot110; + let rot111; + let rot112; + let rot120; + let rot121; + let rot122; + let rot200; + let rot201; + let rot202; + let rot210; + let rot211; + let rot212; + let rot220; + let rot221; + let rot222; + rot100 = this._basisX1X; + rot101 = this._basisY1X; + rot102 = this._basisZ1X; + rot110 = this._basisX1Y; + rot111 = this._basisY1Y; + rot112 = this._basisZ1Y; + rot120 = this._basisX1Z; + rot121 = this._basisY1Z; + rot122 = this._basisZ1Z; + rot200 = this._basisX2X; + rot201 = this._basisY2X; + rot202 = this._basisZ2X; + rot210 = this._basisX2Y; + rot211 = this._basisY2Y; + rot212 = this._basisZ2Y; + rot220 = this._basisX2Z; + rot221 = this._basisY2Z; + rot222 = this._basisZ2Z; + let relRot00; + let relRot01; + let relRot02; + let relRot11; + let relRot12; + let relRot21; + let relRot22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__11; + let __tmp__12; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot100 * rot200 + rot110 * rot210 + rot120 * rot220; + __tmp__01 = rot100 * rot201 + rot110 * rot211 + rot120 * rot221; + __tmp__02 = rot100 * rot202 + rot110 * rot212 + rot120 * rot222; + __tmp__11 = rot101 * rot201 + rot111 * rot211 + rot121 * rot221; + __tmp__12 = rot101 * rot202 + rot111 * rot212 + rot121 * rot222; + __tmp__21 = rot102 * rot201 + rot112 * rot211 + rot122 * rot221; + __tmp__22 = rot102 * rot202 + rot112 * rot212 + rot122 * rot222; + relRot00 = __tmp__00; + relRot01 = __tmp__01; + relRot02 = __tmp__02; + relRot11 = __tmp__11; + relRot12 = __tmp__12; + relRot21 = __tmp__21; + relRot22 = __tmp__22; + let anglesX; + let anglesY; + let anglesZ; + let sy = relRot02; + if(sy <= -1) { + let xSubZ = Math.atan2(relRot21,relRot11); + anglesX = xSubZ * 0.5; + anglesY = -1.570796326794895; + anglesZ = -xSubZ * 0.5; + } else if(sy >= 1) { + let xAddZ = Math.atan2(relRot21,relRot11); + anglesX = xAddZ * 0.5; + anglesY = 1.570796326794895; + anglesZ = xAddZ * 0.5; + } else { + anglesX = Math.atan2(-relRot12,relRot22); + anglesY = Math.asin(sy); + anglesZ = Math.atan2(-relRot01,relRot00); + } + this._angleX = anglesX; + this._angleY = anglesY; + this._angleZ = anglesZ; + this.linearErrorX = this._anchor2X - this._anchor1X; + this.linearErrorY = this._anchor2Y - this._anchor1Y; + this.linearErrorZ = this._anchor2Z - this._anchor1Z; + } + _getVelocitySolverInfo(timeStep,info) { + super._getVelocitySolverInfo(timeStep,info); + this.getInfo(info,timeStep,false); + } + _getPositionSolverInfo(info) { + super._getPositionSolverInfo(info); + this.getInfo(info,null,true); + } + getAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._basisX1X; + v.y = this._basisX1Y; + v.z = this._basisX1Z; + return v; + } + getAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._basisZ2X; + v.y = this._basisZ2Y; + v.z = this._basisZ2Z; + return v; + } + getAxis1To(axis) { + axis.x = this._basisX1X; + axis.y = this._basisX1Y; + axis.z = this._basisX1Z; + } + getAxis2To(axis) { + axis.x = this._basisZ2X; + axis.y = this._basisZ2Y; + axis.z = this._basisZ2Z; + } + getLocalAxis1() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisX1X; + v.y = this._localBasisX1Y; + v.z = this._localBasisX1Z; + return v; + } + getLocalAxis2() { + let v = new oimo.common.Vec3(); + v.x = this._localBasisZ2X; + v.y = this._localBasisZ2Y; + v.z = this._localBasisZ2Z; + return v; + } + getLocalAxis1To(axis) { + axis.x = this._localBasisX1X; + axis.y = this._localBasisX1Y; + axis.z = this._localBasisX1Z; + } + getLocalAxis2To(axis) { + axis.x = this._localBasisZ2X; + axis.y = this._localBasisZ2Y; + axis.z = this._localBasisZ2Z; + } + getSpringDamper1() { + return this._sd1; + } + getSpringDamper2() { + return this._sd2; + } + getLimitMotor1() { + return this._lm1; + } + getLimitMotor2() { + return this._lm2; + } + getAngle1() { + return this._angleX; + } + getAngle2() { + return this._angleZ; + } +} +oimo.dynamics.constraint.joint.UniversalJointConfig = class oimo_dynamics_constraint_joint_UniversalJointConfig extends oimo.dynamics.constraint.joint.JointConfig { + constructor() { + super(); + this.localAxis1 = new oimo.common.Vec3(1,0,0); + this.localAxis2 = new oimo.common.Vec3(1,0,0); + this.springDamper1 = new oimo.dynamics.constraint.joint.SpringDamper(); + this.springDamper2 = new oimo.dynamics.constraint.joint.SpringDamper(); + this.limitMotor1 = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + this.limitMotor2 = new oimo.dynamics.constraint.joint.RotationalLimitMotor(); + } + init(rigidBody1,rigidBody2,worldAnchor,worldAxis1,worldAxis2) { + this._init(rigidBody1,rigidBody2,worldAnchor); + let localVector = this.localAxis1; + let vX; + let vY; + let vZ; + vX = worldAxis1.x; + vY = worldAxis1.y; + vZ = worldAxis1.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = rigidBody1._transform._rotation00 * vX + rigidBody1._transform._rotation10 * vY + rigidBody1._transform._rotation20 * vZ; + __tmp__Y = rigidBody1._transform._rotation01 * vX + rigidBody1._transform._rotation11 * vY + rigidBody1._transform._rotation21 * vZ; + __tmp__Z = rigidBody1._transform._rotation02 * vX + rigidBody1._transform._rotation12 * vY + rigidBody1._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + let localVector1 = this.localAxis2; + let vX1; + let vY1; + let vZ1; + vX1 = worldAxis2.x; + vY1 = worldAxis2.y; + vZ1 = worldAxis2.z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = rigidBody2._transform._rotation00 * vX1 + rigidBody2._transform._rotation10 * vY1 + rigidBody2._transform._rotation20 * vZ1; + __tmp__Y1 = rigidBody2._transform._rotation01 * vX1 + rigidBody2._transform._rotation11 * vY1 + rigidBody2._transform._rotation21 * vZ1; + __tmp__Z1 = rigidBody2._transform._rotation02 * vX1 + rigidBody2._transform._rotation12 * vY1 + rigidBody2._transform._rotation22 * vZ1; + vX1 = __tmp__X1; + vY1 = __tmp__Y1; + vZ1 = __tmp__Z1; + localVector1.x = vX1; + localVector1.y = vY1; + localVector1.z = vZ1; + return this; + } +} +if(!oimo.dynamics.constraint.solver) oimo.dynamics.constraint.solver = {}; +oimo.dynamics.constraint.solver.ConstraintSolverType = class oimo_dynamics_constraint_solver_ConstraintSolverType { +} +if(!oimo.dynamics.constraint.solver.common) oimo.dynamics.constraint.solver.common = {}; +oimo.dynamics.constraint.solver.common.ContactSolverMassDataRow = class oimo_dynamics_constraint_solver_common_ContactSolverMassDataRow { + constructor() { + this.invMLinN1X = 0; + this.invMLinN1Y = 0; + this.invMLinN1Z = 0; + this.invMLinN2X = 0; + this.invMLinN2Y = 0; + this.invMLinN2Z = 0; + this.invMAngN1X = 0; + this.invMAngN1Y = 0; + this.invMAngN1Z = 0; + this.invMAngN2X = 0; + this.invMAngN2Y = 0; + this.invMAngN2Z = 0; + this.invMLinT1X = 0; + this.invMLinT1Y = 0; + this.invMLinT1Z = 0; + this.invMLinT2X = 0; + this.invMLinT2Y = 0; + this.invMLinT2Z = 0; + this.invMAngT1X = 0; + this.invMAngT1Y = 0; + this.invMAngT1Z = 0; + this.invMAngT2X = 0; + this.invMAngT2Y = 0; + this.invMAngT2Z = 0; + this.invMLinB1X = 0; + this.invMLinB1Y = 0; + this.invMLinB1Z = 0; + this.invMLinB2X = 0; + this.invMLinB2Y = 0; + this.invMLinB2Z = 0; + this.invMAngB1X = 0; + this.invMAngB1Y = 0; + this.invMAngB1Z = 0; + this.invMAngB2X = 0; + this.invMAngB2Y = 0; + this.invMAngB2Z = 0; + this.massN = 0; + this.massTB00 = 0; + this.massTB01 = 0; + this.massTB10 = 0; + this.massTB11 = 0; + } +} +oimo.dynamics.constraint.solver.common.JointSolverMassDataRow = class oimo_dynamics_constraint_solver_common_JointSolverMassDataRow { + constructor() { + this.invMLin1X = 0; + this.invMLin1Y = 0; + this.invMLin1Z = 0; + this.invMLin2X = 0; + this.invMLin2Y = 0; + this.invMLin2Z = 0; + this.invMAng1X = 0; + this.invMAng1Y = 0; + this.invMAng1Z = 0; + this.invMAng2X = 0; + this.invMAng2Y = 0; + this.invMAng2Z = 0; + this.mass = 0; + this.massWithoutCfm = 0; + } +} +if(!oimo.dynamics.constraint.solver.direct) oimo.dynamics.constraint.solver.direct = {}; +oimo.dynamics.constraint.solver.direct.Boundary = class oimo_dynamics_constraint_solver_direct_Boundary { + constructor(maxRows) { + this.iBounded = new Array(maxRows); + this.iUnbounded = new Array(maxRows); + this.signs = new Array(maxRows); + this.b = new Array(maxRows); + this.numBounded = 0; + this.numUnbounded = 0; + this.matrixId = 0; + } + init(buildInfo) { + this.numBounded = buildInfo.numBounded; + let _g = 0; + let _g1 = this.numBounded; + while(_g < _g1) { + let i = _g++; + this.iBounded[i] = buildInfo.iBounded[i]; + this.signs[i] = buildInfo.signs[i]; + } + this.numUnbounded = buildInfo.numUnbounded; + this.matrixId = 0; + let _g2 = 0; + let _g3 = this.numUnbounded; + while(_g2 < _g3) { + let i = _g2++; + let idx = buildInfo.iUnbounded[i]; + this.iUnbounded[i] = idx; + this.matrixId |= 1 << idx; + } + } + computeImpulses(info,mass,relVels,impulses,dImpulses,impulseFactor,noCheck) { + let _g = 0; + let _g1 = this.numUnbounded; + while(_g < _g1) { + let idx = this.iUnbounded[_g++]; + let row = info.rows[idx]; + this.b[idx] = row.rhs * impulseFactor - relVels[idx] - row.cfm * impulses[idx]; + } + let invMassWithoutCfm = mass._invMassWithoutCfm; + let _g2 = 0; + let _g3 = this.numBounded; + while(_g2 < _g3) { + let i = _g2++; + let idx = this.iBounded[i]; + let sign = this.signs[i]; + let row = info.rows[idx]; + let dImpulse = (sign < 0 ? row.minImpulse : sign > 0 ? row.maxImpulse : 0) - impulses[idx]; + dImpulses[idx] = dImpulse; + if(dImpulse != 0) { + let _g = 0; + let _g1 = this.numUnbounded; + while(_g < _g1) { + let idx2 = this.iUnbounded[_g++]; + this.b[idx2] -= invMassWithoutCfm[idx][idx2] * dImpulse; + } + } + } + let indices = this.iUnbounded; + let n = this.numUnbounded; + let id = 0; + let _g4 = 0; + while(_g4 < n) id |= 1 << indices[_g4++]; + let massMatrix; + if(mass._cacheComputed[id]) { + massMatrix = mass._cachedSubmatrices[id]; + } else { + mass.computeSubmatrix(id,indices,n); + mass._cacheComputed[id] = true; + massMatrix = mass._cachedSubmatrices[id]; + } + let ok = true; + let _g5 = 0; + let _g6 = this.numUnbounded; + while(_g5 < _g6) { + let i = _g5++; + let idx = this.iUnbounded[i]; + let row = info.rows[idx]; + let oldImpulse = impulses[idx]; + let impulse = oldImpulse; + let _g = 0; + let _g1 = this.numUnbounded; + while(_g < _g1) { + let j = _g++; + impulse += this.b[this.iUnbounded[j]] * massMatrix[i][j]; + } + if(impulse < row.minImpulse - oimo.common.Setting.directMlcpSolverEps || impulse > row.maxImpulse + oimo.common.Setting.directMlcpSolverEps) { + ok = false; + break; + } + dImpulses[idx] = impulse - oldImpulse; + } + if(noCheck) { + return true; + } + if(!ok) { + return false; + } + let _g7 = 0; + let _g8 = this.numBounded; + while(_g7 < _g8) { + let i = _g7++; + let idx = this.iBounded[i]; + let row = info.rows[idx]; + let sign = this.signs[i]; + let error = 0; + let newImpulse = impulses[idx] + dImpulses[idx]; + let relVel = relVels[idx]; + let _g = 0; + let _g1 = info.numRows; + while(_g < _g1) { + let j = _g++; + relVel += invMassWithoutCfm[idx][j] * dImpulses[j]; + } + error = row.rhs * impulseFactor - relVel - row.cfm * newImpulse; + if(sign < 0 && error > oimo.common.Setting.directMlcpSolverEps || sign > 0 && error < -oimo.common.Setting.directMlcpSolverEps) { + ok = false; + break; + } + } + return ok; + } +} +oimo.dynamics.constraint.solver.direct.BoundaryBuildInfo = class oimo_dynamics_constraint_solver_direct_BoundaryBuildInfo { + constructor(size) { + this.size = size; + this.numBounded = 0; + this.iBounded = new Array(size); + this.signs = new Array(size); + this.numUnbounded = 0; + this.iUnbounded = new Array(size); + } +} +oimo.dynamics.constraint.solver.direct.BoundaryBuilder = class oimo_dynamics_constraint_solver_direct_BoundaryBuilder { + constructor(maxRows) { + this.maxRows = maxRows; + this.numBoundaries = 0; + this.boundaries = new Array(1 << maxRows); + this.bbInfo = new oimo.dynamics.constraint.solver.direct.BoundaryBuildInfo(maxRows); + } + buildBoundariesRecursive(info,i) { + if(i == info.numRows) { + if(this.boundaries[this.numBoundaries] == null) { + this.boundaries[this.numBoundaries] = new oimo.dynamics.constraint.solver.direct.Boundary(this.maxRows); + } + this.boundaries[this.numBoundaries++].init(this.bbInfo); + return; + } + let row = info.rows[i]; + let lowerLimitEnabled = row.minImpulse > -1e65536; + let upperLimitEnabled = row.maxImpulse < 1e65536; + if(row.minImpulse == 0 && row.maxImpulse == 0) { + let _this = this.bbInfo; + _this.iBounded[_this.numBounded] = i; + _this.signs[_this.numBounded] = 0; + _this.numBounded++; + this.buildBoundariesRecursive(info,i + 1); + this.bbInfo.numBounded--; + return; + } + let _this = this.bbInfo; + _this.iUnbounded[_this.numUnbounded] = i; + _this.numUnbounded++; + this.buildBoundariesRecursive(info,i + 1); + this.bbInfo.numUnbounded--; + if(lowerLimitEnabled) { + let _this = this.bbInfo; + _this.iBounded[_this.numBounded] = i; + _this.signs[_this.numBounded] = -1; + _this.numBounded++; + this.buildBoundariesRecursive(info,i + 1); + this.bbInfo.numBounded--; + } + if(upperLimitEnabled) { + let _this = this.bbInfo; + _this.iBounded[_this.numBounded] = i; + _this.signs[_this.numBounded] = 1; + _this.numBounded++; + this.buildBoundariesRecursive(info,i + 1); + this.bbInfo.numBounded--; + } + } + buildBoundaries(info) { + this.numBoundaries = 0; + let _this = this.bbInfo; + _this.numBounded = 0; + _this.numUnbounded = 0; + this.buildBoundariesRecursive(info,0); + } +} +oimo.dynamics.constraint.solver.direct.BoundarySelector = class oimo_dynamics_constraint_solver_direct_BoundarySelector { + constructor(n) { + this.n = n; + this.indices = new Array(n); + this.tmpIndices = new Array(n); + let _g = 0; + while(_g < n) { + let i = _g++; + this.indices[i] = i; + } + } + getIndex(i) { + return this.indices[i]; + } + select(index) { + let i = 0; + while(this.indices[i] != index) ++i; + while(i > 0) { + let tmp = this.indices[i]; + this.indices[i] = this.indices[i - 1]; + this.indices[i - 1] = tmp; + --i; + } + } + setSize(size) { + let numSmaller = 0; + let numGreater = 0; + let _g = 0; + let _g1 = this.n; + while(_g < _g1) { + let idx = this.indices[_g++]; + if(idx < size) { + this.tmpIndices[numSmaller] = idx; + ++numSmaller; + } else { + this.tmpIndices[size + numGreater] = idx; + ++numGreater; + } + } + let tmp = this.indices; + this.indices = this.tmpIndices; + this.tmpIndices = tmp; + } +} +oimo.dynamics.constraint.solver.direct.DirectJointConstraintSolver = class oimo_dynamics_constraint_solver_direct_DirectJointConstraintSolver extends oimo.dynamics.constraint.ConstraintSolver { + constructor(joint) { + super(); + this.joint = joint; + this.info = new oimo.dynamics.constraint.info.joint.JointSolverInfo(); + let maxRows = oimo.common.Setting.maxJacobianRows; + this.massMatrix = new oimo.dynamics.constraint.solver.direct.MassMatrix(maxRows); + this.boundaryBuilder = new oimo.dynamics.constraint.solver.direct.BoundaryBuilder(maxRows); + this.massData = new Array(maxRows); + let _g = 0; + let _g1 = this.massData.length; + while(_g < _g1) this.massData[_g++] = new oimo.dynamics.constraint.solver.common.JointSolverMassDataRow(); + let numMaxBoundaries = this.boundaryBuilder.boundaries.length; + this.velBoundarySelector = new oimo.dynamics.constraint.solver.direct.BoundarySelector(numMaxBoundaries); + this.posBoundarySelector = new oimo.dynamics.constraint.solver.direct.BoundarySelector(numMaxBoundaries); + this.relVels = new Array(maxRows); + this.impulses = new Array(maxRows); + this.dImpulses = new Array(maxRows); + this.dTotalImpulses = new Array(maxRows); + let _g2 = 0; + while(_g2 < maxRows) { + let i = _g2++; + this.relVels[i] = 0; + this.impulses[i] = 0; + this.dImpulses[i] = 0; + this.dTotalImpulses[i] = 0; + } + } + preSolveVelocity(timeStep) { + this.joint._syncAnchors(); + this.joint._getVelocitySolverInfo(timeStep,this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + this.massMatrix.computeInvMass(this.info,this.massData); + let _this = this.boundaryBuilder; + _this.numBoundaries = 0; + let _this1 = _this.bbInfo; + _this1.numBounded = 0; + _this1.numUnbounded = 0; + _this.buildBoundariesRecursive(this.info,0); + let _this2 = this.velBoundarySelector; + let size = this.boundaryBuilder.numBoundaries; + let numSmaller = 0; + let numGreater = 0; + let _g = 0; + let _g1 = _this2.n; + while(_g < _g1) { + let idx = _this2.indices[_g++]; + if(idx < size) { + _this2.tmpIndices[numSmaller] = idx; + ++numSmaller; + } else { + _this2.tmpIndices[size + numGreater] = idx; + ++numGreater; + } + } + let tmp = _this2.indices; + _this2.indices = _this2.tmpIndices; + _this2.tmpIndices = tmp; + } + warmStart(timeStep) { + let factor = this.joint._positionCorrectionAlgorithm == oimo.dynamics.constraint.PositionCorrectionAlgorithm.BAUMGARTE ? oimo.common.Setting.jointWarmStartingFactorForBaungarte : oimo.common.Setting.jointWarmStartingFactor; + factor *= timeStep.dtRatio; + if(factor <= 0) { + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let _this = this.info.rows[_g++].impulse; + _this.impulse = 0; + _this.impulseM = 0; + _this.impulseP = 0; + } + return; + } + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let imp = row.impulse; + let impulse = imp.impulse * factor; + if(impulse < row.minImpulse) { + impulse = row.minImpulse; + } else if(impulse > row.maxImpulse) { + impulse = row.maxImpulse; + } + imp.impulse = impulse; + if(row.motorMaxImpulse > 0) { + let impulseM = imp.impulseM * factor; + let max = row.motorMaxImpulse; + if(impulseM < -max) { + impulseM = -max; + } else if(impulseM > max) { + impulseM = max; + } + imp.impulseM = impulseM; + } else { + imp.impulseM = 0; + } + this.dImpulses[i] = imp.impulse + imp.impulseM; + } + let impulses = this.dImpulses; + let linearSet = false; + let angularSet = false; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) { + let i = _g2++; + let j = this.info.rows[i].jacobian; + let md = this.massData[i]; + let imp = impulses[i]; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * imp; + lv1Y += md.invMLin1Y * imp; + lv1Z += md.invMLin1Z * imp; + lv2X += md.invMLin2X * -imp; + lv2Y += md.invMLin2Y * -imp; + lv2Z += md.invMLin2Z * -imp; + linearSet = true; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * imp; + av1Y += md.invMAng1Y * imp; + av1Z += md.invMAng1Z * imp; + av2X += md.invMAng2X * -imp; + av2Y += md.invMAng2Y * -imp; + av2Z += md.invMAng2Z * -imp; + angularSet = true; + } + } + if(linearSet) { + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + } + if(angularSet) { + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + } + solveVelocity() { + let numRows = this.info.numRows; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g = 0; + while(_g < numRows) { + let i = _g++; + let row = this.info.rows[i]; + let j = row.jacobian; + let relVel = 0; + relVel += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + relVel -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + relVel += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + relVel -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + this.relVels[i] = relVel; + this.impulses[i] = row.impulse.impulse; + this.dTotalImpulses[i] = 0; + } + let invMass = this.massMatrix._invMassWithoutCfm; + let _g1 = 0; + while(_g1 < numRows) { + let i = _g1++; + let row = this.info.rows[i]; + let imp = row.impulse; + if(row.motorMaxImpulse > 0) { + let oldImpulseM = imp.impulseM; + let impulseM = oldImpulseM + this.massData[i].massWithoutCfm * (-row.motorSpeed - this.relVels[i]); + let maxImpulseM = row.motorMaxImpulse; + if(impulseM < -maxImpulseM) { + impulseM = -maxImpulseM; + } else if(impulseM > maxImpulseM) { + impulseM = maxImpulseM; + } + imp.impulseM = impulseM; + let dImpulseM = impulseM - oldImpulseM; + this.dTotalImpulses[i] = dImpulseM; + let _g = 0; + while(_g < numRows) { + let j = _g++; + this.relVels[j] += dImpulseM * invMass[i][j]; + } + } + } + let solved = false; + let _g2 = 0; + let _g3 = this.boundaryBuilder.numBoundaries; + while(_g2 < _g3) { + let idx = this.velBoundarySelector.indices[_g2++]; + if(this.boundaryBuilder.boundaries[idx].computeImpulses(this.info,this.massMatrix,this.relVels,this.impulses,this.dImpulses,1,false)) { + let _g = 0; + while(_g < numRows) { + let j = _g++; + let dimp = this.dImpulses[j]; + this.info.rows[j].impulse.impulse += dimp; + this.dTotalImpulses[j] += dimp; + } + let impulses = this.dTotalImpulses; + let linearSet = false; + let angularSet = false; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g1 = 0; + let _g2 = this.info.numRows; + while(_g1 < _g2) { + let i = _g1++; + let j = this.info.rows[i].jacobian; + let md = this.massData[i]; + let imp = impulses[i]; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * imp; + lv1Y += md.invMLin1Y * imp; + lv1Z += md.invMLin1Z * imp; + lv2X += md.invMLin2X * -imp; + lv2Y += md.invMLin2Y * -imp; + lv2Z += md.invMLin2Z * -imp; + linearSet = true; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * imp; + av1Y += md.invMAng1Y * imp; + av1Z += md.invMAng1Z * imp; + av2X += md.invMAng2X * -imp; + av2Y += md.invMAng2Y * -imp; + av2Z += md.invMAng2Z * -imp; + angularSet = true; + } + } + if(linearSet) { + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + } + if(angularSet) { + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + let _this = this.velBoundarySelector; + let i = 0; + while(_this.indices[i] != idx) ++i; + while(i > 0) { + let tmp = _this.indices[i]; + _this.indices[i] = _this.indices[i - 1]; + _this.indices[i - 1] = tmp; + --i; + } + solved = true; + break; + } + } + if(!solved) { + console.log("src/oimo/dynamics/constraint/solver/direct/DirectJointConstraintSolver.hx:335:","could not find solution. (velocity)"); + return; + } + } + postSolveVelocity(timeStep) { + let linX; + let linY; + let linZ; + let angX; + let angY; + let angZ; + linX = 0; + linY = 0; + linZ = 0; + angX = 0; + angY = 0; + angZ = 0; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let row = this.info.rows[_g++]; + let imp = row.impulse; + let j = row.jacobian; + if((j.flag & 1) != 0) { + linX += j.lin1X * imp.impulse; + linY += j.lin1Y * imp.impulse; + linZ += j.lin1Z * imp.impulse; + } else if((j.flag & 2) != 0) { + angX += j.ang1X * imp.impulse; + angY += j.ang1Y * imp.impulse; + angZ += j.ang1Z * imp.impulse; + } + } + this.joint._appliedForceX = linX * timeStep.invDt; + this.joint._appliedForceY = linY * timeStep.invDt; + this.joint._appliedForceZ = linZ * timeStep.invDt; + this.joint._appliedTorqueX = angX * timeStep.invDt; + this.joint._appliedTorqueY = angY * timeStep.invDt; + this.joint._appliedTorqueZ = angZ * timeStep.invDt; + } + preSolvePosition(timeStep) { + this.joint._syncAnchors(); + this.joint._getPositionSolverInfo(this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + this.massMatrix.computeInvMass(this.info,this.massData); + let _this = this.boundaryBuilder; + _this.numBoundaries = 0; + let _this1 = _this.bbInfo; + _this1.numBounded = 0; + _this1.numUnbounded = 0; + _this.buildBoundariesRecursive(this.info,0); + let _this2 = this.posBoundarySelector; + let size = this.boundaryBuilder.numBoundaries; + let numSmaller = 0; + let numGreater = 0; + let _g = 0; + let _g1 = _this2.n; + while(_g < _g1) { + let idx = _this2.indices[_g++]; + if(idx < size) { + _this2.tmpIndices[numSmaller] = idx; + ++numSmaller; + } else { + _this2.tmpIndices[size + numGreater] = idx; + ++numGreater; + } + } + let tmp = _this2.indices; + _this2.indices = _this2.tmpIndices; + _this2.tmpIndices = tmp; + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) this.info.rows[_g2++].impulse.impulseP = 0; + } + solvePositionSplitImpulse() { + let numRows = this.info.numRows; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._pseudoVelX; + lv1Y = this._b1._pseudoVelY; + lv1Z = this._b1._pseudoVelZ; + lv2X = this._b2._pseudoVelX; + lv2Y = this._b2._pseudoVelY; + lv2Z = this._b2._pseudoVelZ; + av1X = this._b1._angPseudoVelX; + av1Y = this._b1._angPseudoVelY; + av1Z = this._b1._angPseudoVelZ; + av2X = this._b2._angPseudoVelX; + av2Y = this._b2._angPseudoVelY; + av2Z = this._b2._angPseudoVelZ; + let _g = 0; + while(_g < numRows) { + let i = _g++; + let row = this.info.rows[i]; + let j = row.jacobian; + let relVel = 0; + relVel += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + relVel -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + relVel += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + relVel -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + this.relVels[i] = relVel; + this.impulses[i] = row.impulse.impulseP; + } + let solved = false; + let _g1 = 0; + let _g2 = this.boundaryBuilder.numBoundaries; + while(_g1 < _g2) { + let idx = this.posBoundarySelector.indices[_g1++]; + if(this.boundaryBuilder.boundaries[idx].computeImpulses(this.info,this.massMatrix,this.relVels,this.impulses,this.dImpulses,oimo.common.Setting.positionSplitImpulseBaumgarte,false)) { + let _g = 0; + while(_g < numRows) { + let j = _g++; + this.info.rows[j].impulse.impulseP += this.dImpulses[j]; + } + let impulses = this.dImpulses; + let linearSet = false; + let angularSet = false; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._pseudoVelX; + lv1Y = this._b1._pseudoVelY; + lv1Z = this._b1._pseudoVelZ; + lv2X = this._b2._pseudoVelX; + lv2Y = this._b2._pseudoVelY; + lv2Z = this._b2._pseudoVelZ; + av1X = this._b1._angPseudoVelX; + av1Y = this._b1._angPseudoVelY; + av1Z = this._b1._angPseudoVelZ; + av2X = this._b2._angPseudoVelX; + av2Y = this._b2._angPseudoVelY; + av2Z = this._b2._angPseudoVelZ; + let _g1 = 0; + let _g2 = this.info.numRows; + while(_g1 < _g2) { + let i = _g1++; + let j = this.info.rows[i].jacobian; + let md = this.massData[i]; + let imp = impulses[i]; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * imp; + lv1Y += md.invMLin1Y * imp; + lv1Z += md.invMLin1Z * imp; + lv2X += md.invMLin2X * -imp; + lv2Y += md.invMLin2Y * -imp; + lv2Z += md.invMLin2Z * -imp; + linearSet = true; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * imp; + av1Y += md.invMAng1Y * imp; + av1Z += md.invMAng1Z * imp; + av2X += md.invMAng2X * -imp; + av2Y += md.invMAng2Y * -imp; + av2Z += md.invMAng2Z * -imp; + angularSet = true; + } + } + if(linearSet) { + this._b1._pseudoVelX = lv1X; + this._b1._pseudoVelY = lv1Y; + this._b1._pseudoVelZ = lv1Z; + this._b2._pseudoVelX = lv2X; + this._b2._pseudoVelY = lv2Y; + this._b2._pseudoVelZ = lv2Z; + } + if(angularSet) { + this._b1._angPseudoVelX = av1X; + this._b1._angPseudoVelY = av1Y; + this._b1._angPseudoVelZ = av1Z; + this._b2._angPseudoVelX = av2X; + this._b2._angPseudoVelY = av2Y; + this._b2._angPseudoVelZ = av2Z; + } + let _this = this.posBoundarySelector; + let i = 0; + while(_this.indices[i] != idx) ++i; + while(i > 0) { + let tmp = _this.indices[i]; + _this.indices[i] = _this.indices[i - 1]; + _this.indices[i - 1] = tmp; + --i; + } + solved = true; + break; + } + } + if(!solved) { + console.log("src/oimo/dynamics/constraint/solver/direct/DirectJointConstraintSolver.hx:450:","could not find solution. (split impulse)"); + return; + } + } + solvePositionNgs(timeStep) { + this.joint._syncAnchors(); + this.joint._getPositionSolverInfo(this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + this.massMatrix.computeInvMass(this.info,this.massData); + let _this = this.boundaryBuilder; + _this.numBoundaries = 0; + let _this1 = _this.bbInfo; + _this1.numBounded = 0; + _this1.numUnbounded = 0; + _this.buildBoundariesRecursive(this.info,0); + let _this2 = this.posBoundarySelector; + let size = this.boundaryBuilder.numBoundaries; + let numSmaller = 0; + let numGreater = 0; + let _g = 0; + let _g1 = _this2.n; + while(_g < _g1) { + let idx = _this2.indices[_g++]; + if(idx < size) { + _this2.tmpIndices[numSmaller] = idx; + ++numSmaller; + } else { + _this2.tmpIndices[size + numGreater] = idx; + ++numGreater; + } + } + let tmp = _this2.indices; + _this2.indices = _this2.tmpIndices; + _this2.tmpIndices = tmp; + let numRows = this.info.numRows; + let _g2 = 0; + while(_g2 < numRows) { + let i = _g2++; + let imp = this.info.rows[i].impulse; + this.relVels[i] = 0; + this.impulses[i] = imp.impulseP; + } + let solved = false; + let _g3 = 0; + let _g4 = this.boundaryBuilder.numBoundaries; + while(_g3 < _g4) { + let idx = this.posBoundarySelector.indices[_g3++]; + if(this.boundaryBuilder.boundaries[idx].computeImpulses(this.info,this.massMatrix,this.relVels,this.impulses,this.dImpulses,oimo.common.Setting.positionNgsBaumgarte,false)) { + let _g = 0; + while(_g < numRows) { + let j = _g++; + this.info.rows[j].impulse.impulseP += this.dImpulses[j]; + } + let impulses = this.dImpulses; + let linearSet = false; + let angularSet = false; + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = 0; + lv1Y = 0; + lv1Z = 0; + lv2X = 0; + lv2Y = 0; + lv2Z = 0; + av1X = 0; + av1Y = 0; + av1Z = 0; + av2X = 0; + av2Y = 0; + av2Z = 0; + let _g1 = 0; + let _g2 = this.info.numRows; + while(_g1 < _g2) { + let i = _g1++; + let j = this.info.rows[i].jacobian; + let md = this.massData[i]; + let imp = impulses[i]; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * imp; + lv1Y += md.invMLin1Y * imp; + lv1Z += md.invMLin1Z * imp; + lv2X += md.invMLin2X * -imp; + lv2Y += md.invMLin2Y * -imp; + lv2Z += md.invMLin2Z * -imp; + linearSet = true; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * imp; + av1Y += md.invMAng1Y * imp; + av1Z += md.invMAng1Z * imp; + av2X += md.invMAng2X * -imp; + av2Y += md.invMAng2Y * -imp; + av2Z += md.invMAng2Z * -imp; + angularSet = true; + } + } + if(linearSet) { + let _this = this._b1; + _this._transform._positionX += lv1X; + _this._transform._positionY += lv1Y; + _this._transform._positionZ += lv1Z; + let _this1 = this._b2; + _this1._transform._positionX += lv2X; + _this1._transform._positionY += lv2Y; + _this1._transform._positionZ += lv2Z; + } + if(angularSet) { + let _this = this._b1; + let theta = Math.sqrt(av1X * av1X + av1Y * av1Y + av1Z * av1Z); + let halfTheta = theta * 0.5; + let rotationToSinAxisFactor; + let cosHalfTheta; + if(halfTheta < 0.5) { + let ht2 = halfTheta * halfTheta; + rotationToSinAxisFactor = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor = Math.sin(halfTheta) / theta; + cosHalfTheta = Math.cos(halfTheta); + } + let sinAxisX; + let sinAxisY; + let sinAxisZ; + sinAxisX = av1X * rotationToSinAxisFactor; + sinAxisY = av1Y * rotationToSinAxisFactor; + sinAxisZ = av1Z * rotationToSinAxisFactor; + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = sinAxisX; + dqY = sinAxisY; + dqZ = sinAxisZ; + dqW = cosHalfTheta; + let qX; + let qY; + let qZ; + let qW; + let e00 = _this._transform._rotation00; + let e11 = _this._transform._rotation11; + let e22 = _this._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + qW = 0.5 * s; + s = 0.5 / s; + qX = (_this._transform._rotation21 - _this._transform._rotation12) * s; + qY = (_this._transform._rotation02 - _this._transform._rotation20) * s; + qZ = (_this._transform._rotation10 - _this._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + qX = 0.5 * s; + s = 0.5 / s; + qY = (_this._transform._rotation01 + _this._transform._rotation10) * s; + qZ = (_this._transform._rotation02 + _this._transform._rotation20) * s; + qW = (_this._transform._rotation21 - _this._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this._transform._rotation02 + _this._transform._rotation20) * s; + qY = (_this._transform._rotation12 + _this._transform._rotation21) * s; + qW = (_this._transform._rotation10 - _this._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + qY = 0.5 * s; + s = 0.5 / s; + qX = (_this._transform._rotation01 + _this._transform._rotation10) * s; + qZ = (_this._transform._rotation12 + _this._transform._rotation21) * s; + qW = (_this._transform._rotation02 - _this._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this._transform._rotation02 + _this._transform._rotation20) * s; + qY = (_this._transform._rotation12 + _this._transform._rotation21) * s; + qW = (_this._transform._rotation10 - _this._transform._rotation01) * s; + } + qX = dqW * qX + dqX * qW + dqY * qZ - dqZ * qY; + qY = dqW * qY - dqX * qZ + dqY * qW + dqZ * qX; + qZ = dqW * qZ + dqX * qY - dqY * qX + dqZ * qW; + qW = dqW * qW - dqX * qX - dqY * qY - dqZ * qZ; + let l = qX * qX + qY * qY + qZ * qZ + qW * qW; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + qX *= l; + qY *= l; + qZ *= l; + qW *= l; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + _this._transform._rotation00 = 1 - yy - zz; + _this._transform._rotation01 = xy - wz; + _this._transform._rotation02 = xz + wy; + _this._transform._rotation10 = xy + wz; + _this._transform._rotation11 = 1 - xx - zz; + _this._transform._rotation12 = yz - wx; + _this._transform._rotation20 = xz - wy; + _this._transform._rotation21 = yz + wx; + _this._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = _this._transform._rotation00 * _this._invLocalInertia00 + _this._transform._rotation01 * _this._invLocalInertia10 + _this._transform._rotation02 * _this._invLocalInertia20; + __tmp__01 = _this._transform._rotation00 * _this._invLocalInertia01 + _this._transform._rotation01 * _this._invLocalInertia11 + _this._transform._rotation02 * _this._invLocalInertia21; + __tmp__02 = _this._transform._rotation00 * _this._invLocalInertia02 + _this._transform._rotation01 * _this._invLocalInertia12 + _this._transform._rotation02 * _this._invLocalInertia22; + __tmp__10 = _this._transform._rotation10 * _this._invLocalInertia00 + _this._transform._rotation11 * _this._invLocalInertia10 + _this._transform._rotation12 * _this._invLocalInertia20; + __tmp__11 = _this._transform._rotation10 * _this._invLocalInertia01 + _this._transform._rotation11 * _this._invLocalInertia11 + _this._transform._rotation12 * _this._invLocalInertia21; + __tmp__12 = _this._transform._rotation10 * _this._invLocalInertia02 + _this._transform._rotation11 * _this._invLocalInertia12 + _this._transform._rotation12 * _this._invLocalInertia22; + __tmp__20 = _this._transform._rotation20 * _this._invLocalInertia00 + _this._transform._rotation21 * _this._invLocalInertia10 + _this._transform._rotation22 * _this._invLocalInertia20; + __tmp__21 = _this._transform._rotation20 * _this._invLocalInertia01 + _this._transform._rotation21 * _this._invLocalInertia11 + _this._transform._rotation22 * _this._invLocalInertia21; + __tmp__22 = _this._transform._rotation20 * _this._invLocalInertia02 + _this._transform._rotation21 * _this._invLocalInertia12 + _this._transform._rotation22 * _this._invLocalInertia22; + _this._invInertia00 = __tmp__00; + _this._invInertia01 = __tmp__01; + _this._invInertia02 = __tmp__02; + _this._invInertia10 = __tmp__10; + _this._invInertia11 = __tmp__11; + _this._invInertia12 = __tmp__12; + _this._invInertia20 = __tmp__20; + _this._invInertia21 = __tmp__21; + _this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = _this._invInertia00 * _this._transform._rotation00 + _this._invInertia01 * _this._transform._rotation01 + _this._invInertia02 * _this._transform._rotation02; + __tmp__011 = _this._invInertia00 * _this._transform._rotation10 + _this._invInertia01 * _this._transform._rotation11 + _this._invInertia02 * _this._transform._rotation12; + __tmp__021 = _this._invInertia00 * _this._transform._rotation20 + _this._invInertia01 * _this._transform._rotation21 + _this._invInertia02 * _this._transform._rotation22; + __tmp__101 = _this._invInertia10 * _this._transform._rotation00 + _this._invInertia11 * _this._transform._rotation01 + _this._invInertia12 * _this._transform._rotation02; + __tmp__111 = _this._invInertia10 * _this._transform._rotation10 + _this._invInertia11 * _this._transform._rotation11 + _this._invInertia12 * _this._transform._rotation12; + __tmp__121 = _this._invInertia10 * _this._transform._rotation20 + _this._invInertia11 * _this._transform._rotation21 + _this._invInertia12 * _this._transform._rotation22; + __tmp__201 = _this._invInertia20 * _this._transform._rotation00 + _this._invInertia21 * _this._transform._rotation01 + _this._invInertia22 * _this._transform._rotation02; + __tmp__211 = _this._invInertia20 * _this._transform._rotation10 + _this._invInertia21 * _this._transform._rotation11 + _this._invInertia22 * _this._transform._rotation12; + __tmp__221 = _this._invInertia20 * _this._transform._rotation20 + _this._invInertia21 * _this._transform._rotation21 + _this._invInertia22 * _this._transform._rotation22; + _this._invInertia00 = __tmp__001; + _this._invInertia01 = __tmp__011; + _this._invInertia02 = __tmp__021; + _this._invInertia10 = __tmp__101; + _this._invInertia11 = __tmp__111; + _this._invInertia12 = __tmp__121; + _this._invInertia20 = __tmp__201; + _this._invInertia21 = __tmp__211; + _this._invInertia22 = __tmp__221; + _this._invInertia00 *= _this._rotFactor.x; + _this._invInertia01 *= _this._rotFactor.x; + _this._invInertia02 *= _this._rotFactor.x; + _this._invInertia10 *= _this._rotFactor.y; + _this._invInertia11 *= _this._rotFactor.y; + _this._invInertia12 *= _this._rotFactor.y; + _this._invInertia20 *= _this._rotFactor.z; + _this._invInertia21 *= _this._rotFactor.z; + _this._invInertia22 *= _this._rotFactor.z; + let _this1 = this._b2; + let theta1 = Math.sqrt(av2X * av2X + av2Y * av2Y + av2Z * av2Z); + let halfTheta1 = theta1 * 0.5; + let rotationToSinAxisFactor1; + let cosHalfTheta1; + if(halfTheta1 < 0.5) { + let ht2 = halfTheta1 * halfTheta1; + rotationToSinAxisFactor1 = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta1 = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor1 = Math.sin(halfTheta1) / theta1; + cosHalfTheta1 = Math.cos(halfTheta1); + } + let sinAxisX1; + let sinAxisY1; + let sinAxisZ1; + sinAxisX1 = av2X * rotationToSinAxisFactor1; + sinAxisY1 = av2Y * rotationToSinAxisFactor1; + sinAxisZ1 = av2Z * rotationToSinAxisFactor1; + let dqX1; + let dqY1; + let dqZ1; + let dqW1; + dqX1 = sinAxisX1; + dqY1 = sinAxisY1; + dqZ1 = sinAxisZ1; + dqW1 = cosHalfTheta1; + let qX1; + let qY1; + let qZ1; + let qW1; + let e001 = _this1._transform._rotation00; + let e111 = _this1._transform._rotation11; + let e221 = _this1._transform._rotation22; + let t1 = e001 + e111 + e221; + let s1; + if(t1 > 0) { + s1 = Math.sqrt(t1 + 1); + qW1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this1._transform._rotation21 - _this1._transform._rotation12) * s1; + qY1 = (_this1._transform._rotation02 - _this1._transform._rotation20) * s1; + qZ1 = (_this1._transform._rotation10 - _this1._transform._rotation01) * s1; + } else if(e001 > e111) { + if(e001 > e221) { + s1 = Math.sqrt(e001 - e111 - e221 + 1); + qX1 = 0.5 * s1; + s1 = 0.5 / s1; + qY1 = (_this1._transform._rotation01 + _this1._transform._rotation10) * s1; + qZ1 = (_this1._transform._rotation02 + _this1._transform._rotation20) * s1; + qW1 = (_this1._transform._rotation21 - _this1._transform._rotation12) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this1._transform._rotation02 + _this1._transform._rotation20) * s1; + qY1 = (_this1._transform._rotation12 + _this1._transform._rotation21) * s1; + qW1 = (_this1._transform._rotation10 - _this1._transform._rotation01) * s1; + } + } else if(e111 > e221) { + s1 = Math.sqrt(e111 - e221 - e001 + 1); + qY1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this1._transform._rotation01 + _this1._transform._rotation10) * s1; + qZ1 = (_this1._transform._rotation12 + _this1._transform._rotation21) * s1; + qW1 = (_this1._transform._rotation02 - _this1._transform._rotation20) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this1._transform._rotation02 + _this1._transform._rotation20) * s1; + qY1 = (_this1._transform._rotation12 + _this1._transform._rotation21) * s1; + qW1 = (_this1._transform._rotation10 - _this1._transform._rotation01) * s1; + } + qX1 = dqW1 * qX1 + dqX1 * qW1 + dqY1 * qZ1 - dqZ1 * qY1; + qY1 = dqW1 * qY1 - dqX1 * qZ1 + dqY1 * qW1 + dqZ1 * qX1; + qZ1 = dqW1 * qZ1 + dqX1 * qY1 - dqY1 * qX1 + dqZ1 * qW1; + qW1 = dqW1 * qW1 - dqX1 * qX1 - dqY1 * qY1 - dqZ1 * qZ1; + let l1 = qX1 * qX1 + qY1 * qY1 + qZ1 * qZ1 + qW1 * qW1; + if(l1 > 1e-32) { + l1 = 1 / Math.sqrt(l1); + } + qX1 *= l1; + qY1 *= l1; + qZ1 *= l1; + qW1 *= l1; + let x1 = qX1; + let y1 = qY1; + let z1 = qZ1; + let w1 = qW1; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + _this1._transform._rotation00 = 1 - yy1 - zz1; + _this1._transform._rotation01 = xy1 - wz1; + _this1._transform._rotation02 = xz1 + wy1; + _this1._transform._rotation10 = xy1 + wz1; + _this1._transform._rotation11 = 1 - xx1 - zz1; + _this1._transform._rotation12 = yz1 - wx1; + _this1._transform._rotation20 = xz1 - wy1; + _this1._transform._rotation21 = yz1 + wx1; + _this1._transform._rotation22 = 1 - xx1 - yy1; + let __tmp__002; + let __tmp__012; + let __tmp__022; + let __tmp__102; + let __tmp__112; + let __tmp__122; + let __tmp__202; + let __tmp__212; + let __tmp__222; + __tmp__002 = _this1._transform._rotation00 * _this1._invLocalInertia00 + _this1._transform._rotation01 * _this1._invLocalInertia10 + _this1._transform._rotation02 * _this1._invLocalInertia20; + __tmp__012 = _this1._transform._rotation00 * _this1._invLocalInertia01 + _this1._transform._rotation01 * _this1._invLocalInertia11 + _this1._transform._rotation02 * _this1._invLocalInertia21; + __tmp__022 = _this1._transform._rotation00 * _this1._invLocalInertia02 + _this1._transform._rotation01 * _this1._invLocalInertia12 + _this1._transform._rotation02 * _this1._invLocalInertia22; + __tmp__102 = _this1._transform._rotation10 * _this1._invLocalInertia00 + _this1._transform._rotation11 * _this1._invLocalInertia10 + _this1._transform._rotation12 * _this1._invLocalInertia20; + __tmp__112 = _this1._transform._rotation10 * _this1._invLocalInertia01 + _this1._transform._rotation11 * _this1._invLocalInertia11 + _this1._transform._rotation12 * _this1._invLocalInertia21; + __tmp__122 = _this1._transform._rotation10 * _this1._invLocalInertia02 + _this1._transform._rotation11 * _this1._invLocalInertia12 + _this1._transform._rotation12 * _this1._invLocalInertia22; + __tmp__202 = _this1._transform._rotation20 * _this1._invLocalInertia00 + _this1._transform._rotation21 * _this1._invLocalInertia10 + _this1._transform._rotation22 * _this1._invLocalInertia20; + __tmp__212 = _this1._transform._rotation20 * _this1._invLocalInertia01 + _this1._transform._rotation21 * _this1._invLocalInertia11 + _this1._transform._rotation22 * _this1._invLocalInertia21; + __tmp__222 = _this1._transform._rotation20 * _this1._invLocalInertia02 + _this1._transform._rotation21 * _this1._invLocalInertia12 + _this1._transform._rotation22 * _this1._invLocalInertia22; + _this1._invInertia00 = __tmp__002; + _this1._invInertia01 = __tmp__012; + _this1._invInertia02 = __tmp__022; + _this1._invInertia10 = __tmp__102; + _this1._invInertia11 = __tmp__112; + _this1._invInertia12 = __tmp__122; + _this1._invInertia20 = __tmp__202; + _this1._invInertia21 = __tmp__212; + _this1._invInertia22 = __tmp__222; + let __tmp__003; + let __tmp__013; + let __tmp__023; + let __tmp__103; + let __tmp__113; + let __tmp__123; + let __tmp__203; + let __tmp__213; + let __tmp__223; + __tmp__003 = _this1._invInertia00 * _this1._transform._rotation00 + _this1._invInertia01 * _this1._transform._rotation01 + _this1._invInertia02 * _this1._transform._rotation02; + __tmp__013 = _this1._invInertia00 * _this1._transform._rotation10 + _this1._invInertia01 * _this1._transform._rotation11 + _this1._invInertia02 * _this1._transform._rotation12; + __tmp__023 = _this1._invInertia00 * _this1._transform._rotation20 + _this1._invInertia01 * _this1._transform._rotation21 + _this1._invInertia02 * _this1._transform._rotation22; + __tmp__103 = _this1._invInertia10 * _this1._transform._rotation00 + _this1._invInertia11 * _this1._transform._rotation01 + _this1._invInertia12 * _this1._transform._rotation02; + __tmp__113 = _this1._invInertia10 * _this1._transform._rotation10 + _this1._invInertia11 * _this1._transform._rotation11 + _this1._invInertia12 * _this1._transform._rotation12; + __tmp__123 = _this1._invInertia10 * _this1._transform._rotation20 + _this1._invInertia11 * _this1._transform._rotation21 + _this1._invInertia12 * _this1._transform._rotation22; + __tmp__203 = _this1._invInertia20 * _this1._transform._rotation00 + _this1._invInertia21 * _this1._transform._rotation01 + _this1._invInertia22 * _this1._transform._rotation02; + __tmp__213 = _this1._invInertia20 * _this1._transform._rotation10 + _this1._invInertia21 * _this1._transform._rotation11 + _this1._invInertia22 * _this1._transform._rotation12; + __tmp__223 = _this1._invInertia20 * _this1._transform._rotation20 + _this1._invInertia21 * _this1._transform._rotation21 + _this1._invInertia22 * _this1._transform._rotation22; + _this1._invInertia00 = __tmp__003; + _this1._invInertia01 = __tmp__013; + _this1._invInertia02 = __tmp__023; + _this1._invInertia10 = __tmp__103; + _this1._invInertia11 = __tmp__113; + _this1._invInertia12 = __tmp__123; + _this1._invInertia20 = __tmp__203; + _this1._invInertia21 = __tmp__213; + _this1._invInertia22 = __tmp__223; + _this1._invInertia00 *= _this1._rotFactor.x; + _this1._invInertia01 *= _this1._rotFactor.x; + _this1._invInertia02 *= _this1._rotFactor.x; + _this1._invInertia10 *= _this1._rotFactor.y; + _this1._invInertia11 *= _this1._rotFactor.y; + _this1._invInertia12 *= _this1._rotFactor.y; + _this1._invInertia20 *= _this1._rotFactor.z; + _this1._invInertia21 *= _this1._rotFactor.z; + _this1._invInertia22 *= _this1._rotFactor.z; + } + let _this = this.posBoundarySelector; + let i = 0; + while(_this.indices[i] != idx) ++i; + while(i > 0) { + let tmp = _this.indices[i]; + _this.indices[i] = _this.indices[i - 1]; + _this.indices[i - 1] = tmp; + --i; + } + solved = true; + break; + } + } + if(!solved) { + console.log("src/oimo/dynamics/constraint/solver/direct/DirectJointConstraintSolver.hx:502:","could not find solution. (NGS)"); + return; + } + } + postSolve() { + this.joint._syncAnchors(); + this.joint._checkDestruction(); + } +} +oimo.dynamics.constraint.solver.direct.MassMatrix = class oimo_dynamics_constraint_solver_direct_MassMatrix { + constructor(size) { + this._size = size; + this.tmpMatrix = new Array(this._size); + this._invMass = new Array(this._size); + this._invMassWithoutCfm = new Array(this._size); + let _g = 0; + let _g1 = this._size; + while(_g < _g1) { + let i = _g++; + this.tmpMatrix[i] = new Array(this._size); + this._invMass[i] = new Array(this._size); + this._invMassWithoutCfm[i] = new Array(this._size); + let _g1 = 0; + let _g2 = this._size; + while(_g1 < _g2) { + let j = _g1++; + this.tmpMatrix[i][j] = 0; + this._invMass[i][j] = 0; + this._invMassWithoutCfm[i][j] = 0; + } + } + this._maxSubmatrixId = 1 << this._size; + this._cacheComputed = new Array(this._maxSubmatrixId); + this._cachedSubmatrices = new Array(this._maxSubmatrixId); + let _g2 = 0; + let _g3 = this._maxSubmatrixId; + while(_g2 < _g3) { + let i = _g2++; + let t; + t = (i & 85) + (i >> 1 & 85); + t = (t & 51) + (t >> 2 & 51); + t = (t & 15) + (t >> 4 & 15); + let matrixSize = t; + let subMatrix = new Array(matrixSize); + let _g = 0; + while(_g < matrixSize) { + let j = _g++; + subMatrix[j] = new Array(matrixSize); + let _g1 = 0; + while(_g1 < matrixSize) subMatrix[j][_g1++] = 0; + } + this._cacheComputed[i] = false; + this._cachedSubmatrices[i] = subMatrix; + } + } + computeSubmatrix(id,indices,size) { + let _g = 0; + while(_g < size) { + let i = _g++; + let ii = indices[i]; + let _g1 = 0; + while(_g1 < size) { + let j = _g1++; + this.tmpMatrix[i][j] = this._invMass[ii][indices[j]]; + } + } + let src = this.tmpMatrix; + let dst = this._cachedSubmatrices[id]; + let srci; + let dsti; + let srcj; + let dstj; + let diag; + switch(size) { + case 4: + srci = src[0]; + dsti = dst[0]; + diag = 1 / srci[0]; + dsti[0] = diag; + srci[1] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srcj = src[1]; + dstj = dst[1]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srci = src[1]; + dsti = dst[1]; + diag = 1 / srci[1]; + dsti[1] = diag; + dsti[0] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srci = src[2]; + dsti = dst[2]; + diag = 1 / srci[2]; + dsti[2] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + srci[3] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srci = src[3]; + dsti = dst[3]; + diag = 1 / srci[3]; + dsti[3] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[3]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + dsti = dst[1]; + dst[0][1] = dsti[0]; + dsti = dst[2]; + dst[0][2] = dsti[0]; + dst[1][2] = dsti[1]; + dsti = dst[3]; + dst[0][3] = dsti[0]; + dst[1][3] = dsti[1]; + dst[2][3] = dsti[2]; + break; + case 5: + srci = src[0]; + dsti = dst[0]; + diag = 1 / srci[0]; + dsti[0] = diag; + srci[1] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srcj = src[1]; + dstj = dst[1]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srci = src[1]; + dsti = dst[1]; + diag = 1 / srci[1]; + dsti[1] = diag; + dsti[0] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srci = src[2]; + dsti = dst[2]; + diag = 1 / srci[2]; + dsti[2] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srci = src[3]; + dsti = dst[3]; + diag = 1 / srci[3]; + dsti[3] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + srci[4] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + dstj[3] = -diag * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srci = src[4]; + dsti = dst[4]; + diag = 1 / srci[4]; + dsti[4] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + dsti[3] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[4]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + dstj[2] -= dsti[2] * srcj[4]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + dstj[2] -= dsti[2] * srcj[4]; + dstj[3] -= dsti[3] * srcj[4]; + dsti = dst[1]; + dst[0][1] = dsti[0]; + dsti = dst[2]; + dst[0][2] = dsti[0]; + dst[1][2] = dsti[1]; + dsti = dst[3]; + dst[0][3] = dsti[0]; + dst[1][3] = dsti[1]; + dst[2][3] = dsti[2]; + dsti = dst[4]; + dst[0][4] = dsti[0]; + dst[1][4] = dsti[1]; + dst[2][4] = dsti[2]; + dst[3][4] = dsti[3]; + break; + case 6: + srci = src[0]; + dsti = dst[0]; + diag = 1 / srci[0]; + dsti[0] = diag; + srci[1] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srci[5] *= diag; + srcj = src[1]; + dstj = dst[1]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj[5] -= srci[5] * srcj[0]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj[5] -= srci[5] * srcj[0]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj[5] -= srci[5] * srcj[0]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj[5] -= srci[5] * srcj[0]; + srcj = src[5]; + dstj = dst[5]; + dstj[0] = -diag * srcj[0]; + srcj[1] -= srci[1] * srcj[0]; + srcj[2] -= srci[2] * srcj[0]; + srcj[3] -= srci[3] * srcj[0]; + srcj[4] -= srci[4] * srcj[0]; + srcj[5] -= srci[5] * srcj[0]; + srci = src[1]; + dsti = dst[1]; + diag = 1 / srci[1]; + dsti[1] = diag; + dsti[0] *= diag; + srci[2] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srci[5] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj[5] -= srci[5] * srcj[1]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj[5] -= srci[5] * srcj[1]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj[5] -= srci[5] * srcj[1]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj[5] -= srci[5] * srcj[1]; + srcj = src[5]; + dstj = dst[5]; + dstj[0] -= dsti[0] * srcj[1]; + dstj[1] = -diag * srcj[1]; + srcj[2] -= srci[2] * srcj[1]; + srcj[3] -= srci[3] * srcj[1]; + srcj[4] -= srci[4] * srcj[1]; + srcj[5] -= srci[5] * srcj[1]; + srci = src[2]; + dsti = dst[2]; + diag = 1 / srci[2]; + dsti[2] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + srci[3] *= diag; + srci[4] *= diag; + srci[5] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj[5] -= srci[5] * srcj[2]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj[5] -= srci[5] * srcj[2]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj[5] -= srci[5] * srcj[2]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj[5] -= srci[5] * srcj[2]; + srcj = src[5]; + dstj = dst[5]; + dstj[0] -= dsti[0] * srcj[2]; + dstj[1] -= dsti[1] * srcj[2]; + dstj[2] = -diag * srcj[2]; + srcj[3] -= srci[3] * srcj[2]; + srcj[4] -= srci[4] * srcj[2]; + srcj[5] -= srci[5] * srcj[2]; + srci = src[3]; + dsti = dst[3]; + diag = 1 / srci[3]; + dsti[3] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + srci[4] *= diag; + srci[5] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj[5] -= srci[5] * srcj[3]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj[5] -= srci[5] * srcj[3]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj[5] -= srci[5] * srcj[3]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + dstj[3] = -diag * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj[5] -= srci[5] * srcj[3]; + srcj = src[5]; + dstj = dst[5]; + dstj[0] -= dsti[0] * srcj[3]; + dstj[1] -= dsti[1] * srcj[3]; + dstj[2] -= dsti[2] * srcj[3]; + dstj[3] = -diag * srcj[3]; + srcj[4] -= srci[4] * srcj[3]; + srcj[5] -= srci[5] * srcj[3]; + srci = src[4]; + dsti = dst[4]; + diag = 1 / srci[4]; + dsti[4] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + dsti[3] *= diag; + srci[5] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[4]; + srcj[5] -= srci[5] * srcj[4]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + srcj[5] -= srci[5] * srcj[4]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + dstj[2] -= dsti[2] * srcj[4]; + srcj[5] -= srci[5] * srcj[4]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + dstj[2] -= dsti[2] * srcj[4]; + dstj[3] -= dsti[3] * srcj[4]; + srcj[5] -= srci[5] * srcj[4]; + srcj = src[5]; + dstj = dst[5]; + dstj[0] -= dsti[0] * srcj[4]; + dstj[1] -= dsti[1] * srcj[4]; + dstj[2] -= dsti[2] * srcj[4]; + dstj[3] -= dsti[3] * srcj[4]; + dstj[4] = -diag * srcj[4]; + srcj[5] -= srci[5] * srcj[4]; + srci = src[5]; + dsti = dst[5]; + diag = 1 / srci[5]; + dsti[5] = diag; + dsti[0] *= diag; + dsti[1] *= diag; + dsti[2] *= diag; + dsti[3] *= diag; + dsti[4] *= diag; + srcj = src[0]; + dstj = dst[0]; + dstj[0] -= dsti[0] * srcj[5]; + srcj = src[1]; + dstj = dst[1]; + dstj[0] -= dsti[0] * srcj[5]; + dstj[1] -= dsti[1] * srcj[5]; + srcj = src[2]; + dstj = dst[2]; + dstj[0] -= dsti[0] * srcj[5]; + dstj[1] -= dsti[1] * srcj[5]; + dstj[2] -= dsti[2] * srcj[5]; + srcj = src[3]; + dstj = dst[3]; + dstj[0] -= dsti[0] * srcj[5]; + dstj[1] -= dsti[1] * srcj[5]; + dstj[2] -= dsti[2] * srcj[5]; + dstj[3] -= dsti[3] * srcj[5]; + srcj = src[4]; + dstj = dst[4]; + dstj[0] -= dsti[0] * srcj[5]; + dstj[1] -= dsti[1] * srcj[5]; + dstj[2] -= dsti[2] * srcj[5]; + dstj[3] -= dsti[3] * srcj[5]; + dstj[4] -= dsti[4] * srcj[5]; + dsti = dst[1]; + dst[0][1] = dsti[0]; + dsti = dst[2]; + dst[0][2] = dsti[0]; + dst[1][2] = dsti[1]; + dsti = dst[3]; + dst[0][3] = dsti[0]; + dst[1][3] = dsti[1]; + dst[2][3] = dsti[2]; + dsti = dst[4]; + dst[0][4] = dsti[0]; + dst[1][4] = dsti[1]; + dst[2][4] = dsti[2]; + dst[3][4] = dsti[3]; + dsti = dst[5]; + dst[0][5] = dsti[0]; + dst[1][5] = dsti[1]; + dst[2][5] = dsti[2]; + dst[3][5] = dsti[3]; + dst[4][5] = dsti[4]; + break; + default: + let _g1 = 0; + while(_g1 < size) { + let i = _g1++; + srci = src[i]; + dsti = dst[i]; + let diag = 1 / srci[i]; + dsti[i] = diag; + let _g = 0; + while(_g < i) dsti[_g++] *= diag; + let _g2 = i + 1; + while(_g2 < size) srci[_g2++] *= diag; + let _g3 = 0; + while(_g3 < i) { + let j = _g3++; + srcj = src[j]; + dstj = dst[j]; + let _g = 0; + let _g1 = j + 1; + while(_g < _g1) { + let k = _g++; + dstj[k] -= dsti[k] * srcj[i]; + } + let _g2 = i + 1; + while(_g2 < size) { + let k = _g2++; + srcj[k] -= srci[k] * srcj[i]; + } + } + let _g4 = i + 1; + while(_g4 < size) { + let j = _g4++; + srcj = src[j]; + dstj = dst[j]; + let _g = 0; + while(_g < i) { + let k = _g++; + dstj[k] -= dsti[k] * srcj[i]; + } + dstj[i] = -diag * srcj[i]; + let _g1 = i + 1; + while(_g1 < size) { + let k = _g1++; + srcj[k] -= srci[k] * srcj[i]; + } + } + } + let _g2 = 1; + while(_g2 < size) { + let i = _g2++; + dsti = dst[i]; + let _g = 0; + while(_g < i) { + let j = _g++; + dst[j][i] = dsti[j]; + } + } + } + } + computeInvMass(info,massData) { + let invMass = this._invMass; + let invMassWithoutCfm = this._invMassWithoutCfm; + let numRows = info.numRows; + let b1 = info.b1; + let b2 = info.b2; + let invM1 = b1._invMass; + let invM2 = b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = b1._invInertia00; + invI101 = b1._invInertia01; + invI102 = b1._invInertia02; + invI110 = b1._invInertia10; + invI111 = b1._invInertia11; + invI112 = b1._invInertia12; + invI120 = b1._invInertia20; + invI121 = b1._invInertia21; + invI122 = b1._invInertia22; + invI200 = b2._invInertia00; + invI201 = b2._invInertia01; + invI202 = b2._invInertia02; + invI210 = b2._invInertia10; + invI211 = b2._invInertia11; + invI212 = b2._invInertia12; + invI220 = b2._invInertia20; + invI221 = b2._invInertia21; + invI222 = b2._invInertia22; + let _g = 0; + while(_g < numRows) { + let i = _g++; + let j = info.rows[i].jacobian; + let md = massData[i]; + j.updateSparsity(); + if((j.flag & 1) != 0) { + md.invMLin1X = j.lin1X * invM1; + md.invMLin1Y = j.lin1Y * invM1; + md.invMLin1Z = j.lin1Z * invM1; + md.invMLin2X = j.lin2X * invM2; + md.invMLin2Y = j.lin2Y * invM2; + md.invMLin2Z = j.lin2Z * invM2; + } else { + md.invMLin1X = 0; + md.invMLin1Y = 0; + md.invMLin1Z = 0; + md.invMLin2X = 0; + md.invMLin2Y = 0; + md.invMLin2Z = 0; + } + if((j.flag & 2) != 0) { + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAng1X = __tmp__X; + md.invMAng1Y = __tmp__Y; + md.invMAng1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAng2X = __tmp__X1; + md.invMAng2Y = __tmp__Y1; + md.invMAng2Z = __tmp__Z1; + } else { + md.invMAng1X = 0; + md.invMAng1Y = 0; + md.invMAng1Z = 0; + md.invMAng2X = 0; + md.invMAng2Y = 0; + md.invMAng2Z = 0; + } + } + let _g1 = 0; + while(_g1 < numRows) { + let i = _g1++; + let j1 = info.rows[i].jacobian; + let _g = i; + while(_g < numRows) { + let j = _g++; + let md2 = massData[j]; + let val = j1.lin1X * md2.invMLin1X + j1.lin1Y * md2.invMLin1Y + j1.lin1Z * md2.invMLin1Z + (j1.ang1X * md2.invMAng1X + j1.ang1Y * md2.invMAng1Y + j1.ang1Z * md2.invMAng1Z) + (j1.lin2X * md2.invMLin2X + j1.lin2Y * md2.invMLin2Y + j1.lin2Z * md2.invMLin2Z) + (j1.ang2X * md2.invMAng2X + j1.ang2Y * md2.invMAng2Y + j1.ang2Z * md2.invMAng2Z); + if(i == j) { + invMass[i][j] = val + info.rows[i].cfm; + invMassWithoutCfm[i][j] = val; + md2.mass = val + info.rows[i].cfm; + md2.massWithoutCfm = val; + if(md2.mass != 0) { + md2.mass = 1 / md2.mass; + } + if(md2.massWithoutCfm != 0) { + md2.massWithoutCfm = 1 / md2.massWithoutCfm; + } + } else { + invMass[i][j] = val; + invMass[j][i] = val; + invMassWithoutCfm[i][j] = val; + invMassWithoutCfm[j][i] = val; + } + } + } + let _g2 = 0; + let _g3 = this._maxSubmatrixId; + while(_g2 < _g3) this._cacheComputed[_g2++] = false; + } +} +if(!oimo.dynamics.constraint.solver.pgs) oimo.dynamics.constraint.solver.pgs = {}; +oimo.dynamics.constraint.solver.pgs.PgsContactConstraintSolver = class oimo_dynamics_constraint_solver_pgs_PgsContactConstraintSolver extends oimo.dynamics.constraint.ConstraintSolver { + constructor(constraint) { + super(); + this.constraint = constraint; + this.info = new oimo.dynamics.constraint.info.contact.ContactSolverInfo(); + this.massData = new Array(oimo.common.Setting.maxManifoldPoints); + let _g = 0; + let _g1 = this.massData.length; + while(_g < _g1) this.massData[_g++] = new oimo.dynamics.constraint.solver.common.ContactSolverMassDataRow(); + } + preSolveVelocity(timeStep) { + this.constraint._getVelocitySolverInfo(timeStep,this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let j = row.jacobianN; + md.invMLinN1X = j.lin1X * invM1; + md.invMLinN1Y = j.lin1Y * invM1; + md.invMLinN1Z = j.lin1Z * invM1; + md.invMLinN2X = j.lin2X * invM2; + md.invMLinN2Y = j.lin2Y * invM2; + md.invMLinN2Z = j.lin2Z * invM2; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAngN1X = __tmp__X; + md.invMAngN1Y = __tmp__Y; + md.invMAngN1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAngN2X = __tmp__X1; + md.invMAngN2Y = __tmp__Y1; + md.invMAngN2Z = __tmp__Z1; + md.massN = invM1 + invM2 + (md.invMAngN1X * j.ang1X + md.invMAngN1Y * j.ang1Y + md.invMAngN1Z * j.ang1Z) + (md.invMAngN2X * j.ang2X + md.invMAngN2Y * j.ang2Y + md.invMAngN2Z * j.ang2Z); + if(md.massN != 0) { + md.massN = 1 / md.massN; + } + let jt = row.jacobianT; + let jb = row.jacobianB; + md.invMLinT1X = jt.lin1X * invM1; + md.invMLinT1Y = jt.lin1Y * invM1; + md.invMLinT1Z = jt.lin1Z * invM1; + md.invMLinT2X = jt.lin2X * invM2; + md.invMLinT2Y = jt.lin2Y * invM2; + md.invMLinT2Z = jt.lin2Z * invM2; + md.invMLinB1X = jb.lin1X * invM1; + md.invMLinB1Y = jb.lin1Y * invM1; + md.invMLinB1Z = jb.lin1Z * invM1; + md.invMLinB2X = jb.lin2X * invM2; + md.invMLinB2Y = jb.lin2Y * invM2; + md.invMLinB2Z = jb.lin2Z * invM2; + let __tmp__X2; + let __tmp__Y2; + let __tmp__Z2; + __tmp__X2 = invI100 * jt.ang1X + invI101 * jt.ang1Y + invI102 * jt.ang1Z; + __tmp__Y2 = invI110 * jt.ang1X + invI111 * jt.ang1Y + invI112 * jt.ang1Z; + __tmp__Z2 = invI120 * jt.ang1X + invI121 * jt.ang1Y + invI122 * jt.ang1Z; + md.invMAngT1X = __tmp__X2; + md.invMAngT1Y = __tmp__Y2; + md.invMAngT1Z = __tmp__Z2; + let __tmp__X3; + let __tmp__Y3; + let __tmp__Z3; + __tmp__X3 = invI200 * jt.ang2X + invI201 * jt.ang2Y + invI202 * jt.ang2Z; + __tmp__Y3 = invI210 * jt.ang2X + invI211 * jt.ang2Y + invI212 * jt.ang2Z; + __tmp__Z3 = invI220 * jt.ang2X + invI221 * jt.ang2Y + invI222 * jt.ang2Z; + md.invMAngT2X = __tmp__X3; + md.invMAngT2Y = __tmp__Y3; + md.invMAngT2Z = __tmp__Z3; + let __tmp__X4; + let __tmp__Y4; + let __tmp__Z4; + __tmp__X4 = invI100 * jb.ang1X + invI101 * jb.ang1Y + invI102 * jb.ang1Z; + __tmp__Y4 = invI110 * jb.ang1X + invI111 * jb.ang1Y + invI112 * jb.ang1Z; + __tmp__Z4 = invI120 * jb.ang1X + invI121 * jb.ang1Y + invI122 * jb.ang1Z; + md.invMAngB1X = __tmp__X4; + md.invMAngB1Y = __tmp__Y4; + md.invMAngB1Z = __tmp__Z4; + let __tmp__X5; + let __tmp__Y5; + let __tmp__Z5; + __tmp__X5 = invI200 * jb.ang2X + invI201 * jb.ang2Y + invI202 * jb.ang2Z; + __tmp__Y5 = invI210 * jb.ang2X + invI211 * jb.ang2Y + invI212 * jb.ang2Z; + __tmp__Z5 = invI220 * jb.ang2X + invI221 * jb.ang2Y + invI222 * jb.ang2Z; + md.invMAngB2X = __tmp__X5; + md.invMAngB2Y = __tmp__Y5; + md.invMAngB2Z = __tmp__Z5; + let invMassTB00 = invM1 + invM2 + (md.invMAngT1X * jt.ang1X + md.invMAngT1Y * jt.ang1Y + md.invMAngT1Z * jt.ang1Z) + (md.invMAngT2X * jt.ang2X + md.invMAngT2Y * jt.ang2Y + md.invMAngT2Z * jt.ang2Z); + let invMassTB01 = md.invMAngT1X * jb.ang1X + md.invMAngT1Y * jb.ang1Y + md.invMAngT1Z * jb.ang1Z + (md.invMAngT2X * jb.ang2X + md.invMAngT2Y * jb.ang2Y + md.invMAngT2Z * jb.ang2Z); + let invMassTB11 = invM1 + invM2 + (md.invMAngB1X * jb.ang1X + md.invMAngB1Y * jb.ang1Y + md.invMAngB1Z * jb.ang1Z) + (md.invMAngB2X * jb.ang2X + md.invMAngB2Y * jb.ang2Y + md.invMAngB2Z * jb.ang2Z); + let invDet = invMassTB00 * invMassTB11 - invMassTB01 * invMassTB01; + if(invDet != 0) { + invDet = 1 / invDet; + } + md.massTB00 = invMassTB11 * invDet; + md.massTB01 = -invMassTB01 * invDet; + md.massTB10 = -invMassTB01 * invDet; + md.massTB11 = invMassTB00 * invDet; + } + } + warmStart(timeStep) { + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let imp = row.impulse; + let md = this.massData[i]; + let jt = row.jacobianT; + let jb = row.jacobianB; + let impulseN = imp.impulseN; + let impulseT = imp.impulseLX * jt.lin1X + imp.impulseLY * jt.lin1Y + imp.impulseLZ * jt.lin1Z; + let impulseB = imp.impulseLX * jb.lin1X + imp.impulseLY * jb.lin1Y + imp.impulseLZ * jb.lin1Z; + imp.impulseT = impulseT; + imp.impulseB = impulseB; + imp.impulseN *= timeStep.dtRatio; + imp.impulseT *= timeStep.dtRatio; + imp.impulseB *= timeStep.dtRatio; + lv1X += md.invMLinN1X * impulseN; + lv1Y += md.invMLinN1Y * impulseN; + lv1Z += md.invMLinN1Z * impulseN; + lv1X += md.invMLinT1X * impulseT; + lv1Y += md.invMLinT1Y * impulseT; + lv1Z += md.invMLinT1Z * impulseT; + lv1X += md.invMLinB1X * impulseB; + lv1Y += md.invMLinB1Y * impulseB; + lv1Z += md.invMLinB1Z * impulseB; + lv2X += md.invMLinN2X * -impulseN; + lv2Y += md.invMLinN2Y * -impulseN; + lv2Z += md.invMLinN2Z * -impulseN; + lv2X += md.invMLinT2X * -impulseT; + lv2Y += md.invMLinT2Y * -impulseT; + lv2Z += md.invMLinT2Z * -impulseT; + lv2X += md.invMLinB2X * -impulseB; + lv2Y += md.invMLinB2Y * -impulseB; + lv2Z += md.invMLinB2Z * -impulseB; + av1X += md.invMAngN1X * impulseN; + av1Y += md.invMAngN1Y * impulseN; + av1Z += md.invMAngN1Z * impulseN; + av1X += md.invMAngT1X * impulseT; + av1Y += md.invMAngT1Y * impulseT; + av1Z += md.invMAngT1Z * impulseT; + av1X += md.invMAngB1X * impulseB; + av1Y += md.invMAngB1Y * impulseB; + av1Z += md.invMAngB1Z * impulseB; + av2X += md.invMAngN2X * -impulseN; + av2Y += md.invMAngN2Y * -impulseN; + av2Z += md.invMAngN2Z * -impulseN; + av2X += md.invMAngT2X * -impulseT; + av2Y += md.invMAngT2Y * -impulseT; + av2Z += md.invMAngT2Z * -impulseT; + av2X += md.invMAngB2X * -impulseB; + av2Y += md.invMAngB2Y * -impulseB; + av2Z += md.invMAngB2Z * -impulseB; + } + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + solveVelocity() { + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let rvt = 0; + let j = row.jacobianT; + rvt += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rvt -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rvt += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rvt -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let rvb = 0; + j = row.jacobianB; + rvb += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rvb -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rvb += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rvb -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseT = -(rvt * md.massTB00 + rvb * md.massTB01); + let impulseB = -(rvt * md.massTB10 + rvb * md.massTB11); + let oldImpulseT = imp.impulseT; + let oldImpulseB = imp.impulseB; + imp.impulseT += impulseT; + imp.impulseB += impulseB; + let maxImpulse = row.friction * imp.impulseN; + if(maxImpulse == 0) { + imp.impulseT = 0; + imp.impulseB = 0; + } else { + let impulseLengthSq = imp.impulseT * imp.impulseT + imp.impulseB * imp.impulseB; + if(impulseLengthSq > maxImpulse * maxImpulse) { + let invL = maxImpulse / Math.sqrt(impulseLengthSq); + imp.impulseT *= invL; + imp.impulseB *= invL; + } + } + impulseT = imp.impulseT - oldImpulseT; + impulseB = imp.impulseB - oldImpulseB; + lv1X += md.invMLinT1X * impulseT; + lv1Y += md.invMLinT1Y * impulseT; + lv1Z += md.invMLinT1Z * impulseT; + lv1X += md.invMLinB1X * impulseB; + lv1Y += md.invMLinB1Y * impulseB; + lv1Z += md.invMLinB1Z * impulseB; + lv2X += md.invMLinT2X * -impulseT; + lv2Y += md.invMLinT2Y * -impulseT; + lv2Z += md.invMLinT2Z * -impulseT; + lv2X += md.invMLinB2X * -impulseB; + lv2Y += md.invMLinB2Y * -impulseB; + lv2Z += md.invMLinB2Z * -impulseB; + av1X += md.invMAngT1X * impulseT; + av1Y += md.invMAngT1Y * impulseT; + av1Z += md.invMAngT1Z * impulseT; + av1X += md.invMAngB1X * impulseB; + av1Y += md.invMAngB1Y * impulseB; + av1Z += md.invMAngB1Z * impulseB; + av2X += md.invMAngT2X * -impulseT; + av2Y += md.invMAngT2Y * -impulseT; + av2Z += md.invMAngT2Z * -impulseT; + av2X += md.invMAngB2X * -impulseB; + av2Y += md.invMAngB2Y * -impulseB; + av2Z += md.invMAngB2Z * -impulseB; + } + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) { + let i = _g2++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let rvn = 0; + let j = row.jacobianN; + rvn += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rvn -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rvn += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rvn -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseN = (row.rhs - rvn) * md.massN; + let oldImpulseN = imp.impulseN; + imp.impulseN += impulseN; + if(imp.impulseN < 0) { + imp.impulseN = 0; + } + impulseN = imp.impulseN - oldImpulseN; + lv1X += md.invMLinN1X * impulseN; + lv1Y += md.invMLinN1Y * impulseN; + lv1Z += md.invMLinN1Z * impulseN; + lv2X += md.invMLinN2X * -impulseN; + lv2Y += md.invMLinN2Y * -impulseN; + lv2Z += md.invMLinN2Z * -impulseN; + av1X += md.invMAngN1X * impulseN; + av1Y += md.invMAngN1Y * impulseN; + av1Z += md.invMAngN1Z * impulseN; + av2X += md.invMAngN2X * -impulseN; + av2Y += md.invMAngN2Y * -impulseN; + av2Z += md.invMAngN2Z * -impulseN; + } + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + preSolvePosition(timeStep) { + this.constraint._syncManifold(); + this.constraint._getPositionSolverInfo(this.info); + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let md = this.massData[i]; + let j = this.info.rows[i].jacobianN; + md.invMLinN1X = j.lin1X * invM1; + md.invMLinN1Y = j.lin1Y * invM1; + md.invMLinN1Z = j.lin1Z * invM1; + md.invMLinN2X = j.lin2X * invM2; + md.invMLinN2Y = j.lin2Y * invM2; + md.invMLinN2Z = j.lin2Z * invM2; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAngN1X = __tmp__X; + md.invMAngN1Y = __tmp__Y; + md.invMAngN1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAngN2X = __tmp__X1; + md.invMAngN2Y = __tmp__Y1; + md.invMAngN2Z = __tmp__Z1; + md.massN = invM1 + invM2 + (md.invMAngN1X * j.ang1X + md.invMAngN1Y * j.ang1Y + md.invMAngN1Z * j.ang1Z) + (md.invMAngN2X * j.ang2X + md.invMAngN2Y * j.ang2Y + md.invMAngN2Z * j.ang2Z); + if(md.massN != 0) { + md.massN = 1 / md.massN; + } + } + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) this.info.rows[_g2++].impulse.impulseP = 0; + } + solvePositionSplitImpulse() { + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._pseudoVelX; + lv1Y = this._b1._pseudoVelY; + lv1Z = this._b1._pseudoVelZ; + lv2X = this._b2._pseudoVelX; + lv2Y = this._b2._pseudoVelY; + lv2Z = this._b2._pseudoVelZ; + av1X = this._b1._angPseudoVelX; + av1Y = this._b1._angPseudoVelY; + av1Z = this._b1._angPseudoVelZ; + av2X = this._b2._angPseudoVelX; + av2Y = this._b2._angPseudoVelY; + av2Z = this._b2._angPseudoVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobianN; + let rvn = 0; + rvn += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rvn -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rvn += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rvn -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseP = (row.rhs - rvn) * md.massN * oimo.common.Setting.positionSplitImpulseBaumgarte; + let oldImpulseP = imp.impulseP; + imp.impulseP += impulseP; + if(imp.impulseP < 0) { + imp.impulseP = 0; + } + impulseP = imp.impulseP - oldImpulseP; + lv1X += md.invMLinN1X * impulseP; + lv1Y += md.invMLinN1Y * impulseP; + lv1Z += md.invMLinN1Z * impulseP; + lv2X += md.invMLinN2X * -impulseP; + lv2Y += md.invMLinN2Y * -impulseP; + lv2Z += md.invMLinN2Z * -impulseP; + av1X += md.invMAngN1X * impulseP; + av1Y += md.invMAngN1Y * impulseP; + av1Z += md.invMAngN1Z * impulseP; + av2X += md.invMAngN2X * -impulseP; + av2Y += md.invMAngN2Y * -impulseP; + av2Z += md.invMAngN2Z * -impulseP; + } + this._b1._pseudoVelX = lv1X; + this._b1._pseudoVelY = lv1Y; + this._b1._pseudoVelZ = lv1Z; + this._b2._pseudoVelX = lv2X; + this._b2._pseudoVelY = lv2Y; + this._b2._pseudoVelZ = lv2Z; + this._b1._angPseudoVelX = av1X; + this._b1._angPseudoVelY = av1Y; + this._b1._angPseudoVelZ = av1Z; + this._b2._angPseudoVelX = av2X; + this._b2._angPseudoVelY = av2Y; + this._b2._angPseudoVelZ = av2Z; + } + solvePositionNgs(timeStep) { + this.constraint._syncManifold(); + this.constraint._getPositionSolverInfo(this.info); + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let md = this.massData[i]; + let j = this.info.rows[i].jacobianN; + md.invMLinN1X = j.lin1X * invM1; + md.invMLinN1Y = j.lin1Y * invM1; + md.invMLinN1Z = j.lin1Z * invM1; + md.invMLinN2X = j.lin2X * invM2; + md.invMLinN2Y = j.lin2Y * invM2; + md.invMLinN2Z = j.lin2Z * invM2; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAngN1X = __tmp__X; + md.invMAngN1Y = __tmp__Y; + md.invMAngN1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAngN2X = __tmp__X1; + md.invMAngN2Y = __tmp__Y1; + md.invMAngN2Z = __tmp__Z1; + md.massN = invM1 + invM2 + (md.invMAngN1X * j.ang1X + md.invMAngN1Y * j.ang1Y + md.invMAngN1Z * j.ang1Z) + (md.invMAngN2X * j.ang2X + md.invMAngN2Y * j.ang2Y + md.invMAngN2Z * j.ang2Z); + if(md.massN != 0) { + md.massN = 1 / md.massN; + } + } + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = 0; + lv1Y = 0; + lv1Z = 0; + lv2X = 0; + lv2Y = 0; + lv2Z = 0; + av1X = 0; + av1Y = 0; + av1Z = 0; + av2X = 0; + av2Y = 0; + av2Z = 0; + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) { + let i = _g2++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobianN; + let rvn = 0; + rvn += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rvn -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rvn += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rvn -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseP = (row.rhs - rvn) * md.massN * oimo.common.Setting.positionNgsBaumgarte; + let oldImpulseP = imp.impulseP; + imp.impulseP += impulseP; + if(imp.impulseP < 0) { + imp.impulseP = 0; + } + impulseP = imp.impulseP - oldImpulseP; + lv1X += md.invMLinN1X * impulseP; + lv1Y += md.invMLinN1Y * impulseP; + lv1Z += md.invMLinN1Z * impulseP; + lv2X += md.invMLinN2X * -impulseP; + lv2Y += md.invMLinN2Y * -impulseP; + lv2Z += md.invMLinN2Z * -impulseP; + av1X += md.invMAngN1X * impulseP; + av1Y += md.invMAngN1Y * impulseP; + av1Z += md.invMAngN1Z * impulseP; + av2X += md.invMAngN2X * -impulseP; + av2Y += md.invMAngN2Y * -impulseP; + av2Z += md.invMAngN2Z * -impulseP; + } + let _this = this._b1; + _this._transform._positionX += lv1X; + _this._transform._positionY += lv1Y; + _this._transform._positionZ += lv1Z; + let _this1 = this._b2; + _this1._transform._positionX += lv2X; + _this1._transform._positionY += lv2Y; + _this1._transform._positionZ += lv2Z; + let _this2 = this._b1; + let theta = Math.sqrt(av1X * av1X + av1Y * av1Y + av1Z * av1Z); + let halfTheta = theta * 0.5; + let rotationToSinAxisFactor; + let cosHalfTheta; + if(halfTheta < 0.5) { + let ht2 = halfTheta * halfTheta; + rotationToSinAxisFactor = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor = Math.sin(halfTheta) / theta; + cosHalfTheta = Math.cos(halfTheta); + } + let sinAxisX; + let sinAxisY; + let sinAxisZ; + sinAxisX = av1X * rotationToSinAxisFactor; + sinAxisY = av1Y * rotationToSinAxisFactor; + sinAxisZ = av1Z * rotationToSinAxisFactor; + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = sinAxisX; + dqY = sinAxisY; + dqZ = sinAxisZ; + dqW = cosHalfTheta; + let qX; + let qY; + let qZ; + let qW; + let e00 = _this2._transform._rotation00; + let e11 = _this2._transform._rotation11; + let e22 = _this2._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + qW = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation21 - _this2._transform._rotation12) * s; + qY = (_this2._transform._rotation02 - _this2._transform._rotation20) * s; + qZ = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + qX = 0.5 * s; + s = 0.5 / s; + qY = (_this2._transform._rotation01 + _this2._transform._rotation10) * s; + qZ = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qW = (_this2._transform._rotation21 - _this2._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qY = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + qY = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation01 + _this2._transform._rotation10) * s; + qZ = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation02 - _this2._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qY = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } + qX = dqW * qX + dqX * qW + dqY * qZ - dqZ * qY; + qY = dqW * qY - dqX * qZ + dqY * qW + dqZ * qX; + qZ = dqW * qZ + dqX * qY - dqY * qX + dqZ * qW; + qW = dqW * qW - dqX * qX - dqY * qY - dqZ * qZ; + let l = qX * qX + qY * qY + qZ * qZ + qW * qW; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + qX *= l; + qY *= l; + qZ *= l; + qW *= l; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + _this2._transform._rotation00 = 1 - yy - zz; + _this2._transform._rotation01 = xy - wz; + _this2._transform._rotation02 = xz + wy; + _this2._transform._rotation10 = xy + wz; + _this2._transform._rotation11 = 1 - xx - zz; + _this2._transform._rotation12 = yz - wx; + _this2._transform._rotation20 = xz - wy; + _this2._transform._rotation21 = yz + wx; + _this2._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = _this2._transform._rotation00 * _this2._invLocalInertia00 + _this2._transform._rotation01 * _this2._invLocalInertia10 + _this2._transform._rotation02 * _this2._invLocalInertia20; + __tmp__01 = _this2._transform._rotation00 * _this2._invLocalInertia01 + _this2._transform._rotation01 * _this2._invLocalInertia11 + _this2._transform._rotation02 * _this2._invLocalInertia21; + __tmp__02 = _this2._transform._rotation00 * _this2._invLocalInertia02 + _this2._transform._rotation01 * _this2._invLocalInertia12 + _this2._transform._rotation02 * _this2._invLocalInertia22; + __tmp__10 = _this2._transform._rotation10 * _this2._invLocalInertia00 + _this2._transform._rotation11 * _this2._invLocalInertia10 + _this2._transform._rotation12 * _this2._invLocalInertia20; + __tmp__11 = _this2._transform._rotation10 * _this2._invLocalInertia01 + _this2._transform._rotation11 * _this2._invLocalInertia11 + _this2._transform._rotation12 * _this2._invLocalInertia21; + __tmp__12 = _this2._transform._rotation10 * _this2._invLocalInertia02 + _this2._transform._rotation11 * _this2._invLocalInertia12 + _this2._transform._rotation12 * _this2._invLocalInertia22; + __tmp__20 = _this2._transform._rotation20 * _this2._invLocalInertia00 + _this2._transform._rotation21 * _this2._invLocalInertia10 + _this2._transform._rotation22 * _this2._invLocalInertia20; + __tmp__21 = _this2._transform._rotation20 * _this2._invLocalInertia01 + _this2._transform._rotation21 * _this2._invLocalInertia11 + _this2._transform._rotation22 * _this2._invLocalInertia21; + __tmp__22 = _this2._transform._rotation20 * _this2._invLocalInertia02 + _this2._transform._rotation21 * _this2._invLocalInertia12 + _this2._transform._rotation22 * _this2._invLocalInertia22; + _this2._invInertia00 = __tmp__00; + _this2._invInertia01 = __tmp__01; + _this2._invInertia02 = __tmp__02; + _this2._invInertia10 = __tmp__10; + _this2._invInertia11 = __tmp__11; + _this2._invInertia12 = __tmp__12; + _this2._invInertia20 = __tmp__20; + _this2._invInertia21 = __tmp__21; + _this2._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = _this2._invInertia00 * _this2._transform._rotation00 + _this2._invInertia01 * _this2._transform._rotation01 + _this2._invInertia02 * _this2._transform._rotation02; + __tmp__011 = _this2._invInertia00 * _this2._transform._rotation10 + _this2._invInertia01 * _this2._transform._rotation11 + _this2._invInertia02 * _this2._transform._rotation12; + __tmp__021 = _this2._invInertia00 * _this2._transform._rotation20 + _this2._invInertia01 * _this2._transform._rotation21 + _this2._invInertia02 * _this2._transform._rotation22; + __tmp__101 = _this2._invInertia10 * _this2._transform._rotation00 + _this2._invInertia11 * _this2._transform._rotation01 + _this2._invInertia12 * _this2._transform._rotation02; + __tmp__111 = _this2._invInertia10 * _this2._transform._rotation10 + _this2._invInertia11 * _this2._transform._rotation11 + _this2._invInertia12 * _this2._transform._rotation12; + __tmp__121 = _this2._invInertia10 * _this2._transform._rotation20 + _this2._invInertia11 * _this2._transform._rotation21 + _this2._invInertia12 * _this2._transform._rotation22; + __tmp__201 = _this2._invInertia20 * _this2._transform._rotation00 + _this2._invInertia21 * _this2._transform._rotation01 + _this2._invInertia22 * _this2._transform._rotation02; + __tmp__211 = _this2._invInertia20 * _this2._transform._rotation10 + _this2._invInertia21 * _this2._transform._rotation11 + _this2._invInertia22 * _this2._transform._rotation12; + __tmp__221 = _this2._invInertia20 * _this2._transform._rotation20 + _this2._invInertia21 * _this2._transform._rotation21 + _this2._invInertia22 * _this2._transform._rotation22; + _this2._invInertia00 = __tmp__001; + _this2._invInertia01 = __tmp__011; + _this2._invInertia02 = __tmp__021; + _this2._invInertia10 = __tmp__101; + _this2._invInertia11 = __tmp__111; + _this2._invInertia12 = __tmp__121; + _this2._invInertia20 = __tmp__201; + _this2._invInertia21 = __tmp__211; + _this2._invInertia22 = __tmp__221; + _this2._invInertia00 *= _this2._rotFactor.x; + _this2._invInertia01 *= _this2._rotFactor.x; + _this2._invInertia02 *= _this2._rotFactor.x; + _this2._invInertia10 *= _this2._rotFactor.y; + _this2._invInertia11 *= _this2._rotFactor.y; + _this2._invInertia12 *= _this2._rotFactor.y; + _this2._invInertia20 *= _this2._rotFactor.z; + _this2._invInertia21 *= _this2._rotFactor.z; + _this2._invInertia22 *= _this2._rotFactor.z; + let _this3 = this._b2; + let theta1 = Math.sqrt(av2X * av2X + av2Y * av2Y + av2Z * av2Z); + let halfTheta1 = theta1 * 0.5; + let rotationToSinAxisFactor1; + let cosHalfTheta1; + if(halfTheta1 < 0.5) { + let ht2 = halfTheta1 * halfTheta1; + rotationToSinAxisFactor1 = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta1 = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor1 = Math.sin(halfTheta1) / theta1; + cosHalfTheta1 = Math.cos(halfTheta1); + } + let sinAxisX1; + let sinAxisY1; + let sinAxisZ1; + sinAxisX1 = av2X * rotationToSinAxisFactor1; + sinAxisY1 = av2Y * rotationToSinAxisFactor1; + sinAxisZ1 = av2Z * rotationToSinAxisFactor1; + let dqX1; + let dqY1; + let dqZ1; + let dqW1; + dqX1 = sinAxisX1; + dqY1 = sinAxisY1; + dqZ1 = sinAxisZ1; + dqW1 = cosHalfTheta1; + let qX1; + let qY1; + let qZ1; + let qW1; + let e001 = _this3._transform._rotation00; + let e111 = _this3._transform._rotation11; + let e221 = _this3._transform._rotation22; + let t1 = e001 + e111 + e221; + let s1; + if(t1 > 0) { + s1 = Math.sqrt(t1 + 1); + qW1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation21 - _this3._transform._rotation12) * s1; + qY1 = (_this3._transform._rotation02 - _this3._transform._rotation20) * s1; + qZ1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } else if(e001 > e111) { + if(e001 > e221) { + s1 = Math.sqrt(e001 - e111 - e221 + 1); + qX1 = 0.5 * s1; + s1 = 0.5 / s1; + qY1 = (_this3._transform._rotation01 + _this3._transform._rotation10) * s1; + qZ1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qW1 = (_this3._transform._rotation21 - _this3._transform._rotation12) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qY1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } + } else if(e111 > e221) { + s1 = Math.sqrt(e111 - e221 - e001 + 1); + qY1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation01 + _this3._transform._rotation10) * s1; + qZ1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation02 - _this3._transform._rotation20) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qY1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } + qX1 = dqW1 * qX1 + dqX1 * qW1 + dqY1 * qZ1 - dqZ1 * qY1; + qY1 = dqW1 * qY1 - dqX1 * qZ1 + dqY1 * qW1 + dqZ1 * qX1; + qZ1 = dqW1 * qZ1 + dqX1 * qY1 - dqY1 * qX1 + dqZ1 * qW1; + qW1 = dqW1 * qW1 - dqX1 * qX1 - dqY1 * qY1 - dqZ1 * qZ1; + let l1 = qX1 * qX1 + qY1 * qY1 + qZ1 * qZ1 + qW1 * qW1; + if(l1 > 1e-32) { + l1 = 1 / Math.sqrt(l1); + } + qX1 *= l1; + qY1 *= l1; + qZ1 *= l1; + qW1 *= l1; + let x1 = qX1; + let y1 = qY1; + let z1 = qZ1; + let w1 = qW1; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + _this3._transform._rotation00 = 1 - yy1 - zz1; + _this3._transform._rotation01 = xy1 - wz1; + _this3._transform._rotation02 = xz1 + wy1; + _this3._transform._rotation10 = xy1 + wz1; + _this3._transform._rotation11 = 1 - xx1 - zz1; + _this3._transform._rotation12 = yz1 - wx1; + _this3._transform._rotation20 = xz1 - wy1; + _this3._transform._rotation21 = yz1 + wx1; + _this3._transform._rotation22 = 1 - xx1 - yy1; + let __tmp__002; + let __tmp__012; + let __tmp__022; + let __tmp__102; + let __tmp__112; + let __tmp__122; + let __tmp__202; + let __tmp__212; + let __tmp__222; + __tmp__002 = _this3._transform._rotation00 * _this3._invLocalInertia00 + _this3._transform._rotation01 * _this3._invLocalInertia10 + _this3._transform._rotation02 * _this3._invLocalInertia20; + __tmp__012 = _this3._transform._rotation00 * _this3._invLocalInertia01 + _this3._transform._rotation01 * _this3._invLocalInertia11 + _this3._transform._rotation02 * _this3._invLocalInertia21; + __tmp__022 = _this3._transform._rotation00 * _this3._invLocalInertia02 + _this3._transform._rotation01 * _this3._invLocalInertia12 + _this3._transform._rotation02 * _this3._invLocalInertia22; + __tmp__102 = _this3._transform._rotation10 * _this3._invLocalInertia00 + _this3._transform._rotation11 * _this3._invLocalInertia10 + _this3._transform._rotation12 * _this3._invLocalInertia20; + __tmp__112 = _this3._transform._rotation10 * _this3._invLocalInertia01 + _this3._transform._rotation11 * _this3._invLocalInertia11 + _this3._transform._rotation12 * _this3._invLocalInertia21; + __tmp__122 = _this3._transform._rotation10 * _this3._invLocalInertia02 + _this3._transform._rotation11 * _this3._invLocalInertia12 + _this3._transform._rotation12 * _this3._invLocalInertia22; + __tmp__202 = _this3._transform._rotation20 * _this3._invLocalInertia00 + _this3._transform._rotation21 * _this3._invLocalInertia10 + _this3._transform._rotation22 * _this3._invLocalInertia20; + __tmp__212 = _this3._transform._rotation20 * _this3._invLocalInertia01 + _this3._transform._rotation21 * _this3._invLocalInertia11 + _this3._transform._rotation22 * _this3._invLocalInertia21; + __tmp__222 = _this3._transform._rotation20 * _this3._invLocalInertia02 + _this3._transform._rotation21 * _this3._invLocalInertia12 + _this3._transform._rotation22 * _this3._invLocalInertia22; + _this3._invInertia00 = __tmp__002; + _this3._invInertia01 = __tmp__012; + _this3._invInertia02 = __tmp__022; + _this3._invInertia10 = __tmp__102; + _this3._invInertia11 = __tmp__112; + _this3._invInertia12 = __tmp__122; + _this3._invInertia20 = __tmp__202; + _this3._invInertia21 = __tmp__212; + _this3._invInertia22 = __tmp__222; + let __tmp__003; + let __tmp__013; + let __tmp__023; + let __tmp__103; + let __tmp__113; + let __tmp__123; + let __tmp__203; + let __tmp__213; + let __tmp__223; + __tmp__003 = _this3._invInertia00 * _this3._transform._rotation00 + _this3._invInertia01 * _this3._transform._rotation01 + _this3._invInertia02 * _this3._transform._rotation02; + __tmp__013 = _this3._invInertia00 * _this3._transform._rotation10 + _this3._invInertia01 * _this3._transform._rotation11 + _this3._invInertia02 * _this3._transform._rotation12; + __tmp__023 = _this3._invInertia00 * _this3._transform._rotation20 + _this3._invInertia01 * _this3._transform._rotation21 + _this3._invInertia02 * _this3._transform._rotation22; + __tmp__103 = _this3._invInertia10 * _this3._transform._rotation00 + _this3._invInertia11 * _this3._transform._rotation01 + _this3._invInertia12 * _this3._transform._rotation02; + __tmp__113 = _this3._invInertia10 * _this3._transform._rotation10 + _this3._invInertia11 * _this3._transform._rotation11 + _this3._invInertia12 * _this3._transform._rotation12; + __tmp__123 = _this3._invInertia10 * _this3._transform._rotation20 + _this3._invInertia11 * _this3._transform._rotation21 + _this3._invInertia12 * _this3._transform._rotation22; + __tmp__203 = _this3._invInertia20 * _this3._transform._rotation00 + _this3._invInertia21 * _this3._transform._rotation01 + _this3._invInertia22 * _this3._transform._rotation02; + __tmp__213 = _this3._invInertia20 * _this3._transform._rotation10 + _this3._invInertia21 * _this3._transform._rotation11 + _this3._invInertia22 * _this3._transform._rotation12; + __tmp__223 = _this3._invInertia20 * _this3._transform._rotation20 + _this3._invInertia21 * _this3._transform._rotation21 + _this3._invInertia22 * _this3._transform._rotation22; + _this3._invInertia00 = __tmp__003; + _this3._invInertia01 = __tmp__013; + _this3._invInertia02 = __tmp__023; + _this3._invInertia10 = __tmp__103; + _this3._invInertia11 = __tmp__113; + _this3._invInertia12 = __tmp__123; + _this3._invInertia20 = __tmp__203; + _this3._invInertia21 = __tmp__213; + _this3._invInertia22 = __tmp__223; + _this3._invInertia00 *= _this3._rotFactor.x; + _this3._invInertia01 *= _this3._rotFactor.x; + _this3._invInertia02 *= _this3._rotFactor.x; + _this3._invInertia10 *= _this3._rotFactor.y; + _this3._invInertia11 *= _this3._rotFactor.y; + _this3._invInertia12 *= _this3._rotFactor.y; + _this3._invInertia20 *= _this3._rotFactor.z; + _this3._invInertia21 *= _this3._rotFactor.z; + _this3._invInertia22 *= _this3._rotFactor.z; + } + postSolve() { + let lin1X; + let lin1Y; + let lin1Z; + let ang1X; + let ang1Y; + let ang1Z; + let ang2X; + let ang2Y; + let ang2Z; + lin1X = 0; + lin1Y = 0; + lin1Z = 0; + ang1X = 0; + ang1Y = 0; + ang1Z = 0; + ang2X = 0; + ang2Y = 0; + ang2Z = 0; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let row = this.info.rows[_g++]; + let imp = row.impulse; + let jn = row.jacobianN; + let jt = row.jacobianT; + let jb = row.jacobianB; + let impN = imp.impulseN; + let impT = imp.impulseT; + let impB = imp.impulseB; + let impulseLX; + let impulseLY; + let impulseLZ; + impulseLX = 0; + impulseLY = 0; + impulseLZ = 0; + impulseLX += jt.lin1X * impT; + impulseLY += jt.lin1Y * impT; + impulseLZ += jt.lin1Z * impT; + impulseLX += jb.lin1X * impB; + impulseLY += jb.lin1Y * impB; + impulseLZ += jb.lin1Z * impB; + imp.impulseLX = impulseLX; + imp.impulseLY = impulseLY; + imp.impulseLZ = impulseLZ; + lin1X += jn.lin1X * impN; + lin1Y += jn.lin1Y * impN; + lin1Z += jn.lin1Z * impN; + ang1X += jn.ang1X * impN; + ang1Y += jn.ang1Y * impN; + ang1Z += jn.ang1Z * impN; + ang2X += jn.ang2X * impN; + ang2Y += jn.ang2Y * impN; + ang2Z += jn.ang2Z * impN; + lin1X += jt.lin1X * impT; + lin1Y += jt.lin1Y * impT; + lin1Z += jt.lin1Z * impT; + ang1X += jt.ang1X * impT; + ang1Y += jt.ang1Y * impT; + ang1Z += jt.ang1Z * impT; + ang2X += jt.ang2X * impT; + ang2Y += jt.ang2Y * impT; + ang2Z += jt.ang2Z * impT; + lin1X += jb.lin1X * impB; + lin1Y += jb.lin1Y * impB; + lin1Z += jb.lin1Z * impB; + ang1X += jb.ang1X * impB; + ang1Y += jb.ang1Y * impB; + ang1Z += jb.ang1Z * impB; + ang2X += jb.ang2X * impB; + ang2Y += jb.ang2Y * impB; + ang2Z += jb.ang2Z * impB; + } + this._b1._linearContactImpulseX += lin1X; + this._b1._linearContactImpulseY += lin1Y; + this._b1._linearContactImpulseZ += lin1Z; + this._b1._angularContactImpulseX += ang1X; + this._b1._angularContactImpulseY += ang1Y; + this._b1._angularContactImpulseZ += ang1Z; + this._b2._linearContactImpulseX -= lin1X; + this._b2._linearContactImpulseY -= lin1Y; + this._b2._linearContactImpulseZ -= lin1Z; + this._b2._angularContactImpulseX -= ang2X; + this._b2._angularContactImpulseY -= ang2Y; + this._b2._angularContactImpulseZ -= ang2Z; + this.constraint._syncManifold(); + } +} +oimo.dynamics.constraint.solver.pgs.PgsJointConstraintSolver = class oimo_dynamics_constraint_solver_pgs_PgsJointConstraintSolver extends oimo.dynamics.constraint.ConstraintSolver { + constructor(joint) { + super(); + this.joint = joint; + this.info = new oimo.dynamics.constraint.info.joint.JointSolverInfo(); + this.massData = new Array(oimo.common.Setting.maxJacobianRows); + let _g = 0; + let _g1 = this.massData.length; + while(_g < _g1) this.massData[_g++] = new oimo.dynamics.constraint.solver.common.JointSolverMassDataRow(); + } + preSolveVelocity(timeStep) { + this.joint._syncAnchors(); + this.joint._getVelocitySolverInfo(timeStep,this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let j = row.jacobian; + j.updateSparsity(); + if((j.flag & 1) != 0) { + md.invMLin1X = j.lin1X * invM1; + md.invMLin1Y = j.lin1Y * invM1; + md.invMLin1Z = j.lin1Z * invM1; + md.invMLin2X = j.lin2X * invM2; + md.invMLin2Y = j.lin2Y * invM2; + md.invMLin2Z = j.lin2Z * invM2; + } else { + md.invMLin1X = 0; + md.invMLin1Y = 0; + md.invMLin1Z = 0; + md.invMLin2X = 0; + md.invMLin2Y = 0; + md.invMLin2Z = 0; + } + if((j.flag & 2) != 0) { + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAng1X = __tmp__X; + md.invMAng1Y = __tmp__Y; + md.invMAng1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAng2X = __tmp__X1; + md.invMAng2Y = __tmp__Y1; + md.invMAng2Z = __tmp__Z1; + } else { + md.invMAng1X = 0; + md.invMAng1Y = 0; + md.invMAng1Z = 0; + md.invMAng2X = 0; + md.invMAng2Y = 0; + md.invMAng2Z = 0; + } + md.massWithoutCfm = md.invMLin1X * j.lin1X + md.invMLin1Y * j.lin1Y + md.invMLin1Z * j.lin1Z + (md.invMLin2X * j.lin2X + md.invMLin2Y * j.lin2Y + md.invMLin2Z * j.lin2Z) + (md.invMAng1X * j.ang1X + md.invMAng1Y * j.ang1Y + md.invMAng1Z * j.ang1Z) + (md.invMAng2X * j.ang2X + md.invMAng2Y * j.ang2Y + md.invMAng2Z * j.ang2Z); + md.mass = md.massWithoutCfm + row.cfm; + if(md.massWithoutCfm != 0) { + md.massWithoutCfm = 1 / md.massWithoutCfm; + } + if(md.mass != 0) { + md.mass = 1 / md.mass; + } + } + } + warmStart(timeStep) { + let factor = this.joint._positionCorrectionAlgorithm == oimo.dynamics.constraint.PositionCorrectionAlgorithm.BAUMGARTE ? oimo.common.Setting.jointWarmStartingFactorForBaungarte : oimo.common.Setting.jointWarmStartingFactor; + factor *= timeStep.dtRatio; + if(factor <= 0) { + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let _this = this.info.rows[_g++].impulse; + _this.impulse = 0; + _this.impulseM = 0; + _this.impulseP = 0; + } + return; + } + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let md = this.massData[i]; + let imp = this.info.rows[i].impulse; + imp.impulse *= factor; + imp.impulseM *= factor; + let impulse = imp.impulse + imp.impulseM; + lv1X += md.invMLin1X * impulse; + lv1Y += md.invMLin1Y * impulse; + lv1Z += md.invMLin1Z * impulse; + lv2X += md.invMLin2X * -impulse; + lv2Y += md.invMLin2Y * -impulse; + lv2Z += md.invMLin2Z * -impulse; + av1X += md.invMAng1X * impulse; + av1Y += md.invMAng1Y * impulse; + av1Z += md.invMAng1Z * impulse; + av2X += md.invMAng2X * -impulse; + av2Y += md.invMAng2Y * -impulse; + av2Z += md.invMAng2Z * -impulse; + } + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + solveVelocity() { + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._velX; + lv1Y = this._b1._velY; + lv1Z = this._b1._velZ; + lv2X = this._b2._velX; + lv2Y = this._b2._velY; + lv2Z = this._b2._velZ; + av1X = this._b1._angVelX; + av1Y = this._b1._angVelY; + av1Z = this._b1._angVelZ; + av2X = this._b2._angVelX; + av2Y = this._b2._angVelY; + av2Z = this._b2._angVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobian; + if(row.motorMaxImpulse == 0) { + continue; + } + let rv = 0; + rv += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rv -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rv += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rv -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseM = (-row.motorSpeed - rv) * md.massWithoutCfm; + let oldImpulseM = imp.impulseM; + imp.impulseM += impulseM; + if(imp.impulseM < -row.motorMaxImpulse) { + imp.impulseM = -row.motorMaxImpulse; + } else if(imp.impulseM > row.motorMaxImpulse) { + imp.impulseM = row.motorMaxImpulse; + } + impulseM = imp.impulseM - oldImpulseM; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * impulseM; + lv1Y += md.invMLin1Y * impulseM; + lv1Z += md.invMLin1Z * impulseM; + lv2X += md.invMLin2X * -impulseM; + lv2Y += md.invMLin2Y * -impulseM; + lv2Z += md.invMLin2Z * -impulseM; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * impulseM; + av1Y += md.invMAng1Y * impulseM; + av1Z += md.invMAng1Z * impulseM; + av2X += md.invMAng2X * -impulseM; + av2Y += md.invMAng2Y * -impulseM; + av2Z += md.invMAng2Z * -impulseM; + } + } + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) { + let i = _g2++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobian; + let rv = 0; + rv += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rv -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rv += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rv -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulse = (row.rhs - rv - imp.impulse * row.cfm) * md.mass; + let oldImpulse = imp.impulse; + imp.impulse += impulse; + if(imp.impulse < row.minImpulse) { + imp.impulse = row.minImpulse; + } else if(imp.impulse > row.maxImpulse) { + imp.impulse = row.maxImpulse; + } + impulse = imp.impulse - oldImpulse; + if((j.flag & 1) != 0) { + lv1X += md.invMLin1X * impulse; + lv1Y += md.invMLin1Y * impulse; + lv1Z += md.invMLin1Z * impulse; + lv2X += md.invMLin2X * -impulse; + lv2Y += md.invMLin2Y * -impulse; + lv2Z += md.invMLin2Z * -impulse; + } + if((j.flag & 2) != 0) { + av1X += md.invMAng1X * impulse; + av1Y += md.invMAng1Y * impulse; + av1Z += md.invMAng1Z * impulse; + av2X += md.invMAng2X * -impulse; + av2Y += md.invMAng2Y * -impulse; + av2Z += md.invMAng2Z * -impulse; + } + } + this._b1._velX = lv1X; + this._b1._velY = lv1Y; + this._b1._velZ = lv1Z; + this._b2._velX = lv2X; + this._b2._velY = lv2Y; + this._b2._velZ = lv2Z; + this._b1._angVelX = av1X; + this._b1._angVelY = av1Y; + this._b1._angVelZ = av1Z; + this._b2._angVelX = av2X; + this._b2._angVelY = av2Y; + this._b2._angVelZ = av2Z; + } + postSolveVelocity(timeStep) { + let linX; + let linY; + let linZ; + let angX; + let angY; + let angZ; + linX = 0; + linY = 0; + linZ = 0; + angX = 0; + angY = 0; + angZ = 0; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let row = this.info.rows[_g++]; + let imp = row.impulse; + let j = row.jacobian; + if((j.flag & 1) != 0) { + linX += j.lin1X * imp.impulse; + linY += j.lin1Y * imp.impulse; + linZ += j.lin1Z * imp.impulse; + } else if((j.flag & 2) != 0) { + angX += j.ang1X * imp.impulse; + angY += j.ang1Y * imp.impulse; + angZ += j.ang1Z * imp.impulse; + } + } + this.joint._appliedForceX = linX * timeStep.invDt; + this.joint._appliedForceY = linY * timeStep.invDt; + this.joint._appliedForceZ = linZ * timeStep.invDt; + this.joint._appliedTorqueX = angX * timeStep.invDt; + this.joint._appliedTorqueY = angY * timeStep.invDt; + this.joint._appliedTorqueZ = angZ * timeStep.invDt; + } + preSolvePosition(timeStep) { + this.joint._syncAnchors(); + this.joint._getPositionSolverInfo(this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let md = this.massData[i]; + let j = this.info.rows[i].jacobian; + md.invMLin1X = j.lin1X * invM1; + md.invMLin1Y = j.lin1Y * invM1; + md.invMLin1Z = j.lin1Z * invM1; + md.invMLin2X = j.lin2X * invM2; + md.invMLin2Y = j.lin2Y * invM2; + md.invMLin2Z = j.lin2Z * invM2; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAng1X = __tmp__X; + md.invMAng1Y = __tmp__Y; + md.invMAng1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAng2X = __tmp__X1; + md.invMAng2Y = __tmp__Y1; + md.invMAng2Z = __tmp__Z1; + md.mass = md.invMLin1X * j.lin1X + md.invMLin1Y * j.lin1Y + md.invMLin1Z * j.lin1Z + (md.invMLin2X * j.lin2X + md.invMLin2Y * j.lin2Y + md.invMLin2Z * j.lin2Z) + (md.invMAng1X * j.ang1X + md.invMAng1Y * j.ang1Y + md.invMAng1Z * j.ang1Z) + (md.invMAng2X * j.ang2X + md.invMAng2Y * j.ang2Y + md.invMAng2Z * j.ang2Z); + if(md.mass != 0) { + md.mass = 1 / md.mass; + } + } + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) this.info.rows[_g2++].impulse.impulseP = 0; + } + solvePositionSplitImpulse() { + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = this._b1._pseudoVelX; + lv1Y = this._b1._pseudoVelY; + lv1Z = this._b1._pseudoVelZ; + lv2X = this._b2._pseudoVelX; + lv2Y = this._b2._pseudoVelY; + lv2Z = this._b2._pseudoVelZ; + av1X = this._b1._angPseudoVelX; + av1Y = this._b1._angPseudoVelY; + av1Z = this._b1._angPseudoVelZ; + av2X = this._b2._angPseudoVelX; + av2Y = this._b2._angPseudoVelY; + av2Z = this._b2._angPseudoVelZ; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobian; + let rv = 0; + rv += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rv -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rv += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rv -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseP = (row.rhs * oimo.common.Setting.positionSplitImpulseBaumgarte - rv) * md.mass; + let oldImpulseP = imp.impulseP; + imp.impulseP += impulseP; + if(imp.impulseP < row.minImpulse) { + imp.impulseP = row.minImpulse; + } else if(imp.impulseP > row.maxImpulse) { + imp.impulseP = row.maxImpulse; + } + impulseP = imp.impulseP - oldImpulseP; + lv1X += md.invMLin1X * impulseP; + lv1Y += md.invMLin1Y * impulseP; + lv1Z += md.invMLin1Z * impulseP; + lv2X += md.invMLin2X * -impulseP; + lv2Y += md.invMLin2Y * -impulseP; + lv2Z += md.invMLin2Z * -impulseP; + av1X += md.invMAng1X * impulseP; + av1Y += md.invMAng1Y * impulseP; + av1Z += md.invMAng1Z * impulseP; + av2X += md.invMAng2X * -impulseP; + av2Y += md.invMAng2Y * -impulseP; + av2Z += md.invMAng2Z * -impulseP; + } + this._b1._pseudoVelX = lv1X; + this._b1._pseudoVelY = lv1Y; + this._b1._pseudoVelZ = lv1Z; + this._b2._pseudoVelX = lv2X; + this._b2._pseudoVelY = lv2Y; + this._b2._pseudoVelZ = lv2Z; + this._b1._angPseudoVelX = av1X; + this._b1._angPseudoVelY = av1Y; + this._b1._angPseudoVelZ = av1Z; + this._b2._angPseudoVelX = av2X; + this._b2._angPseudoVelY = av2Y; + this._b2._angPseudoVelZ = av2Z; + } + solvePositionNgs(timeStep) { + this.joint._syncAnchors(); + this.joint._getPositionSolverInfo(this.info); + this._b1 = this.info.b1; + this._b2 = this.info.b2; + let invM1 = this._b1._invMass; + let invM2 = this._b2._invMass; + let invI100; + let invI101; + let invI102; + let invI110; + let invI111; + let invI112; + let invI120; + let invI121; + let invI122; + let invI200; + let invI201; + let invI202; + let invI210; + let invI211; + let invI212; + let invI220; + let invI221; + let invI222; + invI100 = this._b1._invInertia00; + invI101 = this._b1._invInertia01; + invI102 = this._b1._invInertia02; + invI110 = this._b1._invInertia10; + invI111 = this._b1._invInertia11; + invI112 = this._b1._invInertia12; + invI120 = this._b1._invInertia20; + invI121 = this._b1._invInertia21; + invI122 = this._b1._invInertia22; + invI200 = this._b2._invInertia00; + invI201 = this._b2._invInertia01; + invI202 = this._b2._invInertia02; + invI210 = this._b2._invInertia10; + invI211 = this._b2._invInertia11; + invI212 = this._b2._invInertia12; + invI220 = this._b2._invInertia20; + invI221 = this._b2._invInertia21; + invI222 = this._b2._invInertia22; + let _g = 0; + let _g1 = this.info.numRows; + while(_g < _g1) { + let i = _g++; + let md = this.massData[i]; + let j = this.info.rows[i].jacobian; + md.invMLin1X = j.lin1X * invM1; + md.invMLin1Y = j.lin1Y * invM1; + md.invMLin1Z = j.lin1Z * invM1; + md.invMLin2X = j.lin2X * invM2; + md.invMLin2Y = j.lin2Y * invM2; + md.invMLin2Z = j.lin2Z * invM2; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = invI100 * j.ang1X + invI101 * j.ang1Y + invI102 * j.ang1Z; + __tmp__Y = invI110 * j.ang1X + invI111 * j.ang1Y + invI112 * j.ang1Z; + __tmp__Z = invI120 * j.ang1X + invI121 * j.ang1Y + invI122 * j.ang1Z; + md.invMAng1X = __tmp__X; + md.invMAng1Y = __tmp__Y; + md.invMAng1Z = __tmp__Z; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = invI200 * j.ang2X + invI201 * j.ang2Y + invI202 * j.ang2Z; + __tmp__Y1 = invI210 * j.ang2X + invI211 * j.ang2Y + invI212 * j.ang2Z; + __tmp__Z1 = invI220 * j.ang2X + invI221 * j.ang2Y + invI222 * j.ang2Z; + md.invMAng2X = __tmp__X1; + md.invMAng2Y = __tmp__Y1; + md.invMAng2Z = __tmp__Z1; + md.mass = md.invMLin1X * j.lin1X + md.invMLin1Y * j.lin1Y + md.invMLin1Z * j.lin1Z + (md.invMLin2X * j.lin2X + md.invMLin2Y * j.lin2Y + md.invMLin2Z * j.lin2Z) + (md.invMAng1X * j.ang1X + md.invMAng1Y * j.ang1Y + md.invMAng1Z * j.ang1Z) + (md.invMAng2X * j.ang2X + md.invMAng2Y * j.ang2Y + md.invMAng2Z * j.ang2Z); + if(md.mass != 0) { + md.mass = 1 / md.mass; + } + } + let lv1X; + let lv1Y; + let lv1Z; + let lv2X; + let lv2Y; + let lv2Z; + let av1X; + let av1Y; + let av1Z; + let av2X; + let av2Y; + let av2Z; + lv1X = 0; + lv1Y = 0; + lv1Z = 0; + lv2X = 0; + lv2Y = 0; + lv2Z = 0; + av1X = 0; + av1Y = 0; + av1Z = 0; + av2X = 0; + av2Y = 0; + av2Z = 0; + let _g2 = 0; + let _g3 = this.info.numRows; + while(_g2 < _g3) { + let i = _g2++; + let row = this.info.rows[i]; + let md = this.massData[i]; + let imp = row.impulse; + let j = row.jacobian; + let rv = 0; + rv += lv1X * j.lin1X + lv1Y * j.lin1Y + lv1Z * j.lin1Z; + rv -= lv2X * j.lin2X + lv2Y * j.lin2Y + lv2Z * j.lin2Z; + rv += av1X * j.ang1X + av1Y * j.ang1Y + av1Z * j.ang1Z; + rv -= av2X * j.ang2X + av2Y * j.ang2Y + av2Z * j.ang2Z; + let impulseP = (row.rhs * oimo.common.Setting.positionNgsBaumgarte - rv) * md.mass; + let oldImpulseP = imp.impulseP; + imp.impulseP += impulseP; + if(imp.impulseP < row.minImpulse) { + imp.impulseP = row.minImpulse; + } else if(imp.impulseP > row.maxImpulse) { + imp.impulseP = row.maxImpulse; + } + impulseP = imp.impulseP - oldImpulseP; + lv1X += md.invMLin1X * impulseP; + lv1Y += md.invMLin1Y * impulseP; + lv1Z += md.invMLin1Z * impulseP; + lv2X += md.invMLin2X * -impulseP; + lv2Y += md.invMLin2Y * -impulseP; + lv2Z += md.invMLin2Z * -impulseP; + av1X += md.invMAng1X * impulseP; + av1Y += md.invMAng1Y * impulseP; + av1Z += md.invMAng1Z * impulseP; + av2X += md.invMAng2X * -impulseP; + av2Y += md.invMAng2Y * -impulseP; + av2Z += md.invMAng2Z * -impulseP; + } + let _this = this._b1; + _this._transform._positionX += lv1X; + _this._transform._positionY += lv1Y; + _this._transform._positionZ += lv1Z; + let _this1 = this._b2; + _this1._transform._positionX += lv2X; + _this1._transform._positionY += lv2Y; + _this1._transform._positionZ += lv2Z; + let _this2 = this._b1; + let theta = Math.sqrt(av1X * av1X + av1Y * av1Y + av1Z * av1Z); + let halfTheta = theta * 0.5; + let rotationToSinAxisFactor; + let cosHalfTheta; + if(halfTheta < 0.5) { + let ht2 = halfTheta * halfTheta; + rotationToSinAxisFactor = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor = Math.sin(halfTheta) / theta; + cosHalfTheta = Math.cos(halfTheta); + } + let sinAxisX; + let sinAxisY; + let sinAxisZ; + sinAxisX = av1X * rotationToSinAxisFactor; + sinAxisY = av1Y * rotationToSinAxisFactor; + sinAxisZ = av1Z * rotationToSinAxisFactor; + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = sinAxisX; + dqY = sinAxisY; + dqZ = sinAxisZ; + dqW = cosHalfTheta; + let qX; + let qY; + let qZ; + let qW; + let e00 = _this2._transform._rotation00; + let e11 = _this2._transform._rotation11; + let e22 = _this2._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + qW = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation21 - _this2._transform._rotation12) * s; + qY = (_this2._transform._rotation02 - _this2._transform._rotation20) * s; + qZ = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + qX = 0.5 * s; + s = 0.5 / s; + qY = (_this2._transform._rotation01 + _this2._transform._rotation10) * s; + qZ = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qW = (_this2._transform._rotation21 - _this2._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qY = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + qY = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation01 + _this2._transform._rotation10) * s; + qZ = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation02 - _this2._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (_this2._transform._rotation02 + _this2._transform._rotation20) * s; + qY = (_this2._transform._rotation12 + _this2._transform._rotation21) * s; + qW = (_this2._transform._rotation10 - _this2._transform._rotation01) * s; + } + qX = dqW * qX + dqX * qW + dqY * qZ - dqZ * qY; + qY = dqW * qY - dqX * qZ + dqY * qW + dqZ * qX; + qZ = dqW * qZ + dqX * qY - dqY * qX + dqZ * qW; + qW = dqW * qW - dqX * qX - dqY * qY - dqZ * qZ; + let l = qX * qX + qY * qY + qZ * qZ + qW * qW; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + qX *= l; + qY *= l; + qZ *= l; + qW *= l; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + _this2._transform._rotation00 = 1 - yy - zz; + _this2._transform._rotation01 = xy - wz; + _this2._transform._rotation02 = xz + wy; + _this2._transform._rotation10 = xy + wz; + _this2._transform._rotation11 = 1 - xx - zz; + _this2._transform._rotation12 = yz - wx; + _this2._transform._rotation20 = xz - wy; + _this2._transform._rotation21 = yz + wx; + _this2._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = _this2._transform._rotation00 * _this2._invLocalInertia00 + _this2._transform._rotation01 * _this2._invLocalInertia10 + _this2._transform._rotation02 * _this2._invLocalInertia20; + __tmp__01 = _this2._transform._rotation00 * _this2._invLocalInertia01 + _this2._transform._rotation01 * _this2._invLocalInertia11 + _this2._transform._rotation02 * _this2._invLocalInertia21; + __tmp__02 = _this2._transform._rotation00 * _this2._invLocalInertia02 + _this2._transform._rotation01 * _this2._invLocalInertia12 + _this2._transform._rotation02 * _this2._invLocalInertia22; + __tmp__10 = _this2._transform._rotation10 * _this2._invLocalInertia00 + _this2._transform._rotation11 * _this2._invLocalInertia10 + _this2._transform._rotation12 * _this2._invLocalInertia20; + __tmp__11 = _this2._transform._rotation10 * _this2._invLocalInertia01 + _this2._transform._rotation11 * _this2._invLocalInertia11 + _this2._transform._rotation12 * _this2._invLocalInertia21; + __tmp__12 = _this2._transform._rotation10 * _this2._invLocalInertia02 + _this2._transform._rotation11 * _this2._invLocalInertia12 + _this2._transform._rotation12 * _this2._invLocalInertia22; + __tmp__20 = _this2._transform._rotation20 * _this2._invLocalInertia00 + _this2._transform._rotation21 * _this2._invLocalInertia10 + _this2._transform._rotation22 * _this2._invLocalInertia20; + __tmp__21 = _this2._transform._rotation20 * _this2._invLocalInertia01 + _this2._transform._rotation21 * _this2._invLocalInertia11 + _this2._transform._rotation22 * _this2._invLocalInertia21; + __tmp__22 = _this2._transform._rotation20 * _this2._invLocalInertia02 + _this2._transform._rotation21 * _this2._invLocalInertia12 + _this2._transform._rotation22 * _this2._invLocalInertia22; + _this2._invInertia00 = __tmp__00; + _this2._invInertia01 = __tmp__01; + _this2._invInertia02 = __tmp__02; + _this2._invInertia10 = __tmp__10; + _this2._invInertia11 = __tmp__11; + _this2._invInertia12 = __tmp__12; + _this2._invInertia20 = __tmp__20; + _this2._invInertia21 = __tmp__21; + _this2._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = _this2._invInertia00 * _this2._transform._rotation00 + _this2._invInertia01 * _this2._transform._rotation01 + _this2._invInertia02 * _this2._transform._rotation02; + __tmp__011 = _this2._invInertia00 * _this2._transform._rotation10 + _this2._invInertia01 * _this2._transform._rotation11 + _this2._invInertia02 * _this2._transform._rotation12; + __tmp__021 = _this2._invInertia00 * _this2._transform._rotation20 + _this2._invInertia01 * _this2._transform._rotation21 + _this2._invInertia02 * _this2._transform._rotation22; + __tmp__101 = _this2._invInertia10 * _this2._transform._rotation00 + _this2._invInertia11 * _this2._transform._rotation01 + _this2._invInertia12 * _this2._transform._rotation02; + __tmp__111 = _this2._invInertia10 * _this2._transform._rotation10 + _this2._invInertia11 * _this2._transform._rotation11 + _this2._invInertia12 * _this2._transform._rotation12; + __tmp__121 = _this2._invInertia10 * _this2._transform._rotation20 + _this2._invInertia11 * _this2._transform._rotation21 + _this2._invInertia12 * _this2._transform._rotation22; + __tmp__201 = _this2._invInertia20 * _this2._transform._rotation00 + _this2._invInertia21 * _this2._transform._rotation01 + _this2._invInertia22 * _this2._transform._rotation02; + __tmp__211 = _this2._invInertia20 * _this2._transform._rotation10 + _this2._invInertia21 * _this2._transform._rotation11 + _this2._invInertia22 * _this2._transform._rotation12; + __tmp__221 = _this2._invInertia20 * _this2._transform._rotation20 + _this2._invInertia21 * _this2._transform._rotation21 + _this2._invInertia22 * _this2._transform._rotation22; + _this2._invInertia00 = __tmp__001; + _this2._invInertia01 = __tmp__011; + _this2._invInertia02 = __tmp__021; + _this2._invInertia10 = __tmp__101; + _this2._invInertia11 = __tmp__111; + _this2._invInertia12 = __tmp__121; + _this2._invInertia20 = __tmp__201; + _this2._invInertia21 = __tmp__211; + _this2._invInertia22 = __tmp__221; + _this2._invInertia00 *= _this2._rotFactor.x; + _this2._invInertia01 *= _this2._rotFactor.x; + _this2._invInertia02 *= _this2._rotFactor.x; + _this2._invInertia10 *= _this2._rotFactor.y; + _this2._invInertia11 *= _this2._rotFactor.y; + _this2._invInertia12 *= _this2._rotFactor.y; + _this2._invInertia20 *= _this2._rotFactor.z; + _this2._invInertia21 *= _this2._rotFactor.z; + _this2._invInertia22 *= _this2._rotFactor.z; + let _this3 = this._b2; + let theta1 = Math.sqrt(av2X * av2X + av2Y * av2Y + av2Z * av2Z); + let halfTheta1 = theta1 * 0.5; + let rotationToSinAxisFactor1; + let cosHalfTheta1; + if(halfTheta1 < 0.5) { + let ht2 = halfTheta1 * halfTheta1; + rotationToSinAxisFactor1 = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta1 = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor1 = Math.sin(halfTheta1) / theta1; + cosHalfTheta1 = Math.cos(halfTheta1); + } + let sinAxisX1; + let sinAxisY1; + let sinAxisZ1; + sinAxisX1 = av2X * rotationToSinAxisFactor1; + sinAxisY1 = av2Y * rotationToSinAxisFactor1; + sinAxisZ1 = av2Z * rotationToSinAxisFactor1; + let dqX1; + let dqY1; + let dqZ1; + let dqW1; + dqX1 = sinAxisX1; + dqY1 = sinAxisY1; + dqZ1 = sinAxisZ1; + dqW1 = cosHalfTheta1; + let qX1; + let qY1; + let qZ1; + let qW1; + let e001 = _this3._transform._rotation00; + let e111 = _this3._transform._rotation11; + let e221 = _this3._transform._rotation22; + let t1 = e001 + e111 + e221; + let s1; + if(t1 > 0) { + s1 = Math.sqrt(t1 + 1); + qW1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation21 - _this3._transform._rotation12) * s1; + qY1 = (_this3._transform._rotation02 - _this3._transform._rotation20) * s1; + qZ1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } else if(e001 > e111) { + if(e001 > e221) { + s1 = Math.sqrt(e001 - e111 - e221 + 1); + qX1 = 0.5 * s1; + s1 = 0.5 / s1; + qY1 = (_this3._transform._rotation01 + _this3._transform._rotation10) * s1; + qZ1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qW1 = (_this3._transform._rotation21 - _this3._transform._rotation12) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qY1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } + } else if(e111 > e221) { + s1 = Math.sqrt(e111 - e221 - e001 + 1); + qY1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation01 + _this3._transform._rotation10) * s1; + qZ1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation02 - _this3._transform._rotation20) * s1; + } else { + s1 = Math.sqrt(e221 - e001 - e111 + 1); + qZ1 = 0.5 * s1; + s1 = 0.5 / s1; + qX1 = (_this3._transform._rotation02 + _this3._transform._rotation20) * s1; + qY1 = (_this3._transform._rotation12 + _this3._transform._rotation21) * s1; + qW1 = (_this3._transform._rotation10 - _this3._transform._rotation01) * s1; + } + qX1 = dqW1 * qX1 + dqX1 * qW1 + dqY1 * qZ1 - dqZ1 * qY1; + qY1 = dqW1 * qY1 - dqX1 * qZ1 + dqY1 * qW1 + dqZ1 * qX1; + qZ1 = dqW1 * qZ1 + dqX1 * qY1 - dqY1 * qX1 + dqZ1 * qW1; + qW1 = dqW1 * qW1 - dqX1 * qX1 - dqY1 * qY1 - dqZ1 * qZ1; + let l1 = qX1 * qX1 + qY1 * qY1 + qZ1 * qZ1 + qW1 * qW1; + if(l1 > 1e-32) { + l1 = 1 / Math.sqrt(l1); + } + qX1 *= l1; + qY1 *= l1; + qZ1 *= l1; + qW1 *= l1; + let x1 = qX1; + let y1 = qY1; + let z1 = qZ1; + let w1 = qW1; + let x21 = 2 * x1; + let y21 = 2 * y1; + let z21 = 2 * z1; + let xx1 = x1 * x21; + let yy1 = y1 * y21; + let zz1 = z1 * z21; + let xy1 = x1 * y21; + let yz1 = y1 * z21; + let xz1 = x1 * z21; + let wx1 = w1 * x21; + let wy1 = w1 * y21; + let wz1 = w1 * z21; + _this3._transform._rotation00 = 1 - yy1 - zz1; + _this3._transform._rotation01 = xy1 - wz1; + _this3._transform._rotation02 = xz1 + wy1; + _this3._transform._rotation10 = xy1 + wz1; + _this3._transform._rotation11 = 1 - xx1 - zz1; + _this3._transform._rotation12 = yz1 - wx1; + _this3._transform._rotation20 = xz1 - wy1; + _this3._transform._rotation21 = yz1 + wx1; + _this3._transform._rotation22 = 1 - xx1 - yy1; + let __tmp__002; + let __tmp__012; + let __tmp__022; + let __tmp__102; + let __tmp__112; + let __tmp__122; + let __tmp__202; + let __tmp__212; + let __tmp__222; + __tmp__002 = _this3._transform._rotation00 * _this3._invLocalInertia00 + _this3._transform._rotation01 * _this3._invLocalInertia10 + _this3._transform._rotation02 * _this3._invLocalInertia20; + __tmp__012 = _this3._transform._rotation00 * _this3._invLocalInertia01 + _this3._transform._rotation01 * _this3._invLocalInertia11 + _this3._transform._rotation02 * _this3._invLocalInertia21; + __tmp__022 = _this3._transform._rotation00 * _this3._invLocalInertia02 + _this3._transform._rotation01 * _this3._invLocalInertia12 + _this3._transform._rotation02 * _this3._invLocalInertia22; + __tmp__102 = _this3._transform._rotation10 * _this3._invLocalInertia00 + _this3._transform._rotation11 * _this3._invLocalInertia10 + _this3._transform._rotation12 * _this3._invLocalInertia20; + __tmp__112 = _this3._transform._rotation10 * _this3._invLocalInertia01 + _this3._transform._rotation11 * _this3._invLocalInertia11 + _this3._transform._rotation12 * _this3._invLocalInertia21; + __tmp__122 = _this3._transform._rotation10 * _this3._invLocalInertia02 + _this3._transform._rotation11 * _this3._invLocalInertia12 + _this3._transform._rotation12 * _this3._invLocalInertia22; + __tmp__202 = _this3._transform._rotation20 * _this3._invLocalInertia00 + _this3._transform._rotation21 * _this3._invLocalInertia10 + _this3._transform._rotation22 * _this3._invLocalInertia20; + __tmp__212 = _this3._transform._rotation20 * _this3._invLocalInertia01 + _this3._transform._rotation21 * _this3._invLocalInertia11 + _this3._transform._rotation22 * _this3._invLocalInertia21; + __tmp__222 = _this3._transform._rotation20 * _this3._invLocalInertia02 + _this3._transform._rotation21 * _this3._invLocalInertia12 + _this3._transform._rotation22 * _this3._invLocalInertia22; + _this3._invInertia00 = __tmp__002; + _this3._invInertia01 = __tmp__012; + _this3._invInertia02 = __tmp__022; + _this3._invInertia10 = __tmp__102; + _this3._invInertia11 = __tmp__112; + _this3._invInertia12 = __tmp__122; + _this3._invInertia20 = __tmp__202; + _this3._invInertia21 = __tmp__212; + _this3._invInertia22 = __tmp__222; + let __tmp__003; + let __tmp__013; + let __tmp__023; + let __tmp__103; + let __tmp__113; + let __tmp__123; + let __tmp__203; + let __tmp__213; + let __tmp__223; + __tmp__003 = _this3._invInertia00 * _this3._transform._rotation00 + _this3._invInertia01 * _this3._transform._rotation01 + _this3._invInertia02 * _this3._transform._rotation02; + __tmp__013 = _this3._invInertia00 * _this3._transform._rotation10 + _this3._invInertia01 * _this3._transform._rotation11 + _this3._invInertia02 * _this3._transform._rotation12; + __tmp__023 = _this3._invInertia00 * _this3._transform._rotation20 + _this3._invInertia01 * _this3._transform._rotation21 + _this3._invInertia02 * _this3._transform._rotation22; + __tmp__103 = _this3._invInertia10 * _this3._transform._rotation00 + _this3._invInertia11 * _this3._transform._rotation01 + _this3._invInertia12 * _this3._transform._rotation02; + __tmp__113 = _this3._invInertia10 * _this3._transform._rotation10 + _this3._invInertia11 * _this3._transform._rotation11 + _this3._invInertia12 * _this3._transform._rotation12; + __tmp__123 = _this3._invInertia10 * _this3._transform._rotation20 + _this3._invInertia11 * _this3._transform._rotation21 + _this3._invInertia12 * _this3._transform._rotation22; + __tmp__203 = _this3._invInertia20 * _this3._transform._rotation00 + _this3._invInertia21 * _this3._transform._rotation01 + _this3._invInertia22 * _this3._transform._rotation02; + __tmp__213 = _this3._invInertia20 * _this3._transform._rotation10 + _this3._invInertia21 * _this3._transform._rotation11 + _this3._invInertia22 * _this3._transform._rotation12; + __tmp__223 = _this3._invInertia20 * _this3._transform._rotation20 + _this3._invInertia21 * _this3._transform._rotation21 + _this3._invInertia22 * _this3._transform._rotation22; + _this3._invInertia00 = __tmp__003; + _this3._invInertia01 = __tmp__013; + _this3._invInertia02 = __tmp__023; + _this3._invInertia10 = __tmp__103; + _this3._invInertia11 = __tmp__113; + _this3._invInertia12 = __tmp__123; + _this3._invInertia20 = __tmp__203; + _this3._invInertia21 = __tmp__213; + _this3._invInertia22 = __tmp__223; + _this3._invInertia00 *= _this3._rotFactor.x; + _this3._invInertia01 *= _this3._rotFactor.x; + _this3._invInertia02 *= _this3._rotFactor.x; + _this3._invInertia10 *= _this3._rotFactor.y; + _this3._invInertia11 *= _this3._rotFactor.y; + _this3._invInertia12 *= _this3._rotFactor.y; + _this3._invInertia20 *= _this3._rotFactor.z; + _this3._invInertia21 *= _this3._rotFactor.z; + _this3._invInertia22 *= _this3._rotFactor.z; + } + postSolve() { + this.joint._syncAnchors(); + this.joint._checkDestruction(); + } +} +if(!oimo.dynamics.rigidbody) oimo.dynamics.rigidbody = {}; +oimo.dynamics.rigidbody.MassData = class oimo_dynamics_rigidbody_MassData { + constructor() { + this.mass = 0; + this.localInertia = new oimo.common.Mat3(); + } +} +oimo.dynamics.rigidbody.RigidBody = class oimo_dynamics_rigidbody_RigidBody { + constructor(config) { + this._next = null; + this._prev = null; + this._shapeList = null; + this._shapeListLast = null; + this._numShapes = 0; + this._contactLinkList = null; + this._contactLinkListLast = null; + this._numContactLinks = 0; + this._jointLinkList = null; + this._jointLinkListLast = null; + this._numJointLinks = 0; + let v = config.linearVelocity; + this._velX = v.x; + this._velY = v.y; + this._velZ = v.z; + let v1 = config.angularVelocity; + this._angVelX = v1.x; + this._angVelY = v1.y; + this._angVelZ = v1.z; + this._pseudoVelX = 0; + this._pseudoVelY = 0; + this._pseudoVelZ = 0; + this._angPseudoVelX = 0; + this._angPseudoVelY = 0; + this._angPseudoVelZ = 0; + this._ptransform = new oimo.common.Transform(); + this._transform = new oimo.common.Transform(); + let v2 = config.position; + this._ptransform._positionX = v2.x; + this._ptransform._positionY = v2.y; + this._ptransform._positionZ = v2.z; + let m = config.rotation; + this._ptransform._rotation00 = m.e00; + this._ptransform._rotation01 = m.e01; + this._ptransform._rotation02 = m.e02; + this._ptransform._rotation10 = m.e10; + this._ptransform._rotation11 = m.e11; + this._ptransform._rotation12 = m.e12; + this._ptransform._rotation20 = m.e20; + this._ptransform._rotation21 = m.e21; + this._ptransform._rotation22 = m.e22; + let dst = this._transform; + let src = this._ptransform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + this._type = config.type; + this._sleepTime = 0; + this._sleeping = false; + this._autoSleep = config.autoSleep; + this._mass = 0; + this._invMass = 0; + this._localInertia00 = 0; + this._localInertia01 = 0; + this._localInertia02 = 0; + this._localInertia10 = 0; + this._localInertia11 = 0; + this._localInertia12 = 0; + this._localInertia20 = 0; + this._localInertia21 = 0; + this._localInertia22 = 0; + this._invLocalInertia00 = 0; + this._invLocalInertia01 = 0; + this._invLocalInertia02 = 0; + this._invLocalInertia10 = 0; + this._invLocalInertia11 = 0; + this._invLocalInertia12 = 0; + this._invLocalInertia20 = 0; + this._invLocalInertia21 = 0; + this._invLocalInertia22 = 0; + this._invLocalInertiaWithoutRotFactor00 = 0; + this._invLocalInertiaWithoutRotFactor01 = 0; + this._invLocalInertiaWithoutRotFactor02 = 0; + this._invLocalInertiaWithoutRotFactor10 = 0; + this._invLocalInertiaWithoutRotFactor11 = 0; + this._invLocalInertiaWithoutRotFactor12 = 0; + this._invLocalInertiaWithoutRotFactor20 = 0; + this._invLocalInertiaWithoutRotFactor21 = 0; + this._invLocalInertiaWithoutRotFactor22 = 0; + this._invInertia00 = 0; + this._invInertia01 = 0; + this._invInertia02 = 0; + this._invInertia10 = 0; + this._invInertia11 = 0; + this._invInertia12 = 0; + this._invInertia20 = 0; + this._invInertia21 = 0; + this._invInertia22 = 0; + this._linearDamping = config.linearDamping; + this._angularDamping = config.angularDamping; + this._forceX = 0; + this._forceY = 0; + this._forceZ = 0; + this._torqueX = 0; + this._torqueY = 0; + this._torqueZ = 0; + this._linearContactImpulseX = 0; + this._linearContactImpulseY = 0; + this._linearContactImpulseZ = 0; + this._angularContactImpulseX = 0; + this._angularContactImpulseY = 0; + this._angularContactImpulseZ = 0; + this._rotFactor = new oimo.common.Vec3(1,1,1); + this._addedToIsland = false; + this._gravityScale = 1; + this._world = null; + } + _integrate(dt) { + switch(this._type) { + case 1: + this._velX = 0; + this._velY = 0; + this._velZ = 0; + this._angVelX = 0; + this._angVelY = 0; + this._angVelZ = 0; + this._pseudoVelX = 0; + this._pseudoVelY = 0; + this._pseudoVelZ = 0; + this._angPseudoVelX = 0; + this._angPseudoVelY = 0; + this._angPseudoVelZ = 0; + break; + case 0:case 2: + let translationX; + let translationY; + let translationZ; + let rotationX; + let rotationY; + let rotationZ; + translationX = this._velX * dt; + translationY = this._velY * dt; + translationZ = this._velZ * dt; + rotationX = this._angVelX * dt; + rotationY = this._angVelY * dt; + rotationZ = this._angVelZ * dt; + let translationLengthSq = translationX * translationX + translationY * translationY + translationZ * translationZ; + let rotationLengthSq = rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ; + if(translationLengthSq == 0 && rotationLengthSq == 0) { + return; + } + if(translationLengthSq > oimo.common.Setting.maxTranslationPerStep * oimo.common.Setting.maxTranslationPerStep) { + let l = oimo.common.Setting.maxTranslationPerStep / Math.sqrt(translationLengthSq); + this._velX *= l; + this._velY *= l; + this._velZ *= l; + translationX *= l; + translationY *= l; + translationZ *= l; + } + if(rotationLengthSq > oimo.common.Setting.maxRotationPerStep * oimo.common.Setting.maxRotationPerStep) { + let l = oimo.common.Setting.maxRotationPerStep / Math.sqrt(rotationLengthSq); + this._angVelX *= l; + this._angVelY *= l; + this._angVelZ *= l; + rotationX *= l; + rotationY *= l; + rotationZ *= l; + } + this._transform._positionX += translationX; + this._transform._positionY += translationY; + this._transform._positionZ += translationZ; + let theta = Math.sqrt(rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ); + let halfTheta = theta * 0.5; + let rotationToSinAxisFactor; + let cosHalfTheta; + if(halfTheta < 0.5) { + let ht2 = halfTheta * halfTheta; + rotationToSinAxisFactor = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor = Math.sin(halfTheta) / theta; + cosHalfTheta = Math.cos(halfTheta); + } + let sinAxisX; + let sinAxisY; + let sinAxisZ; + sinAxisX = rotationX * rotationToSinAxisFactor; + sinAxisY = rotationY * rotationToSinAxisFactor; + sinAxisZ = rotationZ * rotationToSinAxisFactor; + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = sinAxisX; + dqY = sinAxisY; + dqZ = sinAxisZ; + dqW = cosHalfTheta; + let qX; + let qY; + let qZ; + let qW; + let e00 = this._transform._rotation00; + let e11 = this._transform._rotation11; + let e22 = this._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + qW = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation21 - this._transform._rotation12) * s; + qY = (this._transform._rotation02 - this._transform._rotation20) * s; + qZ = (this._transform._rotation10 - this._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + qX = 0.5 * s; + s = 0.5 / s; + qY = (this._transform._rotation01 + this._transform._rotation10) * s; + qZ = (this._transform._rotation02 + this._transform._rotation20) * s; + qW = (this._transform._rotation21 - this._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation02 + this._transform._rotation20) * s; + qY = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + qY = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation01 + this._transform._rotation10) * s; + qZ = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation02 - this._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation02 + this._transform._rotation20) * s; + qY = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + qX = dqW * qX + dqX * qW + dqY * qZ - dqZ * qY; + qY = dqW * qY - dqX * qZ + dqY * qW + dqZ * qX; + qZ = dqW * qZ + dqX * qY - dqY * qX + dqZ * qW; + qW = dqW * qW - dqX * qX - dqY * qY - dqZ * qZ; + let l = qX * qX + qY * qY + qZ * qZ + qW * qW; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + qX *= l; + qY *= l; + qZ *= l; + qW *= l; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + this._transform._rotation00 = 1 - yy - zz; + this._transform._rotation01 = xy - wz; + this._transform._rotation02 = xz + wy; + this._transform._rotation10 = xy + wz; + this._transform._rotation11 = 1 - xx - zz; + this._transform._rotation12 = yz - wx; + this._transform._rotation20 = xz - wy; + this._transform._rotation21 = yz + wx; + this._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + break; + } + } + _integratePseudoVelocity() { + if(this._pseudoVelX * this._pseudoVelX + this._pseudoVelY * this._pseudoVelY + this._pseudoVelZ * this._pseudoVelZ == 0 && this._angPseudoVelX * this._angPseudoVelX + this._angPseudoVelY * this._angPseudoVelY + this._angPseudoVelZ * this._angPseudoVelZ == 0) { + return; + } + switch(this._type) { + case 1: + this._pseudoVelX = 0; + this._pseudoVelY = 0; + this._pseudoVelZ = 0; + this._angPseudoVelX = 0; + this._angPseudoVelY = 0; + this._angPseudoVelZ = 0; + break; + case 0:case 2: + let translationX; + let translationY; + let translationZ; + let rotationX; + let rotationY; + let rotationZ; + translationX = this._pseudoVelX; + translationY = this._pseudoVelY; + translationZ = this._pseudoVelZ; + rotationX = this._angPseudoVelX; + rotationY = this._angPseudoVelY; + rotationZ = this._angPseudoVelZ; + this._pseudoVelX = 0; + this._pseudoVelY = 0; + this._pseudoVelZ = 0; + this._angPseudoVelX = 0; + this._angPseudoVelY = 0; + this._angPseudoVelZ = 0; + this._transform._positionX += translationX; + this._transform._positionY += translationY; + this._transform._positionZ += translationZ; + let theta = Math.sqrt(rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ); + let halfTheta = theta * 0.5; + let rotationToSinAxisFactor; + let cosHalfTheta; + if(halfTheta < 0.5) { + let ht2 = halfTheta * halfTheta; + rotationToSinAxisFactor = 0.5 * (1 - ht2 * 0.16666666666666666 + ht2 * ht2 * 0.0083333333333333332); + cosHalfTheta = 1 - ht2 * 0.5 + ht2 * ht2 * 0.041666666666666664; + } else { + rotationToSinAxisFactor = Math.sin(halfTheta) / theta; + cosHalfTheta = Math.cos(halfTheta); + } + let sinAxisX; + let sinAxisY; + let sinAxisZ; + sinAxisX = rotationX * rotationToSinAxisFactor; + sinAxisY = rotationY * rotationToSinAxisFactor; + sinAxisZ = rotationZ * rotationToSinAxisFactor; + let dqX; + let dqY; + let dqZ; + let dqW; + dqX = sinAxisX; + dqY = sinAxisY; + dqZ = sinAxisZ; + dqW = cosHalfTheta; + let qX; + let qY; + let qZ; + let qW; + let e00 = this._transform._rotation00; + let e11 = this._transform._rotation11; + let e22 = this._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + qW = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation21 - this._transform._rotation12) * s; + qY = (this._transform._rotation02 - this._transform._rotation20) * s; + qZ = (this._transform._rotation10 - this._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + qX = 0.5 * s; + s = 0.5 / s; + qY = (this._transform._rotation01 + this._transform._rotation10) * s; + qZ = (this._transform._rotation02 + this._transform._rotation20) * s; + qW = (this._transform._rotation21 - this._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation02 + this._transform._rotation20) * s; + qY = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + qY = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation01 + this._transform._rotation10) * s; + qZ = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation02 - this._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + qZ = 0.5 * s; + s = 0.5 / s; + qX = (this._transform._rotation02 + this._transform._rotation20) * s; + qY = (this._transform._rotation12 + this._transform._rotation21) * s; + qW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + qX = dqW * qX + dqX * qW + dqY * qZ - dqZ * qY; + qY = dqW * qY - dqX * qZ + dqY * qW + dqZ * qX; + qZ = dqW * qZ + dqX * qY - dqY * qX + dqZ * qW; + qW = dqW * qW - dqX * qX - dqY * qY - dqZ * qZ; + let l = qX * qX + qY * qY + qZ * qZ + qW * qW; + if(l > 1e-32) { + l = 1 / Math.sqrt(l); + } + qX *= l; + qY *= l; + qZ *= l; + qW *= l; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + this._transform._rotation00 = 1 - yy - zz; + this._transform._rotation01 = xy - wz; + this._transform._rotation02 = xz + wy; + this._transform._rotation10 = xy + wz; + this._transform._rotation11 = 1 - xx - zz; + this._transform._rotation12 = yz - wx; + this._transform._rotation20 = xz - wy; + this._transform._rotation21 = yz + wx; + this._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + break; + } + } + updateMass() { + let totalInertia00; + let totalInertia01; + let totalInertia02; + let totalInertia10; + let totalInertia11; + let totalInertia12; + let totalInertia20; + let totalInertia21; + let totalInertia22; + totalInertia00 = 0; + totalInertia01 = 0; + totalInertia02 = 0; + totalInertia10 = 0; + totalInertia11 = 0; + totalInertia12 = 0; + totalInertia20 = 0; + totalInertia21 = 0; + totalInertia22 = 0; + let totalMass = 0; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let g = s._geom; + g._updateMass(); + let mass = s._density * g._volume; + let inertia00; + let inertia01; + let inertia02; + let inertia10; + let inertia11; + let inertia12; + let inertia20; + let inertia21; + let inertia22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = s._localTransform._rotation00 * g._inertiaCoeff00 + s._localTransform._rotation01 * g._inertiaCoeff10 + s._localTransform._rotation02 * g._inertiaCoeff20; + __tmp__01 = s._localTransform._rotation00 * g._inertiaCoeff01 + s._localTransform._rotation01 * g._inertiaCoeff11 + s._localTransform._rotation02 * g._inertiaCoeff21; + __tmp__02 = s._localTransform._rotation00 * g._inertiaCoeff02 + s._localTransform._rotation01 * g._inertiaCoeff12 + s._localTransform._rotation02 * g._inertiaCoeff22; + __tmp__10 = s._localTransform._rotation10 * g._inertiaCoeff00 + s._localTransform._rotation11 * g._inertiaCoeff10 + s._localTransform._rotation12 * g._inertiaCoeff20; + __tmp__11 = s._localTransform._rotation10 * g._inertiaCoeff01 + s._localTransform._rotation11 * g._inertiaCoeff11 + s._localTransform._rotation12 * g._inertiaCoeff21; + __tmp__12 = s._localTransform._rotation10 * g._inertiaCoeff02 + s._localTransform._rotation11 * g._inertiaCoeff12 + s._localTransform._rotation12 * g._inertiaCoeff22; + __tmp__20 = s._localTransform._rotation20 * g._inertiaCoeff00 + s._localTransform._rotation21 * g._inertiaCoeff10 + s._localTransform._rotation22 * g._inertiaCoeff20; + __tmp__21 = s._localTransform._rotation20 * g._inertiaCoeff01 + s._localTransform._rotation21 * g._inertiaCoeff11 + s._localTransform._rotation22 * g._inertiaCoeff21; + __tmp__22 = s._localTransform._rotation20 * g._inertiaCoeff02 + s._localTransform._rotation21 * g._inertiaCoeff12 + s._localTransform._rotation22 * g._inertiaCoeff22; + inertia00 = __tmp__00; + inertia01 = __tmp__01; + inertia02 = __tmp__02; + inertia10 = __tmp__10; + inertia11 = __tmp__11; + inertia12 = __tmp__12; + inertia20 = __tmp__20; + inertia21 = __tmp__21; + inertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = inertia00 * s._localTransform._rotation00 + inertia01 * s._localTransform._rotation01 + inertia02 * s._localTransform._rotation02; + __tmp__011 = inertia00 * s._localTransform._rotation10 + inertia01 * s._localTransform._rotation11 + inertia02 * s._localTransform._rotation12; + __tmp__021 = inertia00 * s._localTransform._rotation20 + inertia01 * s._localTransform._rotation21 + inertia02 * s._localTransform._rotation22; + __tmp__101 = inertia10 * s._localTransform._rotation00 + inertia11 * s._localTransform._rotation01 + inertia12 * s._localTransform._rotation02; + __tmp__111 = inertia10 * s._localTransform._rotation10 + inertia11 * s._localTransform._rotation11 + inertia12 * s._localTransform._rotation12; + __tmp__121 = inertia10 * s._localTransform._rotation20 + inertia11 * s._localTransform._rotation21 + inertia12 * s._localTransform._rotation22; + __tmp__201 = inertia20 * s._localTransform._rotation00 + inertia21 * s._localTransform._rotation01 + inertia22 * s._localTransform._rotation02; + __tmp__211 = inertia20 * s._localTransform._rotation10 + inertia21 * s._localTransform._rotation11 + inertia22 * s._localTransform._rotation12; + __tmp__221 = inertia20 * s._localTransform._rotation20 + inertia21 * s._localTransform._rotation21 + inertia22 * s._localTransform._rotation22; + inertia00 = __tmp__001; + inertia01 = __tmp__011; + inertia02 = __tmp__021; + inertia10 = __tmp__101; + inertia11 = __tmp__111; + inertia12 = __tmp__121; + inertia20 = __tmp__201; + inertia21 = __tmp__211; + inertia22 = __tmp__221; + inertia00 *= mass; + inertia01 *= mass; + inertia02 *= mass; + inertia10 *= mass; + inertia11 *= mass; + inertia12 *= mass; + inertia20 *= mass; + inertia21 *= mass; + inertia22 *= mass; + let cogInertia00; + let cogInertia01; + let cogInertia02; + let cogInertia10; + let cogInertia11; + let cogInertia12; + let cogInertia20; + let cogInertia21; + let cogInertia22; + let xx = s._localTransform._positionX * s._localTransform._positionX; + let yy = s._localTransform._positionY * s._localTransform._positionY; + let zz = s._localTransform._positionZ * s._localTransform._positionZ; + let xy = -s._localTransform._positionX * s._localTransform._positionY; + let yz = -s._localTransform._positionY * s._localTransform._positionZ; + let zx = -s._localTransform._positionZ * s._localTransform._positionX; + cogInertia00 = yy + zz; + cogInertia01 = xy; + cogInertia02 = zx; + cogInertia10 = xy; + cogInertia11 = xx + zz; + cogInertia12 = yz; + cogInertia20 = zx; + cogInertia21 = yz; + cogInertia22 = xx + yy; + inertia00 += cogInertia00 * mass; + inertia01 += cogInertia01 * mass; + inertia02 += cogInertia02 * mass; + inertia10 += cogInertia10 * mass; + inertia11 += cogInertia11 * mass; + inertia12 += cogInertia12 * mass; + inertia20 += cogInertia20 * mass; + inertia21 += cogInertia21 * mass; + inertia22 += cogInertia22 * mass; + totalMass += mass; + totalInertia00 += inertia00; + totalInertia01 += inertia01; + totalInertia02 += inertia02; + totalInertia10 += inertia10; + totalInertia11 += inertia11; + totalInertia12 += inertia12; + totalInertia20 += inertia20; + totalInertia21 += inertia21; + totalInertia22 += inertia22; + s = n; + } + this._mass = totalMass; + this._localInertia00 = totalInertia00; + this._localInertia01 = totalInertia01; + this._localInertia02 = totalInertia02; + this._localInertia10 = totalInertia10; + this._localInertia11 = totalInertia11; + this._localInertia12 = totalInertia12; + this._localInertia20 = totalInertia20; + this._localInertia21 = totalInertia21; + this._localInertia22 = totalInertia22; + if(this._mass > 0 && this._localInertia00 * (this._localInertia11 * this._localInertia22 - this._localInertia12 * this._localInertia21) - this._localInertia01 * (this._localInertia10 * this._localInertia22 - this._localInertia12 * this._localInertia20) + this._localInertia02 * (this._localInertia10 * this._localInertia21 - this._localInertia11 * this._localInertia20) > 0 && this._type == 0) { + this._invMass = 1 / this._mass; + let d00 = this._localInertia11 * this._localInertia22 - this._localInertia12 * this._localInertia21; + let d01 = this._localInertia10 * this._localInertia22 - this._localInertia12 * this._localInertia20; + let d02 = this._localInertia10 * this._localInertia21 - this._localInertia11 * this._localInertia20; + let d = this._localInertia00 * d00 - this._localInertia01 * d01 + this._localInertia02 * d02; + if(d < -1e-32 || d > 1e-32) { + d = 1 / d; + } + this._invLocalInertia00 = d00 * d; + this._invLocalInertia01 = -(this._localInertia01 * this._localInertia22 - this._localInertia02 * this._localInertia21) * d; + this._invLocalInertia02 = (this._localInertia01 * this._localInertia12 - this._localInertia02 * this._localInertia11) * d; + this._invLocalInertia10 = -d01 * d; + this._invLocalInertia11 = (this._localInertia00 * this._localInertia22 - this._localInertia02 * this._localInertia20) * d; + this._invLocalInertia12 = -(this._localInertia00 * this._localInertia12 - this._localInertia02 * this._localInertia10) * d; + this._invLocalInertia20 = d02 * d; + this._invLocalInertia21 = -(this._localInertia00 * this._localInertia21 - this._localInertia01 * this._localInertia20) * d; + this._invLocalInertia22 = (this._localInertia00 * this._localInertia11 - this._localInertia01 * this._localInertia10) * d; + this._invLocalInertiaWithoutRotFactor00 = this._invLocalInertia00; + this._invLocalInertiaWithoutRotFactor01 = this._invLocalInertia01; + this._invLocalInertiaWithoutRotFactor02 = this._invLocalInertia02; + this._invLocalInertiaWithoutRotFactor10 = this._invLocalInertia10; + this._invLocalInertiaWithoutRotFactor11 = this._invLocalInertia11; + this._invLocalInertiaWithoutRotFactor12 = this._invLocalInertia12; + this._invLocalInertiaWithoutRotFactor20 = this._invLocalInertia20; + this._invLocalInertiaWithoutRotFactor21 = this._invLocalInertia21; + this._invLocalInertiaWithoutRotFactor22 = this._invLocalInertia22; + this._invLocalInertia00 = this._invLocalInertiaWithoutRotFactor00 * this._rotFactor.x; + this._invLocalInertia01 = this._invLocalInertiaWithoutRotFactor01 * this._rotFactor.x; + this._invLocalInertia02 = this._invLocalInertiaWithoutRotFactor02 * this._rotFactor.x; + this._invLocalInertia10 = this._invLocalInertiaWithoutRotFactor10 * this._rotFactor.y; + this._invLocalInertia11 = this._invLocalInertiaWithoutRotFactor11 * this._rotFactor.y; + this._invLocalInertia12 = this._invLocalInertiaWithoutRotFactor12 * this._rotFactor.y; + this._invLocalInertia20 = this._invLocalInertiaWithoutRotFactor20 * this._rotFactor.z; + this._invLocalInertia21 = this._invLocalInertiaWithoutRotFactor21 * this._rotFactor.z; + this._invLocalInertia22 = this._invLocalInertiaWithoutRotFactor22 * this._rotFactor.z; + } else { + this._invMass = 0; + this._invLocalInertia00 = 0; + this._invLocalInertia01 = 0; + this._invLocalInertia02 = 0; + this._invLocalInertia10 = 0; + this._invLocalInertia11 = 0; + this._invLocalInertia12 = 0; + this._invLocalInertia20 = 0; + this._invLocalInertia21 = 0; + this._invLocalInertia22 = 0; + this._invLocalInertiaWithoutRotFactor00 = 0; + this._invLocalInertiaWithoutRotFactor01 = 0; + this._invLocalInertiaWithoutRotFactor02 = 0; + this._invLocalInertiaWithoutRotFactor10 = 0; + this._invLocalInertiaWithoutRotFactor11 = 0; + this._invLocalInertiaWithoutRotFactor12 = 0; + this._invLocalInertiaWithoutRotFactor20 = 0; + this._invLocalInertiaWithoutRotFactor21 = 0; + this._invLocalInertiaWithoutRotFactor22 = 0; + if(this._type == 0) { + this._type = 1; + } + } + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + this._sleeping = false; + this._sleepTime = 0; + } + getPosition() { + let v = new oimo.common.Vec3(); + v.x = this._transform._positionX; + v.y = this._transform._positionY; + v.z = this._transform._positionZ; + return v; + } + getPositionTo(position) { + position.x = this._transform._positionX; + position.y = this._transform._positionY; + position.z = this._transform._positionZ; + } + setPosition(position) { + this._transform._positionX = position.x; + this._transform._positionY = position.y; + this._transform._positionZ = position.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + translate(translation) { + let diffX; + let diffY; + let diffZ; + diffX = translation.x; + diffY = translation.y; + diffZ = translation.z; + this._transform._positionX += diffX; + this._transform._positionY += diffY; + this._transform._positionZ += diffZ; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + getRotation() { + let m = new oimo.common.Mat3(); + m.e00 = this._transform._rotation00; + m.e01 = this._transform._rotation01; + m.e02 = this._transform._rotation02; + m.e10 = this._transform._rotation10; + m.e11 = this._transform._rotation11; + m.e12 = this._transform._rotation12; + m.e20 = this._transform._rotation20; + m.e21 = this._transform._rotation21; + m.e22 = this._transform._rotation22; + return m; + } + getRotationTo(rotation) { + rotation.e00 = this._transform._rotation00; + rotation.e01 = this._transform._rotation01; + rotation.e02 = this._transform._rotation02; + rotation.e10 = this._transform._rotation10; + rotation.e11 = this._transform._rotation11; + rotation.e12 = this._transform._rotation12; + rotation.e20 = this._transform._rotation20; + rotation.e21 = this._transform._rotation21; + rotation.e22 = this._transform._rotation22; + } + setRotation(rotation) { + this._transform._rotation00 = rotation.e00; + this._transform._rotation01 = rotation.e01; + this._transform._rotation02 = rotation.e02; + this._transform._rotation10 = rotation.e10; + this._transform._rotation11 = rotation.e11; + this._transform._rotation12 = rotation.e12; + this._transform._rotation20 = rotation.e20; + this._transform._rotation21 = rotation.e21; + this._transform._rotation22 = rotation.e22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + setRotationXyz(eulerAngles) { + let xyzX; + let xyzY; + let xyzZ; + xyzX = eulerAngles.x; + xyzY = eulerAngles.y; + xyzZ = eulerAngles.z; + let sx = Math.sin(xyzX); + let sy = Math.sin(xyzY); + let sz = Math.sin(xyzZ); + let cx = Math.cos(xyzX); + let cy = Math.cos(xyzY); + let cz = Math.cos(xyzZ); + this._transform._rotation00 = cy * cz; + this._transform._rotation01 = -cy * sz; + this._transform._rotation02 = sy; + this._transform._rotation10 = cx * sz + cz * sx * sy; + this._transform._rotation11 = cx * cz - sx * sy * sz; + this._transform._rotation12 = -cy * sx; + this._transform._rotation20 = sx * sz - cx * cz * sy; + this._transform._rotation21 = cz * sx + cx * sy * sz; + this._transform._rotation22 = cx * cy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + rotate(rotation) { + let rot00; + let rot01; + let rot02; + let rot10; + let rot11; + let rot12; + let rot20; + let rot21; + let rot22; + rot00 = rotation.e00; + rot01 = rotation.e01; + rot02 = rotation.e02; + rot10 = rotation.e10; + rot11 = rotation.e11; + rot12 = rotation.e12; + rot20 = rotation.e20; + rot21 = rotation.e21; + rot22 = rotation.e22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot00 * this._transform._rotation00 + rot01 * this._transform._rotation10 + rot02 * this._transform._rotation20; + __tmp__01 = rot00 * this._transform._rotation01 + rot01 * this._transform._rotation11 + rot02 * this._transform._rotation21; + __tmp__02 = rot00 * this._transform._rotation02 + rot01 * this._transform._rotation12 + rot02 * this._transform._rotation22; + __tmp__10 = rot10 * this._transform._rotation00 + rot11 * this._transform._rotation10 + rot12 * this._transform._rotation20; + __tmp__11 = rot10 * this._transform._rotation01 + rot11 * this._transform._rotation11 + rot12 * this._transform._rotation21; + __tmp__12 = rot10 * this._transform._rotation02 + rot11 * this._transform._rotation12 + rot12 * this._transform._rotation22; + __tmp__20 = rot20 * this._transform._rotation00 + rot21 * this._transform._rotation10 + rot22 * this._transform._rotation20; + __tmp__21 = rot20 * this._transform._rotation01 + rot21 * this._transform._rotation11 + rot22 * this._transform._rotation21; + __tmp__22 = rot20 * this._transform._rotation02 + rot21 * this._transform._rotation12 + rot22 * this._transform._rotation22; + this._transform._rotation00 = __tmp__00; + this._transform._rotation01 = __tmp__01; + this._transform._rotation02 = __tmp__02; + this._transform._rotation10 = __tmp__10; + this._transform._rotation11 = __tmp__11; + this._transform._rotation12 = __tmp__12; + this._transform._rotation20 = __tmp__20; + this._transform._rotation21 = __tmp__21; + this._transform._rotation22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__011 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__021 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__101 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__111 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__121 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__201 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__211 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__221 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + let __tmp__002; + let __tmp__012; + let __tmp__022; + let __tmp__102; + let __tmp__112; + let __tmp__122; + let __tmp__202; + let __tmp__212; + let __tmp__222; + __tmp__002 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__012 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__022 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__102 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__112 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__122 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__202 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__212 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__222 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__002; + this._invInertia01 = __tmp__012; + this._invInertia02 = __tmp__022; + this._invInertia10 = __tmp__102; + this._invInertia11 = __tmp__112; + this._invInertia12 = __tmp__122; + this._invInertia20 = __tmp__202; + this._invInertia21 = __tmp__212; + this._invInertia22 = __tmp__222; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + rotateXyz(eulerAngles) { + let xyzX; + let xyzY; + let xyzZ; + let rot00; + let rot01; + let rot02; + let rot10; + let rot11; + let rot12; + let rot20; + let rot21; + let rot22; + xyzX = eulerAngles.x; + xyzY = eulerAngles.y; + xyzZ = eulerAngles.z; + let sx = Math.sin(xyzX); + let sy = Math.sin(xyzY); + let sz = Math.sin(xyzZ); + let cx = Math.cos(xyzX); + let cy = Math.cos(xyzY); + let cz = Math.cos(xyzZ); + rot00 = cy * cz; + rot01 = -cy * sz; + rot02 = sy; + rot10 = cx * sz + cz * sx * sy; + rot11 = cx * cz - sx * sy * sz; + rot12 = -cy * sx; + rot20 = sx * sz - cx * cz * sy; + rot21 = cz * sx + cx * sy * sz; + rot22 = cx * cy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = rot00 * this._transform._rotation00 + rot01 * this._transform._rotation10 + rot02 * this._transform._rotation20; + __tmp__01 = rot00 * this._transform._rotation01 + rot01 * this._transform._rotation11 + rot02 * this._transform._rotation21; + __tmp__02 = rot00 * this._transform._rotation02 + rot01 * this._transform._rotation12 + rot02 * this._transform._rotation22; + __tmp__10 = rot10 * this._transform._rotation00 + rot11 * this._transform._rotation10 + rot12 * this._transform._rotation20; + __tmp__11 = rot10 * this._transform._rotation01 + rot11 * this._transform._rotation11 + rot12 * this._transform._rotation21; + __tmp__12 = rot10 * this._transform._rotation02 + rot11 * this._transform._rotation12 + rot12 * this._transform._rotation22; + __tmp__20 = rot20 * this._transform._rotation00 + rot21 * this._transform._rotation10 + rot22 * this._transform._rotation20; + __tmp__21 = rot20 * this._transform._rotation01 + rot21 * this._transform._rotation11 + rot22 * this._transform._rotation21; + __tmp__22 = rot20 * this._transform._rotation02 + rot21 * this._transform._rotation12 + rot22 * this._transform._rotation22; + this._transform._rotation00 = __tmp__00; + this._transform._rotation01 = __tmp__01; + this._transform._rotation02 = __tmp__02; + this._transform._rotation10 = __tmp__10; + this._transform._rotation11 = __tmp__11; + this._transform._rotation12 = __tmp__12; + this._transform._rotation20 = __tmp__20; + this._transform._rotation21 = __tmp__21; + this._transform._rotation22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__011 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__021 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__101 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__111 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__121 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__201 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__211 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__221 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + let __tmp__002; + let __tmp__012; + let __tmp__022; + let __tmp__102; + let __tmp__112; + let __tmp__122; + let __tmp__202; + let __tmp__212; + let __tmp__222; + __tmp__002 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__012 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__022 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__102 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__112 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__122 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__202 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__212 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__222 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__002; + this._invInertia01 = __tmp__012; + this._invInertia02 = __tmp__022; + this._invInertia10 = __tmp__102; + this._invInertia11 = __tmp__112; + this._invInertia12 = __tmp__122; + this._invInertia20 = __tmp__202; + this._invInertia21 = __tmp__212; + this._invInertia22 = __tmp__222; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + getOrientation() { + let q = new oimo.common.Quat(); + let iqX; + let iqY; + let iqZ; + let iqW; + let e00 = this._transform._rotation00; + let e11 = this._transform._rotation11; + let e22 = this._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + iqW = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation21 - this._transform._rotation12) * s; + iqY = (this._transform._rotation02 - this._transform._rotation20) * s; + iqZ = (this._transform._rotation10 - this._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + iqX = 0.5 * s; + s = 0.5 / s; + iqY = (this._transform._rotation01 + this._transform._rotation10) * s; + iqZ = (this._transform._rotation02 + this._transform._rotation20) * s; + iqW = (this._transform._rotation21 - this._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation02 + this._transform._rotation20) * s; + iqY = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + iqY = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation01 + this._transform._rotation10) * s; + iqZ = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation02 - this._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation02 + this._transform._rotation20) * s; + iqY = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + q.x = iqX; + q.y = iqY; + q.z = iqZ; + q.w = iqW; + return q; + } + getOrientationTo(orientation) { + let iqX; + let iqY; + let iqZ; + let iqW; + let e00 = this._transform._rotation00; + let e11 = this._transform._rotation11; + let e22 = this._transform._rotation22; + let t = e00 + e11 + e22; + let s; + if(t > 0) { + s = Math.sqrt(t + 1); + iqW = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation21 - this._transform._rotation12) * s; + iqY = (this._transform._rotation02 - this._transform._rotation20) * s; + iqZ = (this._transform._rotation10 - this._transform._rotation01) * s; + } else if(e00 > e11) { + if(e00 > e22) { + s = Math.sqrt(e00 - e11 - e22 + 1); + iqX = 0.5 * s; + s = 0.5 / s; + iqY = (this._transform._rotation01 + this._transform._rotation10) * s; + iqZ = (this._transform._rotation02 + this._transform._rotation20) * s; + iqW = (this._transform._rotation21 - this._transform._rotation12) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation02 + this._transform._rotation20) * s; + iqY = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + } else if(e11 > e22) { + s = Math.sqrt(e11 - e22 - e00 + 1); + iqY = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation01 + this._transform._rotation10) * s; + iqZ = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation02 - this._transform._rotation20) * s; + } else { + s = Math.sqrt(e22 - e00 - e11 + 1); + iqZ = 0.5 * s; + s = 0.5 / s; + iqX = (this._transform._rotation02 + this._transform._rotation20) * s; + iqY = (this._transform._rotation12 + this._transform._rotation21) * s; + iqW = (this._transform._rotation10 - this._transform._rotation01) * s; + } + orientation.x = iqX; + orientation.y = iqY; + orientation.z = iqZ; + orientation.w = iqW; + } + setOrientation(quaternion) { + let qX; + let qY; + let qZ; + let qW; + qX = quaternion.x; + qY = quaternion.y; + qZ = quaternion.z; + qW = quaternion.w; + let x = qX; + let y = qY; + let z = qZ; + let w = qW; + let x2 = 2 * x; + let y2 = 2 * y; + let z2 = 2 * z; + let xx = x * x2; + let yy = y * y2; + let zz = z * z2; + let xy = x * y2; + let yz = y * z2; + let xz = x * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + this._transform._rotation00 = 1 - yy - zz; + this._transform._rotation01 = xy - wz; + this._transform._rotation02 = xz + wy; + this._transform._rotation10 = xy + wz; + this._transform._rotation11 = 1 - xx - zz; + this._transform._rotation12 = yz - wx; + this._transform._rotation20 = xz - wy; + this._transform._rotation21 = yz + wx; + this._transform._rotation22 = 1 - xx - yy; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + getTransform() { + let _this = this._transform; + let tf = new oimo.common.Transform(); + tf._positionX = _this._positionX; + tf._positionY = _this._positionY; + tf._positionZ = _this._positionZ; + tf._rotation00 = _this._rotation00; + tf._rotation01 = _this._rotation01; + tf._rotation02 = _this._rotation02; + tf._rotation10 = _this._rotation10; + tf._rotation11 = _this._rotation11; + tf._rotation12 = _this._rotation12; + tf._rotation20 = _this._rotation20; + tf._rotation21 = _this._rotation21; + tf._rotation22 = _this._rotation22; + return tf; + } + getTransformTo(transform) { + let transform1 = this._transform; + transform._positionX = transform1._positionX; + transform._positionY = transform1._positionY; + transform._positionZ = transform1._positionZ; + transform._rotation00 = transform1._rotation00; + transform._rotation01 = transform1._rotation01; + transform._rotation02 = transform1._rotation02; + transform._rotation10 = transform1._rotation10; + transform._rotation11 = transform1._rotation11; + transform._rotation12 = transform1._rotation12; + transform._rotation20 = transform1._rotation20; + transform._rotation21 = transform1._rotation21; + transform._rotation22 = transform1._rotation22; + } + setTransform(transform) { + this._transform._positionX = transform._positionX; + this._transform._positionY = transform._positionY; + this._transform._positionZ = transform._positionZ; + this._transform._rotation00 = transform._rotation00; + this._transform._rotation01 = transform._rotation01; + this._transform._rotation02 = transform._rotation02; + this._transform._rotation10 = transform._rotation10; + this._transform._rotation11 = transform._rotation11; + this._transform._rotation12 = transform._rotation12; + this._transform._rotation20 = transform._rotation20; + this._transform._rotation21 = transform._rotation21; + this._transform._rotation22 = transform._rotation22; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + let dst = this._ptransform; + let src = this._transform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + this._sleeping = false; + this._sleepTime = 0; + } + getMass() { + return this._mass; + } + getLocalInertia() { + let m = new oimo.common.Mat3(); + m.e00 = this._localInertia00; + m.e01 = this._localInertia01; + m.e02 = this._localInertia02; + m.e10 = this._localInertia10; + m.e11 = this._localInertia11; + m.e12 = this._localInertia12; + m.e20 = this._localInertia20; + m.e21 = this._localInertia21; + m.e22 = this._localInertia22; + return m; + } + getLocalInertiaTo(inertia) { + inertia.e00 = this._localInertia00; + inertia.e01 = this._localInertia01; + inertia.e02 = this._localInertia02; + inertia.e10 = this._localInertia10; + inertia.e11 = this._localInertia11; + inertia.e12 = this._localInertia12; + inertia.e20 = this._localInertia20; + inertia.e21 = this._localInertia21; + inertia.e22 = this._localInertia22; + } + getMassData() { + let md = new oimo.dynamics.rigidbody.MassData(); + md.mass = this._mass; + let m = md.localInertia; + m.e00 = this._localInertia00; + m.e01 = this._localInertia01; + m.e02 = this._localInertia02; + m.e10 = this._localInertia10; + m.e11 = this._localInertia11; + m.e12 = this._localInertia12; + m.e20 = this._localInertia20; + m.e21 = this._localInertia21; + m.e22 = this._localInertia22; + return md; + } + getMassDataTo(massData) { + massData.mass = this._mass; + let m = massData.localInertia; + m.e00 = this._localInertia00; + m.e01 = this._localInertia01; + m.e02 = this._localInertia02; + m.e10 = this._localInertia10; + m.e11 = this._localInertia11; + m.e12 = this._localInertia12; + m.e20 = this._localInertia20; + m.e21 = this._localInertia21; + m.e22 = this._localInertia22; + } + setMassData(massData) { + this._mass = massData.mass; + let m = massData.localInertia; + this._localInertia00 = m.e00; + this._localInertia01 = m.e01; + this._localInertia02 = m.e02; + this._localInertia10 = m.e10; + this._localInertia11 = m.e11; + this._localInertia12 = m.e12; + this._localInertia20 = m.e20; + this._localInertia21 = m.e21; + this._localInertia22 = m.e22; + if(this._mass > 0 && this._localInertia00 * (this._localInertia11 * this._localInertia22 - this._localInertia12 * this._localInertia21) - this._localInertia01 * (this._localInertia10 * this._localInertia22 - this._localInertia12 * this._localInertia20) + this._localInertia02 * (this._localInertia10 * this._localInertia21 - this._localInertia11 * this._localInertia20) > 0 && this._type == 0) { + this._invMass = 1 / this._mass; + let d00 = this._localInertia11 * this._localInertia22 - this._localInertia12 * this._localInertia21; + let d01 = this._localInertia10 * this._localInertia22 - this._localInertia12 * this._localInertia20; + let d02 = this._localInertia10 * this._localInertia21 - this._localInertia11 * this._localInertia20; + let d = this._localInertia00 * d00 - this._localInertia01 * d01 + this._localInertia02 * d02; + if(d < -1e-32 || d > 1e-32) { + d = 1 / d; + } + this._invLocalInertia00 = d00 * d; + this._invLocalInertia01 = -(this._localInertia01 * this._localInertia22 - this._localInertia02 * this._localInertia21) * d; + this._invLocalInertia02 = (this._localInertia01 * this._localInertia12 - this._localInertia02 * this._localInertia11) * d; + this._invLocalInertia10 = -d01 * d; + this._invLocalInertia11 = (this._localInertia00 * this._localInertia22 - this._localInertia02 * this._localInertia20) * d; + this._invLocalInertia12 = -(this._localInertia00 * this._localInertia12 - this._localInertia02 * this._localInertia10) * d; + this._invLocalInertia20 = d02 * d; + this._invLocalInertia21 = -(this._localInertia00 * this._localInertia21 - this._localInertia01 * this._localInertia20) * d; + this._invLocalInertia22 = (this._localInertia00 * this._localInertia11 - this._localInertia01 * this._localInertia10) * d; + this._invLocalInertiaWithoutRotFactor00 = this._invLocalInertia00; + this._invLocalInertiaWithoutRotFactor01 = this._invLocalInertia01; + this._invLocalInertiaWithoutRotFactor02 = this._invLocalInertia02; + this._invLocalInertiaWithoutRotFactor10 = this._invLocalInertia10; + this._invLocalInertiaWithoutRotFactor11 = this._invLocalInertia11; + this._invLocalInertiaWithoutRotFactor12 = this._invLocalInertia12; + this._invLocalInertiaWithoutRotFactor20 = this._invLocalInertia20; + this._invLocalInertiaWithoutRotFactor21 = this._invLocalInertia21; + this._invLocalInertiaWithoutRotFactor22 = this._invLocalInertia22; + this._invLocalInertia00 = this._invLocalInertiaWithoutRotFactor00 * this._rotFactor.x; + this._invLocalInertia01 = this._invLocalInertiaWithoutRotFactor01 * this._rotFactor.x; + this._invLocalInertia02 = this._invLocalInertiaWithoutRotFactor02 * this._rotFactor.x; + this._invLocalInertia10 = this._invLocalInertiaWithoutRotFactor10 * this._rotFactor.y; + this._invLocalInertia11 = this._invLocalInertiaWithoutRotFactor11 * this._rotFactor.y; + this._invLocalInertia12 = this._invLocalInertiaWithoutRotFactor12 * this._rotFactor.y; + this._invLocalInertia20 = this._invLocalInertiaWithoutRotFactor20 * this._rotFactor.z; + this._invLocalInertia21 = this._invLocalInertiaWithoutRotFactor21 * this._rotFactor.z; + this._invLocalInertia22 = this._invLocalInertiaWithoutRotFactor22 * this._rotFactor.z; + } else { + this._invMass = 0; + this._invLocalInertia00 = 0; + this._invLocalInertia01 = 0; + this._invLocalInertia02 = 0; + this._invLocalInertia10 = 0; + this._invLocalInertia11 = 0; + this._invLocalInertia12 = 0; + this._invLocalInertia20 = 0; + this._invLocalInertia21 = 0; + this._invLocalInertia22 = 0; + this._invLocalInertiaWithoutRotFactor00 = 0; + this._invLocalInertiaWithoutRotFactor01 = 0; + this._invLocalInertiaWithoutRotFactor02 = 0; + this._invLocalInertiaWithoutRotFactor10 = 0; + this._invLocalInertiaWithoutRotFactor11 = 0; + this._invLocalInertiaWithoutRotFactor12 = 0; + this._invLocalInertiaWithoutRotFactor20 = 0; + this._invLocalInertiaWithoutRotFactor21 = 0; + this._invLocalInertiaWithoutRotFactor22 = 0; + if(this._type == 0) { + this._type = 1; + } + } + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + this._sleeping = false; + this._sleepTime = 0; + } + getRotationFactor() { + let _this = this._rotFactor; + return new oimo.common.Vec3(_this.x,_this.y,_this.z); + } + setRotationFactor(rotationFactor) { + let _this = this._rotFactor; + _this.x = rotationFactor.x; + _this.y = rotationFactor.y; + _this.z = rotationFactor.z; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = this._transform._rotation00 * this._invLocalInertia00 + this._transform._rotation01 * this._invLocalInertia10 + this._transform._rotation02 * this._invLocalInertia20; + __tmp__01 = this._transform._rotation00 * this._invLocalInertia01 + this._transform._rotation01 * this._invLocalInertia11 + this._transform._rotation02 * this._invLocalInertia21; + __tmp__02 = this._transform._rotation00 * this._invLocalInertia02 + this._transform._rotation01 * this._invLocalInertia12 + this._transform._rotation02 * this._invLocalInertia22; + __tmp__10 = this._transform._rotation10 * this._invLocalInertia00 + this._transform._rotation11 * this._invLocalInertia10 + this._transform._rotation12 * this._invLocalInertia20; + __tmp__11 = this._transform._rotation10 * this._invLocalInertia01 + this._transform._rotation11 * this._invLocalInertia11 + this._transform._rotation12 * this._invLocalInertia21; + __tmp__12 = this._transform._rotation10 * this._invLocalInertia02 + this._transform._rotation11 * this._invLocalInertia12 + this._transform._rotation12 * this._invLocalInertia22; + __tmp__20 = this._transform._rotation20 * this._invLocalInertia00 + this._transform._rotation21 * this._invLocalInertia10 + this._transform._rotation22 * this._invLocalInertia20; + __tmp__21 = this._transform._rotation20 * this._invLocalInertia01 + this._transform._rotation21 * this._invLocalInertia11 + this._transform._rotation22 * this._invLocalInertia21; + __tmp__22 = this._transform._rotation20 * this._invLocalInertia02 + this._transform._rotation21 * this._invLocalInertia12 + this._transform._rotation22 * this._invLocalInertia22; + this._invInertia00 = __tmp__00; + this._invInertia01 = __tmp__01; + this._invInertia02 = __tmp__02; + this._invInertia10 = __tmp__10; + this._invInertia11 = __tmp__11; + this._invInertia12 = __tmp__12; + this._invInertia20 = __tmp__20; + this._invInertia21 = __tmp__21; + this._invInertia22 = __tmp__22; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = this._invInertia00 * this._transform._rotation00 + this._invInertia01 * this._transform._rotation01 + this._invInertia02 * this._transform._rotation02; + __tmp__011 = this._invInertia00 * this._transform._rotation10 + this._invInertia01 * this._transform._rotation11 + this._invInertia02 * this._transform._rotation12; + __tmp__021 = this._invInertia00 * this._transform._rotation20 + this._invInertia01 * this._transform._rotation21 + this._invInertia02 * this._transform._rotation22; + __tmp__101 = this._invInertia10 * this._transform._rotation00 + this._invInertia11 * this._transform._rotation01 + this._invInertia12 * this._transform._rotation02; + __tmp__111 = this._invInertia10 * this._transform._rotation10 + this._invInertia11 * this._transform._rotation11 + this._invInertia12 * this._transform._rotation12; + __tmp__121 = this._invInertia10 * this._transform._rotation20 + this._invInertia11 * this._transform._rotation21 + this._invInertia12 * this._transform._rotation22; + __tmp__201 = this._invInertia20 * this._transform._rotation00 + this._invInertia21 * this._transform._rotation01 + this._invInertia22 * this._transform._rotation02; + __tmp__211 = this._invInertia20 * this._transform._rotation10 + this._invInertia21 * this._transform._rotation11 + this._invInertia22 * this._transform._rotation12; + __tmp__221 = this._invInertia20 * this._transform._rotation20 + this._invInertia21 * this._transform._rotation21 + this._invInertia22 * this._transform._rotation22; + this._invInertia00 = __tmp__001; + this._invInertia01 = __tmp__011; + this._invInertia02 = __tmp__021; + this._invInertia10 = __tmp__101; + this._invInertia11 = __tmp__111; + this._invInertia12 = __tmp__121; + this._invInertia20 = __tmp__201; + this._invInertia21 = __tmp__211; + this._invInertia22 = __tmp__221; + this._invInertia00 *= this._rotFactor.x; + this._invInertia01 *= this._rotFactor.x; + this._invInertia02 *= this._rotFactor.x; + this._invInertia10 *= this._rotFactor.y; + this._invInertia11 *= this._rotFactor.y; + this._invInertia12 *= this._rotFactor.y; + this._invInertia20 *= this._rotFactor.z; + this._invInertia21 *= this._rotFactor.z; + this._invInertia22 *= this._rotFactor.z; + this._sleeping = false; + this._sleepTime = 0; + } + getLinearVelocity() { + let v = new oimo.common.Vec3(); + v.x = this._velX; + v.y = this._velY; + v.z = this._velZ; + return v; + } + getLinearVelocityTo(linearVelocity) { + linearVelocity.x = this._velX; + linearVelocity.y = this._velY; + linearVelocity.z = this._velZ; + } + setLinearVelocity(linearVelocity) { + if(this._type == 1) { + this._velX = 0; + this._velY = 0; + this._velZ = 0; + } else { + this._velX = linearVelocity.x; + this._velY = linearVelocity.y; + this._velZ = linearVelocity.z; + } + this._sleeping = false; + this._sleepTime = 0; + } + getAngularVelocity() { + let v = new oimo.common.Vec3(); + v.x = this._angVelX; + v.y = this._angVelY; + v.z = this._angVelZ; + return v; + } + getAngularVelocityTo(angularVelocity) { + angularVelocity.x = this._velX; + angularVelocity.y = this._velY; + angularVelocity.z = this._velZ; + } + setAngularVelocity(angularVelocity) { + if(this._type == 1) { + this._angVelX = 0; + this._angVelY = 0; + this._angVelZ = 0; + } else { + this._angVelX = angularVelocity.x; + this._angVelY = angularVelocity.y; + this._angVelZ = angularVelocity.z; + } + this._sleeping = false; + this._sleepTime = 0; + } + addLinearVelocity(linearVelocityChange) { + if(this._type != 1) { + let dX; + let dY; + let dZ; + dX = linearVelocityChange.x; + dY = linearVelocityChange.y; + dZ = linearVelocityChange.z; + this._velX += dX; + this._velY += dY; + this._velZ += dZ; + } + this._sleeping = false; + this._sleepTime = 0; + } + addAngularVelocity(angularVelocityChange) { + if(this._type != 1) { + let dX; + let dY; + let dZ; + dX = angularVelocityChange.x; + dY = angularVelocityChange.y; + dZ = angularVelocityChange.z; + this._angVelX += dX; + this._angVelY += dY; + this._angVelZ += dZ; + } + this._sleeping = false; + this._sleepTime = 0; + } + applyImpulse(impulse,positionInWorld) { + let impX; + let impY; + let impZ; + impX = impulse.x; + impY = impulse.y; + impZ = impulse.z; + this._velX += impX * this._invMass; + this._velY += impY * this._invMass; + this._velZ += impZ * this._invMass; + let aimpX; + let aimpY; + let aimpZ; + let posX; + let posY; + let posZ; + posX = positionInWorld.x; + posY = positionInWorld.y; + posZ = positionInWorld.z; + posX -= this._transform._positionX; + posY -= this._transform._positionY; + posZ -= this._transform._positionZ; + aimpX = posY * impZ - posZ * impY; + aimpY = posZ * impX - posX * impZ; + aimpZ = posX * impY - posY * impX; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._invInertia00 * aimpX + this._invInertia01 * aimpY + this._invInertia02 * aimpZ; + __tmp__Y = this._invInertia10 * aimpX + this._invInertia11 * aimpY + this._invInertia12 * aimpZ; + __tmp__Z = this._invInertia20 * aimpX + this._invInertia21 * aimpY + this._invInertia22 * aimpZ; + aimpX = __tmp__X; + aimpY = __tmp__Y; + aimpZ = __tmp__Z; + this._angVelX += aimpX; + this._angVelY += aimpY; + this._angVelZ += aimpZ; + this._sleeping = false; + this._sleepTime = 0; + } + applyLinearImpulse(impulse) { + let impX; + let impY; + let impZ; + impX = impulse.x; + impY = impulse.y; + impZ = impulse.z; + this._velX += impX * this._invMass; + this._velY += impY * this._invMass; + this._velZ += impZ * this._invMass; + this._sleeping = false; + this._sleepTime = 0; + } + applyAngularImpulse(impulse) { + let impX; + let impY; + let impZ; + impX = impulse.x; + impY = impulse.y; + impZ = impulse.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._invInertia00 * impX + this._invInertia01 * impY + this._invInertia02 * impZ; + __tmp__Y = this._invInertia10 * impX + this._invInertia11 * impY + this._invInertia12 * impZ; + __tmp__Z = this._invInertia20 * impX + this._invInertia21 * impY + this._invInertia22 * impZ; + impX = __tmp__X; + impY = __tmp__Y; + impZ = __tmp__Z; + this._angVelX += impX; + this._angVelY += impY; + this._angVelZ += impZ; + this._sleeping = false; + this._sleepTime = 0; + } + applyForce(force,positionInWorld) { + let iforceX; + let iforceY; + let iforceZ; + iforceX = force.x; + iforceY = force.y; + iforceZ = force.z; + this._forceX += iforceX; + this._forceY += iforceY; + this._forceZ += iforceZ; + let itorqueX; + let itorqueY; + let itorqueZ; + let posX; + let posY; + let posZ; + posX = positionInWorld.x; + posY = positionInWorld.y; + posZ = positionInWorld.z; + posX -= this._transform._positionX; + posY -= this._transform._positionY; + posZ -= this._transform._positionZ; + itorqueX = posY * iforceZ - posZ * iforceY; + itorqueY = posZ * iforceX - posX * iforceZ; + itorqueZ = posX * iforceY - posY * iforceX; + this._torqueX += itorqueX; + this._torqueY += itorqueY; + this._torqueZ += itorqueZ; + this._sleeping = false; + this._sleepTime = 0; + } + applyForceToCenter(force) { + let iforceX; + let iforceY; + let iforceZ; + iforceX = force.x; + iforceY = force.y; + iforceZ = force.z; + this._forceX += iforceX; + this._forceY += iforceY; + this._forceZ += iforceZ; + this._sleeping = false; + this._sleepTime = 0; + } + applyTorque(torque) { + let itorqueX; + let itorqueY; + let itorqueZ; + itorqueX = torque.x; + itorqueY = torque.y; + itorqueZ = torque.z; + this._torqueX += itorqueX; + this._torqueY += itorqueY; + this._torqueZ += itorqueZ; + this._sleeping = false; + this._sleepTime = 0; + } + getLinearContactImpulse() { + let res = new oimo.common.Vec3(); + res.x = this._linearContactImpulseX; + res.y = this._linearContactImpulseY; + res.z = this._linearContactImpulseZ; + return res; + } + getLinearContactImpulseTo(linearContactImpulse) { + linearContactImpulse.x = this._linearContactImpulseX; + linearContactImpulse.y = this._linearContactImpulseY; + linearContactImpulse.z = this._linearContactImpulseZ; + } + getAngularContactImpulse() { + let res = new oimo.common.Vec3(); + res.x = this._angularContactImpulseX; + res.y = this._angularContactImpulseY; + res.z = this._angularContactImpulseZ; + return res; + } + getAngularContactImpulseTo(angularContactImpulse) { + angularContactImpulse.x = this._angularContactImpulseX; + angularContactImpulse.y = this._angularContactImpulseY; + angularContactImpulse.z = this._angularContactImpulseZ; + } + getGravityScale() { + return this._gravityScale; + } + setGravityScale(gravityScale) { + this._gravityScale = gravityScale; + this._sleeping = false; + this._sleepTime = 0; + } + getLocalPoint(worldPoint) { + let vX; + let vY; + let vZ; + vX = worldPoint.x; + vY = worldPoint.y; + vZ = worldPoint.z; + vX -= this._transform._positionX; + vY -= this._transform._positionY; + vZ -= this._transform._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation10 * vY + this._transform._rotation20 * vZ; + __tmp__Y = this._transform._rotation01 * vX + this._transform._rotation11 * vY + this._transform._rotation21 * vZ; + __tmp__Z = this._transform._rotation02 * vX + this._transform._rotation12 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + let res = new oimo.common.Vec3(); + res.x = vX; + res.y = vY; + res.z = vZ; + return res; + } + getLocalPointTo(worldPoint,localPoint) { + let vX; + let vY; + let vZ; + vX = worldPoint.x; + vY = worldPoint.y; + vZ = worldPoint.z; + vX -= this._transform._positionX; + vY -= this._transform._positionY; + vZ -= this._transform._positionZ; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation10 * vY + this._transform._rotation20 * vZ; + __tmp__Y = this._transform._rotation01 * vX + this._transform._rotation11 * vY + this._transform._rotation21 * vZ; + __tmp__Z = this._transform._rotation02 * vX + this._transform._rotation12 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localPoint.x = vX; + localPoint.y = vY; + localPoint.z = vZ; + } + getLocalVector(worldVector) { + let vX; + let vY; + let vZ; + vX = worldVector.x; + vY = worldVector.y; + vZ = worldVector.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation10 * vY + this._transform._rotation20 * vZ; + __tmp__Y = this._transform._rotation01 * vX + this._transform._rotation11 * vY + this._transform._rotation21 * vZ; + __tmp__Z = this._transform._rotation02 * vX + this._transform._rotation12 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + let res = new oimo.common.Vec3(); + res.x = vX; + res.y = vY; + res.z = vZ; + return res; + } + getLocalVectorTo(worldVector,localVector) { + let vX; + let vY; + let vZ; + vX = worldVector.x; + vY = worldVector.y; + vZ = worldVector.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation10 * vY + this._transform._rotation20 * vZ; + __tmp__Y = this._transform._rotation01 * vX + this._transform._rotation11 * vY + this._transform._rotation21 * vZ; + __tmp__Z = this._transform._rotation02 * vX + this._transform._rotation12 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + localVector.x = vX; + localVector.y = vY; + localVector.z = vZ; + } + getWorldPoint(localPoint) { + let vX; + let vY; + let vZ; + vX = localPoint.x; + vY = localPoint.y; + vZ = localPoint.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation01 * vY + this._transform._rotation02 * vZ; + __tmp__Y = this._transform._rotation10 * vX + this._transform._rotation11 * vY + this._transform._rotation12 * vZ; + __tmp__Z = this._transform._rotation20 * vX + this._transform._rotation21 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + vX += this._transform._positionX; + vY += this._transform._positionY; + vZ += this._transform._positionZ; + let res = new oimo.common.Vec3(); + res.x = vX; + res.y = vY; + res.z = vZ; + return res; + } + getWorldPointTo(localPoint,worldPoint) { + let vX; + let vY; + let vZ; + vX = localPoint.x; + vY = localPoint.y; + vZ = localPoint.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation01 * vY + this._transform._rotation02 * vZ; + __tmp__Y = this._transform._rotation10 * vX + this._transform._rotation11 * vY + this._transform._rotation12 * vZ; + __tmp__Z = this._transform._rotation20 * vX + this._transform._rotation21 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + vX += this._transform._positionX; + vY += this._transform._positionY; + vZ += this._transform._positionZ; + worldPoint.x = vX; + worldPoint.y = vY; + worldPoint.z = vZ; + } + getWorldVector(localVector) { + let vX; + let vY; + let vZ; + vX = localVector.x; + vY = localVector.y; + vZ = localVector.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation01 * vY + this._transform._rotation02 * vZ; + __tmp__Y = this._transform._rotation10 * vX + this._transform._rotation11 * vY + this._transform._rotation12 * vZ; + __tmp__Z = this._transform._rotation20 * vX + this._transform._rotation21 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + let res = new oimo.common.Vec3(); + res.x = vX; + res.y = vY; + res.z = vZ; + return res; + } + getWorldVectorTo(localVector,worldVector) { + let vX; + let vY; + let vZ; + vX = localVector.x; + vY = localVector.y; + vZ = localVector.z; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = this._transform._rotation00 * vX + this._transform._rotation01 * vY + this._transform._rotation02 * vZ; + __tmp__Y = this._transform._rotation10 * vX + this._transform._rotation11 * vY + this._transform._rotation12 * vZ; + __tmp__Z = this._transform._rotation20 * vX + this._transform._rotation21 * vY + this._transform._rotation22 * vZ; + vX = __tmp__X; + vY = __tmp__Y; + vZ = __tmp__Z; + worldVector.x = vX; + worldVector.y = vY; + worldVector.z = vZ; + } + getNumShapes() { + return this._numShapes; + } + getShapeList() { + return this._shapeList; + } + getNumContectLinks() { + return this._numContactLinks; + } + getContactLinkList() { + return this._contactLinkList; + } + getNumJointLinks() { + return this._numJointLinks; + } + getJointLinkList() { + return this._jointLinkList; + } + addShape(shape) { + if(this._shapeList == null) { + this._shapeList = shape; + this._shapeListLast = shape; + } else { + this._shapeListLast._next = shape; + shape._prev = this._shapeListLast; + this._shapeListLast = shape; + } + this._numShapes++; + shape._rigidBody = this; + if(this._world != null) { + let _this = this._world; + shape._proxy = _this._broadPhase.createProxy(shape,shape._aabb); + shape._id = _this._shapeIdCount++; + _this._numShapes++; + } + this.updateMass(); + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + removeShape(shape) { + let prev = shape._prev; + let next = shape._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(shape == this._shapeList) { + this._shapeList = this._shapeList._next; + } + if(shape == this._shapeListLast) { + this._shapeListLast = this._shapeListLast._prev; + } + shape._next = null; + shape._prev = null; + this._numShapes--; + shape._rigidBody = null; + if(this._world != null) { + let _this = this._world; + _this._broadPhase.destroyProxy(shape._proxy); + shape._proxy = null; + shape._id = -1; + let cl = shape._rigidBody._contactLinkList; + while(cl != null) { + let n = cl._next; + let c = cl._contact; + if(c._s1 == shape || c._s2 == shape) { + let _this1 = cl._other; + _this1._sleeping = false; + _this1._sleepTime = 0; + let _this2 = _this._contactManager; + let prev = c._prev; + let next = c._next; + if(prev != null) { + prev._next = next; + } + if(next != null) { + next._prev = prev; + } + if(c == _this2._contactList) { + _this2._contactList = _this2._contactList._next; + } + if(c == _this2._contactListLast) { + _this2._contactListLast = _this2._contactListLast._prev; + } + c._next = null; + c._prev = null; + if(c._touching) { + let cc1 = c._s1._contactCallback; + let cc2 = c._s2._contactCallback; + if(cc1 == cc2) { + cc2 = null; + } + if(cc1 != null) { + cc1.endContact(c); + } + if(cc2 != null) { + cc2.endContact(c); + } + } + let prev1 = c._link1._prev; + let next1 = c._link1._next; + if(prev1 != null) { + prev1._next = next1; + } + if(next1 != null) { + next1._prev = prev1; + } + if(c._link1 == c._b1._contactLinkList) { + c._b1._contactLinkList = c._b1._contactLinkList._next; + } + if(c._link1 == c._b1._contactLinkListLast) { + c._b1._contactLinkListLast = c._b1._contactLinkListLast._prev; + } + c._link1._next = null; + c._link1._prev = null; + let prev2 = c._link2._prev; + let next2 = c._link2._next; + if(prev2 != null) { + prev2._next = next2; + } + if(next2 != null) { + next2._prev = prev2; + } + if(c._link2 == c._b2._contactLinkList) { + c._b2._contactLinkList = c._b2._contactLinkList._next; + } + if(c._link2 == c._b2._contactLinkListLast) { + c._b2._contactLinkListLast = c._b2._contactLinkListLast._prev; + } + c._link2._next = null; + c._link2._prev = null; + c._b1._numContactLinks--; + c._b2._numContactLinks--; + c._link1._other = null; + c._link2._other = null; + c._link1._contact = null; + c._link2._contact = null; + c._s1 = null; + c._s2 = null; + c._b1 = null; + c._b2 = null; + c._touching = false; + c._cachedDetectorData._clear(); + c._manifold._clear(); + c._detector = null; + let _this3 = c._contactConstraint; + _this3._s1 = null; + _this3._s2 = null; + _this3._b1 = null; + _this3._b2 = null; + _this3._tf1 = null; + _this3._tf2 = null; + c._next = _this2._contactPool; + _this2._contactPool = c; + _this2._numContacts--; + } + cl = n; + } + _this._numShapes--; + } + this.updateMass(); + let s = this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = this._ptransform; + let tf2 = this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + getType() { + return this._type; + } + setType(type) { + this._type = type; + this.updateMass(); + } + wakeUp() { + this._sleeping = false; + this._sleepTime = 0; + } + sleep() { + this._sleeping = true; + this._sleepTime = 0; + } + isSleeping() { + return this._sleeping; + } + getSleepTime() { + return this._sleepTime; + } + setAutoSleep(autoSleepEnabled) { + this._autoSleep = autoSleepEnabled; + this._sleeping = false; + this._sleepTime = 0; + } + getLinearDamping() { + return this._linearDamping; + } + setLinearDamping(damping) { + this._linearDamping = damping; + } + getAngularDamping() { + return this._angularDamping; + } + setAngularDamping(damping) { + this._angularDamping = damping; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.rigidbody.RigidBodyConfig = class oimo_dynamics_rigidbody_RigidBodyConfig { + constructor() { + this.position = new oimo.common.Vec3(); + this.rotation = new oimo.common.Mat3(); + this.linearVelocity = new oimo.common.Vec3(); + this.angularVelocity = new oimo.common.Vec3(); + this.type = 0; + this.autoSleep = true; + this.linearDamping = 0; + this.angularDamping = 0; + } +} +oimo.dynamics.rigidbody.RigidBodyType = class oimo_dynamics_rigidbody_RigidBodyType { +} +oimo.dynamics.rigidbody.Shape = class oimo_dynamics_rigidbody_Shape { + constructor(config) { + this._id = -1; + this._localTransform = new oimo.common.Transform(); + this._ptransform = new oimo.common.Transform(); + this._transform = new oimo.common.Transform(); + let v = config.position; + this._localTransform._positionX = v.x; + this._localTransform._positionY = v.y; + this._localTransform._positionZ = v.z; + let m = config.rotation; + this._localTransform._rotation00 = m.e00; + this._localTransform._rotation01 = m.e01; + this._localTransform._rotation02 = m.e02; + this._localTransform._rotation10 = m.e10; + this._localTransform._rotation11 = m.e11; + this._localTransform._rotation12 = m.e12; + this._localTransform._rotation20 = m.e20; + this._localTransform._rotation21 = m.e21; + this._localTransform._rotation22 = m.e22; + let dst = this._ptransform; + let src = this._localTransform; + dst._positionX = src._positionX; + dst._positionY = src._positionY; + dst._positionZ = src._positionZ; + dst._rotation00 = src._rotation00; + dst._rotation01 = src._rotation01; + dst._rotation02 = src._rotation02; + dst._rotation10 = src._rotation10; + dst._rotation11 = src._rotation11; + dst._rotation12 = src._rotation12; + dst._rotation20 = src._rotation20; + dst._rotation21 = src._rotation21; + dst._rotation22 = src._rotation22; + let dst1 = this._transform; + let src1 = this._localTransform; + dst1._positionX = src1._positionX; + dst1._positionY = src1._positionY; + dst1._positionZ = src1._positionZ; + dst1._rotation00 = src1._rotation00; + dst1._rotation01 = src1._rotation01; + dst1._rotation02 = src1._rotation02; + dst1._rotation10 = src1._rotation10; + dst1._rotation11 = src1._rotation11; + dst1._rotation12 = src1._rotation12; + dst1._rotation20 = src1._rotation20; + dst1._rotation21 = src1._rotation21; + dst1._rotation22 = src1._rotation22; + this._restitution = config.restitution; + this._friction = config.friction; + this._density = config.density; + this._geom = config.geometry; + this._collisionGroup = config.collisionGroup; + this._collisionMask = config.collisionMask; + this._contactCallback = config.contactCallback; + this._aabb = new oimo.collision.geometry.Aabb(); + this._proxy = null; + this.displacement = new oimo.common.Vec3(); + } + getFriction() { + return this._friction; + } + setFriction(friction) { + this._friction = friction; + } + getRestitution() { + return this._restitution; + } + setRestitution(restitution) { + this._restitution = restitution; + } + getLocalTransform() { + let _this = this._localTransform; + let tf = new oimo.common.Transform(); + tf._positionX = _this._positionX; + tf._positionY = _this._positionY; + tf._positionZ = _this._positionZ; + tf._rotation00 = _this._rotation00; + tf._rotation01 = _this._rotation01; + tf._rotation02 = _this._rotation02; + tf._rotation10 = _this._rotation10; + tf._rotation11 = _this._rotation11; + tf._rotation12 = _this._rotation12; + tf._rotation20 = _this._rotation20; + tf._rotation21 = _this._rotation21; + tf._rotation22 = _this._rotation22; + return tf; + } + getLocalTransformTo(transform) { + let transform1 = this._localTransform; + transform._positionX = transform1._positionX; + transform._positionY = transform1._positionY; + transform._positionZ = transform1._positionZ; + transform._rotation00 = transform1._rotation00; + transform._rotation01 = transform1._rotation01; + transform._rotation02 = transform1._rotation02; + transform._rotation10 = transform1._rotation10; + transform._rotation11 = transform1._rotation11; + transform._rotation12 = transform1._rotation12; + transform._rotation20 = transform1._rotation20; + transform._rotation21 = transform1._rotation21; + transform._rotation22 = transform1._rotation22; + } + getTransform() { + let _this = this._transform; + let tf = new oimo.common.Transform(); + tf._positionX = _this._positionX; + tf._positionY = _this._positionY; + tf._positionZ = _this._positionZ; + tf._rotation00 = _this._rotation00; + tf._rotation01 = _this._rotation01; + tf._rotation02 = _this._rotation02; + tf._rotation10 = _this._rotation10; + tf._rotation11 = _this._rotation11; + tf._rotation12 = _this._rotation12; + tf._rotation20 = _this._rotation20; + tf._rotation21 = _this._rotation21; + tf._rotation22 = _this._rotation22; + return tf; + } + getTransformTo(transform) { + let transform1 = this._transform; + transform._positionX = transform1._positionX; + transform._positionY = transform1._positionY; + transform._positionZ = transform1._positionZ; + transform._rotation00 = transform1._rotation00; + transform._rotation01 = transform1._rotation01; + transform._rotation02 = transform1._rotation02; + transform._rotation10 = transform1._rotation10; + transform._rotation11 = transform1._rotation11; + transform._rotation12 = transform1._rotation12; + transform._rotation20 = transform1._rotation20; + transform._rotation21 = transform1._rotation21; + transform._rotation22 = transform1._rotation22; + } + setLocalTransform(transform) { + let _this = this._localTransform; + _this._positionX = transform._positionX; + _this._positionY = transform._positionY; + _this._positionZ = transform._positionZ; + _this._rotation00 = transform._rotation00; + _this._rotation01 = transform._rotation01; + _this._rotation02 = transform._rotation02; + _this._rotation10 = transform._rotation10; + _this._rotation11 = transform._rotation11; + _this._rotation12 = transform._rotation12; + _this._rotation20 = transform._rotation20; + _this._rotation21 = transform._rotation21; + _this._rotation22 = transform._rotation22; + if(this._rigidBody != null) { + let _this = this._rigidBody; + _this.updateMass(); + let s = _this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = _this._ptransform; + let tf2 = _this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + } + getDensity() { + return this._density; + } + setDensity(density) { + this._density = density; + if(this._rigidBody != null) { + let _this = this._rigidBody; + _this.updateMass(); + let s = _this._shapeList; + while(s != null) { + let n = s._next; + let tf1 = _this._ptransform; + let tf2 = _this._transform; + let dst = s._ptransform; + let src1 = s._localTransform; + let __tmp__00; + let __tmp__01; + let __tmp__02; + let __tmp__10; + let __tmp__11; + let __tmp__12; + let __tmp__20; + let __tmp__21; + let __tmp__22; + __tmp__00 = tf1._rotation00 * src1._rotation00 + tf1._rotation01 * src1._rotation10 + tf1._rotation02 * src1._rotation20; + __tmp__01 = tf1._rotation00 * src1._rotation01 + tf1._rotation01 * src1._rotation11 + tf1._rotation02 * src1._rotation21; + __tmp__02 = tf1._rotation00 * src1._rotation02 + tf1._rotation01 * src1._rotation12 + tf1._rotation02 * src1._rotation22; + __tmp__10 = tf1._rotation10 * src1._rotation00 + tf1._rotation11 * src1._rotation10 + tf1._rotation12 * src1._rotation20; + __tmp__11 = tf1._rotation10 * src1._rotation01 + tf1._rotation11 * src1._rotation11 + tf1._rotation12 * src1._rotation21; + __tmp__12 = tf1._rotation10 * src1._rotation02 + tf1._rotation11 * src1._rotation12 + tf1._rotation12 * src1._rotation22; + __tmp__20 = tf1._rotation20 * src1._rotation00 + tf1._rotation21 * src1._rotation10 + tf1._rotation22 * src1._rotation20; + __tmp__21 = tf1._rotation20 * src1._rotation01 + tf1._rotation21 * src1._rotation11 + tf1._rotation22 * src1._rotation21; + __tmp__22 = tf1._rotation20 * src1._rotation02 + tf1._rotation21 * src1._rotation12 + tf1._rotation22 * src1._rotation22; + dst._rotation00 = __tmp__00; + dst._rotation01 = __tmp__01; + dst._rotation02 = __tmp__02; + dst._rotation10 = __tmp__10; + dst._rotation11 = __tmp__11; + dst._rotation12 = __tmp__12; + dst._rotation20 = __tmp__20; + dst._rotation21 = __tmp__21; + dst._rotation22 = __tmp__22; + let __tmp__X; + let __tmp__Y; + let __tmp__Z; + __tmp__X = tf1._rotation00 * src1._positionX + tf1._rotation01 * src1._positionY + tf1._rotation02 * src1._positionZ; + __tmp__Y = tf1._rotation10 * src1._positionX + tf1._rotation11 * src1._positionY + tf1._rotation12 * src1._positionZ; + __tmp__Z = tf1._rotation20 * src1._positionX + tf1._rotation21 * src1._positionY + tf1._rotation22 * src1._positionZ; + dst._positionX = __tmp__X; + dst._positionY = __tmp__Y; + dst._positionZ = __tmp__Z; + dst._positionX += tf1._positionX; + dst._positionY += tf1._positionY; + dst._positionZ += tf1._positionZ; + let dst1 = s._transform; + let src11 = s._localTransform; + let __tmp__001; + let __tmp__011; + let __tmp__021; + let __tmp__101; + let __tmp__111; + let __tmp__121; + let __tmp__201; + let __tmp__211; + let __tmp__221; + __tmp__001 = tf2._rotation00 * src11._rotation00 + tf2._rotation01 * src11._rotation10 + tf2._rotation02 * src11._rotation20; + __tmp__011 = tf2._rotation00 * src11._rotation01 + tf2._rotation01 * src11._rotation11 + tf2._rotation02 * src11._rotation21; + __tmp__021 = tf2._rotation00 * src11._rotation02 + tf2._rotation01 * src11._rotation12 + tf2._rotation02 * src11._rotation22; + __tmp__101 = tf2._rotation10 * src11._rotation00 + tf2._rotation11 * src11._rotation10 + tf2._rotation12 * src11._rotation20; + __tmp__111 = tf2._rotation10 * src11._rotation01 + tf2._rotation11 * src11._rotation11 + tf2._rotation12 * src11._rotation21; + __tmp__121 = tf2._rotation10 * src11._rotation02 + tf2._rotation11 * src11._rotation12 + tf2._rotation12 * src11._rotation22; + __tmp__201 = tf2._rotation20 * src11._rotation00 + tf2._rotation21 * src11._rotation10 + tf2._rotation22 * src11._rotation20; + __tmp__211 = tf2._rotation20 * src11._rotation01 + tf2._rotation21 * src11._rotation11 + tf2._rotation22 * src11._rotation21; + __tmp__221 = tf2._rotation20 * src11._rotation02 + tf2._rotation21 * src11._rotation12 + tf2._rotation22 * src11._rotation22; + dst1._rotation00 = __tmp__001; + dst1._rotation01 = __tmp__011; + dst1._rotation02 = __tmp__021; + dst1._rotation10 = __tmp__101; + dst1._rotation11 = __tmp__111; + dst1._rotation12 = __tmp__121; + dst1._rotation20 = __tmp__201; + dst1._rotation21 = __tmp__211; + dst1._rotation22 = __tmp__221; + let __tmp__X1; + let __tmp__Y1; + let __tmp__Z1; + __tmp__X1 = tf2._rotation00 * src11._positionX + tf2._rotation01 * src11._positionY + tf2._rotation02 * src11._positionZ; + __tmp__Y1 = tf2._rotation10 * src11._positionX + tf2._rotation11 * src11._positionY + tf2._rotation12 * src11._positionZ; + __tmp__Z1 = tf2._rotation20 * src11._positionX + tf2._rotation21 * src11._positionY + tf2._rotation22 * src11._positionZ; + dst1._positionX = __tmp__X1; + dst1._positionY = __tmp__Y1; + dst1._positionZ = __tmp__Z1; + dst1._positionX += tf2._positionX; + dst1._positionY += tf2._positionY; + dst1._positionZ += tf2._positionZ; + let minX; + let minY; + let minZ; + let maxX; + let maxY; + let maxZ; + s._geom._computeAabb(s._aabb,s._ptransform); + minX = s._aabb._minX; + minY = s._aabb._minY; + minZ = s._aabb._minZ; + maxX = s._aabb._maxX; + maxY = s._aabb._maxY; + maxZ = s._aabb._maxZ; + s._geom._computeAabb(s._aabb,s._transform); + s._aabb._minX = minX < s._aabb._minX ? minX : s._aabb._minX; + s._aabb._minY = minY < s._aabb._minY ? minY : s._aabb._minY; + s._aabb._minZ = minZ < s._aabb._minZ ? minZ : s._aabb._minZ; + s._aabb._maxX = maxX > s._aabb._maxX ? maxX : s._aabb._maxX; + s._aabb._maxY = maxY > s._aabb._maxY ? maxY : s._aabb._maxY; + s._aabb._maxZ = maxZ > s._aabb._maxZ ? maxZ : s._aabb._maxZ; + if(s._proxy != null) { + let dX; + let dY; + let dZ; + dX = s._transform._positionX - s._ptransform._positionX; + dY = s._transform._positionY - s._ptransform._positionY; + dZ = s._transform._positionZ - s._ptransform._positionZ; + let v = s.displacement; + v.x = dX; + v.y = dY; + v.z = dZ; + s._rigidBody._world._broadPhase.moveProxy(s._proxy,s._aabb,s.displacement); + } + s = n; + } + } + } + getAabb() { + return this._aabb.clone(); + } + getAabbTo(aabb) { + aabb.copyFrom(this._aabb); + } + getGeometry() { + return this._geom; + } + getRigidBody() { + return this._rigidBody; + } + getCollisionGroup() { + return this._collisionGroup; + } + setCollisionGroup(collisionGroup) { + this._collisionGroup = collisionGroup; + } + getCollisionMask() { + return this._collisionMask; + } + setCollisionMask(collisionMask) { + this._collisionMask = collisionMask; + } + getContactCallback() { + return this._contactCallback; + } + setContactCallback(callback) { + this._contactCallback = callback; + } + getPrev() { + return this._prev; + } + getNext() { + return this._next; + } +} +oimo.dynamics.rigidbody.ShapeConfig = class oimo_dynamics_rigidbody_ShapeConfig { + constructor() { + this.position = new oimo.common.Vec3(); + this.rotation = new oimo.common.Mat3(); + this.friction = oimo.common.Setting.defaultFriction; + this.restitution = oimo.common.Setting.defaultRestitution; + this.density = oimo.common.Setting.defaultDensity; + this.collisionGroup = oimo.common.Setting.defaultCollisionGroup; + this.collisionMask = oimo.common.Setting.defaultCollisionMask; + this.geometry = null; + this.contactCallback = null; + } +} +if(!oimo.m) oimo.m = {}; +oimo.m.M = class oimo_m_M { +} + +oimo.collision.broadphase.BroadPhaseType._BRUTE_FORCE = 1; +oimo.collision.broadphase.BroadPhaseType._BVH = 2; +oimo.collision.broadphase.BroadPhaseType.BRUTE_FORCE = 1; +oimo.collision.broadphase.BroadPhaseType.BVH = 2; +oimo.collision.broadphase.bvh.BvhInsertionStrategy.SIMPLE = 0; +oimo.collision.broadphase.bvh.BvhInsertionStrategy.MINIMIZE_SURFACE_AREA = 1; +oimo.collision.geometry.GeometryType._SPHERE = 0; +oimo.collision.geometry.GeometryType._BOX = 1; +oimo.collision.geometry.GeometryType._CYLINDER = 2; +oimo.collision.geometry.GeometryType._CONE = 3; +oimo.collision.geometry.GeometryType._CAPSULE = 4; +oimo.collision.geometry.GeometryType._CONVEX_HULL = 5; +oimo.collision.geometry.GeometryType._CONVEX_MIN = 0; +oimo.collision.geometry.GeometryType._CONVEX_MAX = 5; +oimo.collision.geometry.GeometryType.SPHERE = 0; +oimo.collision.geometry.GeometryType.BOX = 1; +oimo.collision.geometry.GeometryType.CYLINDER = 2; +oimo.collision.geometry.GeometryType.CONE = 3; +oimo.collision.geometry.GeometryType.CAPSULE = 4; +oimo.collision.geometry.GeometryType.CONVEX_HULL = 5; +oimo.collision.narrowphase.detector.BoxBoxDetector.EDGE_BIAS_MULT = 1.0; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.OK = 0; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.INVALID_TRIANGLE = 1; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.NO_ADJACENT_PAIR_INDEX = 2; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.NO_ADJACENT_TRIANGLE = 3; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.EDGE_LOOP_BROKEN = 4; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.NO_OUTER_TRIANGLE = 5; +oimo.collision.narrowphase.detector.gjkepa.EpaPolyhedronState.TRIANGLE_INVISIBLE = 6; +oimo.collision.narrowphase.detector.gjkepa.EpaTriangle.count = 0; +oimo.common.Vec3.numCreations = 0; +oimo.common.Setting.defaultFriction = 0.2; +oimo.common.Setting.defaultRestitution = 0.2; +oimo.common.Setting.defaultDensity = 1; +oimo.common.Setting.defaultCollisionGroup = 1; +oimo.common.Setting.defaultCollisionMask = 1; +oimo.common.Setting.maxTranslationPerStep = 20; +oimo.common.Setting.maxRotationPerStep = 3.14159265358979; +oimo.common.Setting.bvhProxyPadding = 0.1; +oimo.common.Setting.bvhIncrementalCollisionThreshold = 0.45; +oimo.common.Setting.defaultGJKMargin = 0.05; +oimo.common.Setting.enableGJKCaching = true; +oimo.common.Setting.maxEPAVertices = 128; +oimo.common.Setting.maxEPAPolyhedronFaces = 128; +oimo.common.Setting.contactEnableBounceThreshold = 0.5; +oimo.common.Setting.velocityBaumgarte = 0.2; +oimo.common.Setting.positionSplitImpulseBaumgarte = 0.4; +oimo.common.Setting.positionNgsBaumgarte = 1.0; +oimo.common.Setting.contactUseAlternativePositionCorrectionAlgorithmDepthThreshold = 0.05; +oimo.common.Setting.defaultContactPositionCorrectionAlgorithm = 0; +oimo.common.Setting.alternativeContactPositionCorrectionAlgorithm = 1; +oimo.common.Setting.contactPersistenceThreshold = 0.05; +oimo.common.Setting.maxManifoldPoints = 4; +oimo.common.Setting.defaultJointConstraintSolverType = 0; +oimo.common.Setting.defaultJointPositionCorrectionAlgorithm = 0; +oimo.common.Setting.jointWarmStartingFactorForBaungarte = 0.8; +oimo.common.Setting.jointWarmStartingFactor = 0.95; +oimo.common.Setting.minSpringDamperDampingRatio = 1e-6; +oimo.common.Setting.minRagdollMaxSwingAngle = 1e-6; +oimo.common.Setting.maxJacobianRows = 6; +oimo.common.Setting.directMlcpSolverEps = 1e-9; +oimo.common.Setting.islandInitialRigidBodyArraySize = 128; +oimo.common.Setting.islandInitialConstraintArraySize = 128; +oimo.common.Setting.sleepingVelocityThreshold = 0.2; +oimo.common.Setting.sleepingAngularVelocityThreshold = 0.5; +oimo.common.Setting.sleepingTimeThreshold = 1.0; +oimo.common.Setting.disableSleeping = false; +oimo.common.Setting.linearSlop = 0.005; +oimo.common.Setting.angularSlop = 0.017453292519943278; +oimo.collision.narrowphase.detector.gjkepa.GjkEpa.instance = new oimo.collision.narrowphase.detector.gjkepa.GjkEpa(); +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._SUCCEEDED = 0; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._GJK_FAILED_TO_MAKE_TETRAHEDRON = 1; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._GJK_DID_NOT_CONVERGE = 2; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._EPA_FAILED_TO_INIT = 257; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._EPA_FAILED_TO_ADD_VERTEX = 258; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState._EPA_DID_NOT_CONVERGE = 259; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.SUCCEEDED = 0; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.GJK_FAILED_TO_MAKE_TETRAHEDRON = 1; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.GJK_DID_NOT_CONVERGE = 2; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_FAILED_TO_INIT = 257; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_FAILED_TO_ADD_VERTEX = 258; +oimo.collision.narrowphase.detector.gjkepa.GjkEpaResultState.EPA_DID_NOT_CONVERGE = 259; +oimo.common.Mat3.numCreations = 0; +oimo.common.Mat4.numCreations = 0; +oimo.common.MathUtil.POSITIVE_INFINITY = 1e65536; +oimo.common.MathUtil.NEGATIVE_INFINITY = -1e65536; +oimo.common.MathUtil.PI = 3.14159265358979; +oimo.common.MathUtil.TWO_PI = 6.28318530717958; +oimo.common.MathUtil.HALF_PI = 1.570796326794895; +oimo.common.MathUtil.TO_RADIANS = 0.017453292519943278; +oimo.common.MathUtil.TO_DEGREES = 57.29577951308238; +oimo.common.Quat.numCreations = 0; +oimo.dynamics.common.DebugDraw.SPHERE_PHI_DIVISION = 8; +oimo.dynamics.common.DebugDraw.SPHERE_THETA_DIVISION = 4; +oimo.dynamics.common.DebugDraw.CIRCLE_THETA_DIVISION = 8; +oimo.dynamics.common.Performance.broadPhaseCollisionTime = 0; +oimo.dynamics.common.Performance.narrowPhaseCollisionTime = 0; +oimo.dynamics.common.Performance.dynamicsTime = 0; +oimo.dynamics.common.Performance.totalTime = 0; +oimo.dynamics.constraint.PositionCorrectionAlgorithm._BAUMGARTE = 0; +oimo.dynamics.constraint.PositionCorrectionAlgorithm._SPLIT_IMPULSE = 1; +oimo.dynamics.constraint.PositionCorrectionAlgorithm._NGS = 2; +oimo.dynamics.constraint.PositionCorrectionAlgorithm.BAUMGARTE = 0; +oimo.dynamics.constraint.PositionCorrectionAlgorithm.SPLIT_IMPULSE = 1; +oimo.dynamics.constraint.PositionCorrectionAlgorithm.NGS = 2; +oimo.dynamics.constraint.info.JacobianRow.BIT_LINEAR_SET = 1; +oimo.dynamics.constraint.info.JacobianRow.BIT_ANGULAR_SET = 2; +oimo.dynamics.constraint.joint.JointType._SPHERICAL = 0; +oimo.dynamics.constraint.joint.JointType._REVOLUTE = 1; +oimo.dynamics.constraint.joint.JointType._CYLINDRICAL = 2; +oimo.dynamics.constraint.joint.JointType._PRISMATIC = 3; +oimo.dynamics.constraint.joint.JointType._UNIVERSAL = 4; +oimo.dynamics.constraint.joint.JointType._RAGDOLL = 5; +oimo.dynamics.constraint.joint.JointType._GENERIC = 6; +oimo.dynamics.constraint.joint.JointType.SPHERICAL = 0; +oimo.dynamics.constraint.joint.JointType.REVOLUTE = 1; +oimo.dynamics.constraint.joint.JointType.CYLINDRICAL = 2; +oimo.dynamics.constraint.joint.JointType.PRISMATIC = 3; +oimo.dynamics.constraint.joint.JointType.UNIVERSAL = 4; +oimo.dynamics.constraint.joint.JointType.RAGDOLL = 5; +oimo.dynamics.constraint.joint.JointType.GENERIC = 6; +oimo.dynamics.constraint.solver.ConstraintSolverType._ITERATIVE = 0; +oimo.dynamics.constraint.solver.ConstraintSolverType._DIRECT = 1; +oimo.dynamics.constraint.solver.ConstraintSolverType.ITERATIVE = 0; +oimo.dynamics.constraint.solver.ConstraintSolverType.DIRECT = 1; +oimo.dynamics.rigidbody.RigidBodyType._DYNAMIC = 0; +oimo.dynamics.rigidbody.RigidBodyType._STATIC = 1; +oimo.dynamics.rigidbody.RigidBodyType._KINEMATIC = 2; +oimo.dynamics.rigidbody.RigidBodyType.DYNAMIC = 0; +oimo.dynamics.rigidbody.RigidBodyType.STATIC = 1; +oimo.dynamics.rigidbody.RigidBodyType.KINEMATIC = 2; +export {oimo}; diff --git a/renderer/jsm/libs/OimoPhysics/index.js b/renderer/jsm/libs/OimoPhysics/index.js new file mode 100644 index 0000000..0bf5789 --- /dev/null +++ b/renderer/jsm/libs/OimoPhysics/index.js @@ -0,0 +1,43 @@ +import {oimo} from './OimoPhysics.js'; + +// dynamics +export const World = oimo.dynamics.World; +export const RigidBodyType = oimo.dynamics.rigidbody.RigidBodyType; +export const RigidBodyConfig = oimo.dynamics.rigidbody.RigidBodyConfig; +export const ShapeConfig = oimo.dynamics.rigidbody.ShapeConfig; +export const RigidBody = oimo.dynamics.rigidbody.RigidBody; +export const Shape = oimo.dynamics.rigidbody.Shape; +export const SphericalJoint = oimo.dynamics.constraint.joint.SphericalJoint; +export const RevoluteJointConfig = oimo.dynamics.constraint.joint.RevoluteJointConfig; +export const UniversalJointConfig = oimo.dynamics.constraint.joint.UniversalJointConfig; +export const CylindricalJoint = oimo.dynamics.constraint.joint.CylindricalJoint; +export const PrismaticJoint = oimo.dynamics.constraint.joint.PrismaticJoint; +export const PrismaticJointConfig = oimo.dynamics.constraint.joint.PrismaticJointConfig; +export const RevoluteJoint = oimo.dynamics.constraint.joint.RevoluteJoint; +export const RagdollJoint = oimo.dynamics.constraint.joint.RagdollJoint; +export const CylindricalJointConfig = oimo.dynamics.constraint.joint.CylindricalJointConfig; +export const SphericalJointConfig = oimo.dynamics.constraint.joint.SphericalJointConfig; +export const RagdollJointConfig = oimo.dynamics.constraint.joint.RagdollJointConfig; +export const SpringDamper = oimo.dynamics.constraint.joint.SpringDamper; +export const TranslationalLimitMotor = oimo.dynamics.constraint.joint.TranslationalLimitMotor; +export const RotationalLimitMotor = oimo.dynamics.constraint.joint.RotationalLimitMotor; +export const UniversalJoint = oimo.dynamics.constraint.joint.UniversalJoint; + +// common +export const Vec3 = oimo.common.Vec3; +export const Quat = oimo.common.Quat; +export const Mat3 = oimo.common.Mat3; +export const MathUtil = oimo.common.MathUtil; +export const Transform = oimo.common.Transform; + +// collision +export const OCapsuleGeometry = oimo.collision.geometry.CapsuleGeometry; +export const OConvexHullGeometry = oimo.collision.geometry.ConvexHullGeometry; +export const OBoxGeometry = oimo.collision.geometry.BoxGeometry; +export const OSphereGeometry = oimo.collision.geometry.SphereGeometry; +export const OCylinderGeometry = oimo.collision.geometry.CylinderGeometry; +export const OConeGeometry = oimo.collision.geometry.ConeGeometry; +export const OGeometry = oimo.collision.geometry.Geometry; + +// callback +export const RayCastClosest = oimo.dynamics.callback.RayCastClosest; diff --git a/renderer/jsm/libs/ammo.wasm.js b/renderer/jsm/libs/ammo.wasm.js new file mode 100644 index 0000000..a7f835c --- /dev/null +++ b/renderer/jsm/libs/ammo.wasm.js @@ -0,0 +1,822 @@ + +// This is ammo.js, a port of Bullet Physics to JavaScript. zlib licensed. + +var Ammo = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(Ammo) { + Ammo = Ammo || {}; + + +var b;b||(b=typeof Ammo !== 'undefined' ? Ammo : {});var ba;b.ready=new Promise(function(a){ba=a});var ca={},da;for(da in b)b.hasOwnProperty(da)&&(ca[da]=b[da]);var ea=!1,fa=!1,ha=!1,ia=!1;ea="object"===typeof window;fa="function"===typeof importScripts;ha="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node;ia=!ea&&!ha&&!fa;var ja="",ka,la,ma,na; +if(ha)ja=fa?require("path").dirname(ja)+"/":__dirname+"/",ka=function(a,c){ma||(ma=require("fs"));na||(na=require("path"));a=na.normalize(a);return ma.readFileSync(a,c?null:"utf8")},la=function(a){a=ka(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},1>=2;d=za[a++];)Xa.push(105>d?Ca[++c>>1]:Aa[c]),++c;return Xa}var Za={f:function(){oa()},c:function(a,c,d){c=Ya(c,d);return Va[a].apply(null,c)},a:function(a,c,d){c=Ya(c,d);return Va[a].apply(null,c)},d:function(a,c,d){za.copyWithin(a,c,c+d)},e:function(){oa("OOM")},b:function(a){var c=Date.now();Aa[a>>2]=c/1E3|0;Aa[a+4>>2]=c%1E3*1E3|0;return 0},memory:sa,table:ua}; +(function(){function a(g){b.asm=g.exports;Ma--;b.monitorRunDependencies&&b.monitorRunDependencies(Ma);0==Ma&&(null!==Na&&(clearInterval(Na),Na=null),Oa&&(g=Oa,Oa=null,g()))}function c(g){a(g.instance)}function d(g){return Ua().then(function(n){return WebAssembly.instantiate(n,e)}).then(g,function(n){qa("failed to asynchronously prepare wasm: "+n);oa(n)})}var e={a:Za};Ma++;b.monitorRunDependencies&&b.monitorRunDependencies(Ma);if(b.instantiateWasm)try{return b.instantiateWasm(e,a)}catch(g){return qa("Module.instantiateWasm callback failed with error: "+ +g),!1}(function(){if(ra||"function"!==typeof WebAssembly.instantiateStreaming||Ra()||Pa("file://")||"function"!==typeof fetch)return d(c);fetch(Qa,{credentials:"same-origin"}).then(function(g){return WebAssembly.instantiateStreaming(g,e).then(c,function(n){qa("wasm streaming compile failed: "+n);qa("falling back to ArrayBuffer instantiation");return d(c)})})})();return{}})();var Wa=b.___wasm_call_ctors=function(){return(Wa=b.___wasm_call_ctors=b.asm.g).apply(null,arguments)}; +b.___em_js__array_bounds_check_error=function(){return(b.___em_js__array_bounds_check_error=b.asm.h).apply(null,arguments)}; +var $a=b._emscripten_bind_btCollisionWorld_getDispatcher_0=function(){return($a=b._emscripten_bind_btCollisionWorld_getDispatcher_0=b.asm.i).apply(null,arguments)},ab=b._emscripten_bind_btCollisionWorld_rayTest_3=function(){return(ab=b._emscripten_bind_btCollisionWorld_rayTest_3=b.asm.j).apply(null,arguments)},bb=b._emscripten_bind_btCollisionWorld_getPairCache_0=function(){return(bb=b._emscripten_bind_btCollisionWorld_getPairCache_0=b.asm.k).apply(null,arguments)},cb=b._emscripten_bind_btCollisionWorld_getDispatchInfo_0= +function(){return(cb=b._emscripten_bind_btCollisionWorld_getDispatchInfo_0=b.asm.l).apply(null,arguments)},db=b._emscripten_bind_btCollisionWorld_addCollisionObject_1=function(){return(db=b._emscripten_bind_btCollisionWorld_addCollisionObject_1=b.asm.m).apply(null,arguments)},eb=b._emscripten_bind_btCollisionWorld_addCollisionObject_2=function(){return(eb=b._emscripten_bind_btCollisionWorld_addCollisionObject_2=b.asm.n).apply(null,arguments)},fb=b._emscripten_bind_btCollisionWorld_addCollisionObject_3= +function(){return(fb=b._emscripten_bind_btCollisionWorld_addCollisionObject_3=b.asm.o).apply(null,arguments)},gb=b._emscripten_bind_btCollisionWorld_removeCollisionObject_1=function(){return(gb=b._emscripten_bind_btCollisionWorld_removeCollisionObject_1=b.asm.p).apply(null,arguments)},hb=b._emscripten_bind_btCollisionWorld_getBroadphase_0=function(){return(hb=b._emscripten_bind_btCollisionWorld_getBroadphase_0=b.asm.q).apply(null,arguments)},ib=b._emscripten_bind_btCollisionWorld_convexSweepTest_5= +function(){return(ib=b._emscripten_bind_btCollisionWorld_convexSweepTest_5=b.asm.r).apply(null,arguments)},jb=b._emscripten_bind_btCollisionWorld_contactPairTest_3=function(){return(jb=b._emscripten_bind_btCollisionWorld_contactPairTest_3=b.asm.s).apply(null,arguments)},kb=b._emscripten_bind_btCollisionWorld_contactTest_2=function(){return(kb=b._emscripten_bind_btCollisionWorld_contactTest_2=b.asm.t).apply(null,arguments)},lb=b._emscripten_bind_btCollisionWorld_updateSingleAabb_1=function(){return(lb= +b._emscripten_bind_btCollisionWorld_updateSingleAabb_1=b.asm.u).apply(null,arguments)},mb=b._emscripten_bind_btCollisionWorld_setDebugDrawer_1=function(){return(mb=b._emscripten_bind_btCollisionWorld_setDebugDrawer_1=b.asm.v).apply(null,arguments)},nb=b._emscripten_bind_btCollisionWorld_getDebugDrawer_0=function(){return(nb=b._emscripten_bind_btCollisionWorld_getDebugDrawer_0=b.asm.w).apply(null,arguments)},ob=b._emscripten_bind_btCollisionWorld_debugDrawWorld_0=function(){return(ob=b._emscripten_bind_btCollisionWorld_debugDrawWorld_0= +b.asm.x).apply(null,arguments)},pb=b._emscripten_bind_btCollisionWorld_debugDrawObject_3=function(){return(pb=b._emscripten_bind_btCollisionWorld_debugDrawObject_3=b.asm.y).apply(null,arguments)},qb=b._emscripten_bind_btCollisionWorld___destroy___0=function(){return(qb=b._emscripten_bind_btCollisionWorld___destroy___0=b.asm.z).apply(null,arguments)},rb=b._emscripten_bind_btCollisionShape_setLocalScaling_1=function(){return(rb=b._emscripten_bind_btCollisionShape_setLocalScaling_1=b.asm.A).apply(null, +arguments)},sb=b._emscripten_bind_btCollisionShape_getLocalScaling_0=function(){return(sb=b._emscripten_bind_btCollisionShape_getLocalScaling_0=b.asm.B).apply(null,arguments)},tb=b._emscripten_bind_btCollisionShape_calculateLocalInertia_2=function(){return(tb=b._emscripten_bind_btCollisionShape_calculateLocalInertia_2=b.asm.C).apply(null,arguments)},ub=b._emscripten_bind_btCollisionShape_setMargin_1=function(){return(ub=b._emscripten_bind_btCollisionShape_setMargin_1=b.asm.D).apply(null,arguments)}, +vb=b._emscripten_bind_btCollisionShape_getMargin_0=function(){return(vb=b._emscripten_bind_btCollisionShape_getMargin_0=b.asm.E).apply(null,arguments)},wb=b._emscripten_bind_btCollisionShape___destroy___0=function(){return(wb=b._emscripten_bind_btCollisionShape___destroy___0=b.asm.F).apply(null,arguments)},xb=b._emscripten_bind_btCollisionObject_setAnisotropicFriction_2=function(){return(xb=b._emscripten_bind_btCollisionObject_setAnisotropicFriction_2=b.asm.G).apply(null,arguments)},yb=b._emscripten_bind_btCollisionObject_getCollisionShape_0= +function(){return(yb=b._emscripten_bind_btCollisionObject_getCollisionShape_0=b.asm.H).apply(null,arguments)},zb=b._emscripten_bind_btCollisionObject_setContactProcessingThreshold_1=function(){return(zb=b._emscripten_bind_btCollisionObject_setContactProcessingThreshold_1=b.asm.I).apply(null,arguments)},Ab=b._emscripten_bind_btCollisionObject_setActivationState_1=function(){return(Ab=b._emscripten_bind_btCollisionObject_setActivationState_1=b.asm.J).apply(null,arguments)},Bb=b._emscripten_bind_btCollisionObject_forceActivationState_1= +function(){return(Bb=b._emscripten_bind_btCollisionObject_forceActivationState_1=b.asm.K).apply(null,arguments)},Cb=b._emscripten_bind_btCollisionObject_activate_0=function(){return(Cb=b._emscripten_bind_btCollisionObject_activate_0=b.asm.L).apply(null,arguments)},Db=b._emscripten_bind_btCollisionObject_activate_1=function(){return(Db=b._emscripten_bind_btCollisionObject_activate_1=b.asm.M).apply(null,arguments)},Eb=b._emscripten_bind_btCollisionObject_isActive_0=function(){return(Eb=b._emscripten_bind_btCollisionObject_isActive_0= +b.asm.N).apply(null,arguments)},Fb=b._emscripten_bind_btCollisionObject_isKinematicObject_0=function(){return(Fb=b._emscripten_bind_btCollisionObject_isKinematicObject_0=b.asm.O).apply(null,arguments)},Gb=b._emscripten_bind_btCollisionObject_isStaticObject_0=function(){return(Gb=b._emscripten_bind_btCollisionObject_isStaticObject_0=b.asm.P).apply(null,arguments)},Hb=b._emscripten_bind_btCollisionObject_isStaticOrKinematicObject_0=function(){return(Hb=b._emscripten_bind_btCollisionObject_isStaticOrKinematicObject_0= +b.asm.Q).apply(null,arguments)},Ib=b._emscripten_bind_btCollisionObject_getRestitution_0=function(){return(Ib=b._emscripten_bind_btCollisionObject_getRestitution_0=b.asm.R).apply(null,arguments)},Jb=b._emscripten_bind_btCollisionObject_getFriction_0=function(){return(Jb=b._emscripten_bind_btCollisionObject_getFriction_0=b.asm.S).apply(null,arguments)},Kb=b._emscripten_bind_btCollisionObject_getRollingFriction_0=function(){return(Kb=b._emscripten_bind_btCollisionObject_getRollingFriction_0=b.asm.T).apply(null, +arguments)},Lb=b._emscripten_bind_btCollisionObject_setRestitution_1=function(){return(Lb=b._emscripten_bind_btCollisionObject_setRestitution_1=b.asm.U).apply(null,arguments)},Mb=b._emscripten_bind_btCollisionObject_setFriction_1=function(){return(Mb=b._emscripten_bind_btCollisionObject_setFriction_1=b.asm.V).apply(null,arguments)},Nb=b._emscripten_bind_btCollisionObject_setRollingFriction_1=function(){return(Nb=b._emscripten_bind_btCollisionObject_setRollingFriction_1=b.asm.W).apply(null,arguments)}, +Ob=b._emscripten_bind_btCollisionObject_getWorldTransform_0=function(){return(Ob=b._emscripten_bind_btCollisionObject_getWorldTransform_0=b.asm.X).apply(null,arguments)},Pb=b._emscripten_bind_btCollisionObject_getCollisionFlags_0=function(){return(Pb=b._emscripten_bind_btCollisionObject_getCollisionFlags_0=b.asm.Y).apply(null,arguments)},Qb=b._emscripten_bind_btCollisionObject_setCollisionFlags_1=function(){return(Qb=b._emscripten_bind_btCollisionObject_setCollisionFlags_1=b.asm.Z).apply(null,arguments)}, +Sb=b._emscripten_bind_btCollisionObject_setWorldTransform_1=function(){return(Sb=b._emscripten_bind_btCollisionObject_setWorldTransform_1=b.asm._).apply(null,arguments)},Tb=b._emscripten_bind_btCollisionObject_setCollisionShape_1=function(){return(Tb=b._emscripten_bind_btCollisionObject_setCollisionShape_1=b.asm.$).apply(null,arguments)},Ub=b._emscripten_bind_btCollisionObject_setCcdMotionThreshold_1=function(){return(Ub=b._emscripten_bind_btCollisionObject_setCcdMotionThreshold_1=b.asm.aa).apply(null, +arguments)},Vb=b._emscripten_bind_btCollisionObject_setCcdSweptSphereRadius_1=function(){return(Vb=b._emscripten_bind_btCollisionObject_setCcdSweptSphereRadius_1=b.asm.ba).apply(null,arguments)},Wb=b._emscripten_bind_btCollisionObject_getUserIndex_0=function(){return(Wb=b._emscripten_bind_btCollisionObject_getUserIndex_0=b.asm.ca).apply(null,arguments)},Xb=b._emscripten_bind_btCollisionObject_setUserIndex_1=function(){return(Xb=b._emscripten_bind_btCollisionObject_setUserIndex_1=b.asm.da).apply(null, +arguments)},Yb=b._emscripten_bind_btCollisionObject_getUserPointer_0=function(){return(Yb=b._emscripten_bind_btCollisionObject_getUserPointer_0=b.asm.ea).apply(null,arguments)},Zb=b._emscripten_bind_btCollisionObject_setUserPointer_1=function(){return(Zb=b._emscripten_bind_btCollisionObject_setUserPointer_1=b.asm.fa).apply(null,arguments)},$b=b._emscripten_bind_btCollisionObject_getBroadphaseHandle_0=function(){return($b=b._emscripten_bind_btCollisionObject_getBroadphaseHandle_0=b.asm.ga).apply(null, +arguments)},ac=b._emscripten_bind_btCollisionObject___destroy___0=function(){return(ac=b._emscripten_bind_btCollisionObject___destroy___0=b.asm.ha).apply(null,arguments)},bc=b._emscripten_bind_btDynamicsWorld_addAction_1=function(){return(bc=b._emscripten_bind_btDynamicsWorld_addAction_1=b.asm.ia).apply(null,arguments)},cc=b._emscripten_bind_btDynamicsWorld_removeAction_1=function(){return(cc=b._emscripten_bind_btDynamicsWorld_removeAction_1=b.asm.ja).apply(null,arguments)},dc=b._emscripten_bind_btDynamicsWorld_getSolverInfo_0= +function(){return(dc=b._emscripten_bind_btDynamicsWorld_getSolverInfo_0=b.asm.ka).apply(null,arguments)},ec=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_1=function(){return(ec=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_1=b.asm.la).apply(null,arguments)},fc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_2=function(){return(fc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_2=b.asm.ma).apply(null,arguments)},hc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_3= +function(){return(hc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_3=b.asm.na).apply(null,arguments)},ic=b._emscripten_bind_btDynamicsWorld_getDispatcher_0=function(){return(ic=b._emscripten_bind_btDynamicsWorld_getDispatcher_0=b.asm.oa).apply(null,arguments)},jc=b._emscripten_bind_btDynamicsWorld_rayTest_3=function(){return(jc=b._emscripten_bind_btDynamicsWorld_rayTest_3=b.asm.pa).apply(null,arguments)},kc=b._emscripten_bind_btDynamicsWorld_getPairCache_0=function(){return(kc=b._emscripten_bind_btDynamicsWorld_getPairCache_0= +b.asm.qa).apply(null,arguments)},lc=b._emscripten_bind_btDynamicsWorld_getDispatchInfo_0=function(){return(lc=b._emscripten_bind_btDynamicsWorld_getDispatchInfo_0=b.asm.ra).apply(null,arguments)},mc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_1=function(){return(mc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_1=b.asm.sa).apply(null,arguments)},nc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_2=function(){return(nc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_2= +b.asm.ta).apply(null,arguments)},oc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_3=function(){return(oc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_3=b.asm.ua).apply(null,arguments)},pc=b._emscripten_bind_btDynamicsWorld_removeCollisionObject_1=function(){return(pc=b._emscripten_bind_btDynamicsWorld_removeCollisionObject_1=b.asm.va).apply(null,arguments)},qc=b._emscripten_bind_btDynamicsWorld_getBroadphase_0=function(){return(qc=b._emscripten_bind_btDynamicsWorld_getBroadphase_0= +b.asm.wa).apply(null,arguments)},rc=b._emscripten_bind_btDynamicsWorld_convexSweepTest_5=function(){return(rc=b._emscripten_bind_btDynamicsWorld_convexSweepTest_5=b.asm.xa).apply(null,arguments)},sc=b._emscripten_bind_btDynamicsWorld_contactPairTest_3=function(){return(sc=b._emscripten_bind_btDynamicsWorld_contactPairTest_3=b.asm.ya).apply(null,arguments)},tc=b._emscripten_bind_btDynamicsWorld_contactTest_2=function(){return(tc=b._emscripten_bind_btDynamicsWorld_contactTest_2=b.asm.za).apply(null, +arguments)},uc=b._emscripten_bind_btDynamicsWorld_updateSingleAabb_1=function(){return(uc=b._emscripten_bind_btDynamicsWorld_updateSingleAabb_1=b.asm.Aa).apply(null,arguments)},vc=b._emscripten_bind_btDynamicsWorld_setDebugDrawer_1=function(){return(vc=b._emscripten_bind_btDynamicsWorld_setDebugDrawer_1=b.asm.Ba).apply(null,arguments)},wc=b._emscripten_bind_btDynamicsWorld_getDebugDrawer_0=function(){return(wc=b._emscripten_bind_btDynamicsWorld_getDebugDrawer_0=b.asm.Ca).apply(null,arguments)},xc= +b._emscripten_bind_btDynamicsWorld_debugDrawWorld_0=function(){return(xc=b._emscripten_bind_btDynamicsWorld_debugDrawWorld_0=b.asm.Da).apply(null,arguments)},yc=b._emscripten_bind_btDynamicsWorld_debugDrawObject_3=function(){return(yc=b._emscripten_bind_btDynamicsWorld_debugDrawObject_3=b.asm.Ea).apply(null,arguments)},zc=b._emscripten_bind_btDynamicsWorld___destroy___0=function(){return(zc=b._emscripten_bind_btDynamicsWorld___destroy___0=b.asm.Fa).apply(null,arguments)},Ac=b._emscripten_bind_btTypedConstraint_enableFeedback_1= +function(){return(Ac=b._emscripten_bind_btTypedConstraint_enableFeedback_1=b.asm.Ga).apply(null,arguments)},Bc=b._emscripten_bind_btTypedConstraint_getBreakingImpulseThreshold_0=function(){return(Bc=b._emscripten_bind_btTypedConstraint_getBreakingImpulseThreshold_0=b.asm.Ha).apply(null,arguments)},Cc=b._emscripten_bind_btTypedConstraint_setBreakingImpulseThreshold_1=function(){return(Cc=b._emscripten_bind_btTypedConstraint_setBreakingImpulseThreshold_1=b.asm.Ia).apply(null,arguments)},Dc=b._emscripten_bind_btTypedConstraint_getParam_2= +function(){return(Dc=b._emscripten_bind_btTypedConstraint_getParam_2=b.asm.Ja).apply(null,arguments)},Ec=b._emscripten_bind_btTypedConstraint_setParam_3=function(){return(Ec=b._emscripten_bind_btTypedConstraint_setParam_3=b.asm.Ka).apply(null,arguments)},Fc=b._emscripten_bind_btTypedConstraint___destroy___0=function(){return(Fc=b._emscripten_bind_btTypedConstraint___destroy___0=b.asm.La).apply(null,arguments)},Gc=b._emscripten_bind_btConcaveShape_setLocalScaling_1=function(){return(Gc=b._emscripten_bind_btConcaveShape_setLocalScaling_1= +b.asm.Ma).apply(null,arguments)},Hc=b._emscripten_bind_btConcaveShape_getLocalScaling_0=function(){return(Hc=b._emscripten_bind_btConcaveShape_getLocalScaling_0=b.asm.Na).apply(null,arguments)},Ic=b._emscripten_bind_btConcaveShape_calculateLocalInertia_2=function(){return(Ic=b._emscripten_bind_btConcaveShape_calculateLocalInertia_2=b.asm.Oa).apply(null,arguments)},Jc=b._emscripten_bind_btConcaveShape___destroy___0=function(){return(Jc=b._emscripten_bind_btConcaveShape___destroy___0=b.asm.Pa).apply(null, +arguments)},Kc=b._emscripten_bind_btCapsuleShape_btCapsuleShape_2=function(){return(Kc=b._emscripten_bind_btCapsuleShape_btCapsuleShape_2=b.asm.Qa).apply(null,arguments)},Lc=b._emscripten_bind_btCapsuleShape_setMargin_1=function(){return(Lc=b._emscripten_bind_btCapsuleShape_setMargin_1=b.asm.Ra).apply(null,arguments)},Mc=b._emscripten_bind_btCapsuleShape_getMargin_0=function(){return(Mc=b._emscripten_bind_btCapsuleShape_getMargin_0=b.asm.Sa).apply(null,arguments)},Nc=b._emscripten_bind_btCapsuleShape_getUpAxis_0= +function(){return(Nc=b._emscripten_bind_btCapsuleShape_getUpAxis_0=b.asm.Ta).apply(null,arguments)},Oc=b._emscripten_bind_btCapsuleShape_getRadius_0=function(){return(Oc=b._emscripten_bind_btCapsuleShape_getRadius_0=b.asm.Ua).apply(null,arguments)},Pc=b._emscripten_bind_btCapsuleShape_getHalfHeight_0=function(){return(Pc=b._emscripten_bind_btCapsuleShape_getHalfHeight_0=b.asm.Va).apply(null,arguments)},Qc=b._emscripten_bind_btCapsuleShape_setLocalScaling_1=function(){return(Qc=b._emscripten_bind_btCapsuleShape_setLocalScaling_1= +b.asm.Wa).apply(null,arguments)},Rc=b._emscripten_bind_btCapsuleShape_getLocalScaling_0=function(){return(Rc=b._emscripten_bind_btCapsuleShape_getLocalScaling_0=b.asm.Xa).apply(null,arguments)},Sc=b._emscripten_bind_btCapsuleShape_calculateLocalInertia_2=function(){return(Sc=b._emscripten_bind_btCapsuleShape_calculateLocalInertia_2=b.asm.Ya).apply(null,arguments)},Tc=b._emscripten_bind_btCapsuleShape___destroy___0=function(){return(Tc=b._emscripten_bind_btCapsuleShape___destroy___0=b.asm.Za).apply(null, +arguments)},Uc=b._emscripten_bind_btIDebugDraw_drawLine_3=function(){return(Uc=b._emscripten_bind_btIDebugDraw_drawLine_3=b.asm._a).apply(null,arguments)},Vc=b._emscripten_bind_btIDebugDraw_drawContactPoint_5=function(){return(Vc=b._emscripten_bind_btIDebugDraw_drawContactPoint_5=b.asm.$a).apply(null,arguments)},Wc=b._emscripten_bind_btIDebugDraw_reportErrorWarning_1=function(){return(Wc=b._emscripten_bind_btIDebugDraw_reportErrorWarning_1=b.asm.ab).apply(null,arguments)},Xc=b._emscripten_bind_btIDebugDraw_draw3dText_2= +function(){return(Xc=b._emscripten_bind_btIDebugDraw_draw3dText_2=b.asm.bb).apply(null,arguments)},Yc=b._emscripten_bind_btIDebugDraw_setDebugMode_1=function(){return(Yc=b._emscripten_bind_btIDebugDraw_setDebugMode_1=b.asm.cb).apply(null,arguments)},Zc=b._emscripten_bind_btIDebugDraw_getDebugMode_0=function(){return(Zc=b._emscripten_bind_btIDebugDraw_getDebugMode_0=b.asm.db).apply(null,arguments)},$c=b._emscripten_bind_btIDebugDraw___destroy___0=function(){return($c=b._emscripten_bind_btIDebugDraw___destroy___0= +b.asm.eb).apply(null,arguments)},ad=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_0=function(){return(ad=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_0=b.asm.fb).apply(null,arguments)},bd=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_1=function(){return(bd=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_1=b.asm.gb).apply(null,arguments)},cd=b._emscripten_bind_btDefaultCollisionConfiguration___destroy___0= +function(){return(cd=b._emscripten_bind_btDefaultCollisionConfiguration___destroy___0=b.asm.hb).apply(null,arguments)},dd=b._emscripten_bind_btTriangleMeshShape_setLocalScaling_1=function(){return(dd=b._emscripten_bind_btTriangleMeshShape_setLocalScaling_1=b.asm.ib).apply(null,arguments)},ed=b._emscripten_bind_btTriangleMeshShape_getLocalScaling_0=function(){return(ed=b._emscripten_bind_btTriangleMeshShape_getLocalScaling_0=b.asm.jb).apply(null,arguments)},fd=b._emscripten_bind_btTriangleMeshShape_calculateLocalInertia_2= +function(){return(fd=b._emscripten_bind_btTriangleMeshShape_calculateLocalInertia_2=b.asm.kb).apply(null,arguments)},gd=b._emscripten_bind_btTriangleMeshShape___destroy___0=function(){return(gd=b._emscripten_bind_btTriangleMeshShape___destroy___0=b.asm.lb).apply(null,arguments)},hd=b._emscripten_bind_btGhostObject_btGhostObject_0=function(){return(hd=b._emscripten_bind_btGhostObject_btGhostObject_0=b.asm.mb).apply(null,arguments)},id=b._emscripten_bind_btGhostObject_getNumOverlappingObjects_0=function(){return(id= +b._emscripten_bind_btGhostObject_getNumOverlappingObjects_0=b.asm.nb).apply(null,arguments)},jd=b._emscripten_bind_btGhostObject_getOverlappingObject_1=function(){return(jd=b._emscripten_bind_btGhostObject_getOverlappingObject_1=b.asm.ob).apply(null,arguments)},kd=b._emscripten_bind_btGhostObject_setAnisotropicFriction_2=function(){return(kd=b._emscripten_bind_btGhostObject_setAnisotropicFriction_2=b.asm.pb).apply(null,arguments)},ld=b._emscripten_bind_btGhostObject_getCollisionShape_0=function(){return(ld= +b._emscripten_bind_btGhostObject_getCollisionShape_0=b.asm.qb).apply(null,arguments)},md=b._emscripten_bind_btGhostObject_setContactProcessingThreshold_1=function(){return(md=b._emscripten_bind_btGhostObject_setContactProcessingThreshold_1=b.asm.rb).apply(null,arguments)},nd=b._emscripten_bind_btGhostObject_setActivationState_1=function(){return(nd=b._emscripten_bind_btGhostObject_setActivationState_1=b.asm.sb).apply(null,arguments)},od=b._emscripten_bind_btGhostObject_forceActivationState_1=function(){return(od= +b._emscripten_bind_btGhostObject_forceActivationState_1=b.asm.tb).apply(null,arguments)},pd=b._emscripten_bind_btGhostObject_activate_0=function(){return(pd=b._emscripten_bind_btGhostObject_activate_0=b.asm.ub).apply(null,arguments)},qd=b._emscripten_bind_btGhostObject_activate_1=function(){return(qd=b._emscripten_bind_btGhostObject_activate_1=b.asm.vb).apply(null,arguments)},rd=b._emscripten_bind_btGhostObject_isActive_0=function(){return(rd=b._emscripten_bind_btGhostObject_isActive_0=b.asm.wb).apply(null, +arguments)},sd=b._emscripten_bind_btGhostObject_isKinematicObject_0=function(){return(sd=b._emscripten_bind_btGhostObject_isKinematicObject_0=b.asm.xb).apply(null,arguments)},td=b._emscripten_bind_btGhostObject_isStaticObject_0=function(){return(td=b._emscripten_bind_btGhostObject_isStaticObject_0=b.asm.yb).apply(null,arguments)},ud=b._emscripten_bind_btGhostObject_isStaticOrKinematicObject_0=function(){return(ud=b._emscripten_bind_btGhostObject_isStaticOrKinematicObject_0=b.asm.zb).apply(null,arguments)}, +vd=b._emscripten_bind_btGhostObject_getRestitution_0=function(){return(vd=b._emscripten_bind_btGhostObject_getRestitution_0=b.asm.Ab).apply(null,arguments)},wd=b._emscripten_bind_btGhostObject_getFriction_0=function(){return(wd=b._emscripten_bind_btGhostObject_getFriction_0=b.asm.Bb).apply(null,arguments)},xd=b._emscripten_bind_btGhostObject_getRollingFriction_0=function(){return(xd=b._emscripten_bind_btGhostObject_getRollingFriction_0=b.asm.Cb).apply(null,arguments)},yd=b._emscripten_bind_btGhostObject_setRestitution_1= +function(){return(yd=b._emscripten_bind_btGhostObject_setRestitution_1=b.asm.Db).apply(null,arguments)},zd=b._emscripten_bind_btGhostObject_setFriction_1=function(){return(zd=b._emscripten_bind_btGhostObject_setFriction_1=b.asm.Eb).apply(null,arguments)},Ad=b._emscripten_bind_btGhostObject_setRollingFriction_1=function(){return(Ad=b._emscripten_bind_btGhostObject_setRollingFriction_1=b.asm.Fb).apply(null,arguments)},Bd=b._emscripten_bind_btGhostObject_getWorldTransform_0=function(){return(Bd=b._emscripten_bind_btGhostObject_getWorldTransform_0= +b.asm.Gb).apply(null,arguments)},Cd=b._emscripten_bind_btGhostObject_getCollisionFlags_0=function(){return(Cd=b._emscripten_bind_btGhostObject_getCollisionFlags_0=b.asm.Hb).apply(null,arguments)},Dd=b._emscripten_bind_btGhostObject_setCollisionFlags_1=function(){return(Dd=b._emscripten_bind_btGhostObject_setCollisionFlags_1=b.asm.Ib).apply(null,arguments)},Ed=b._emscripten_bind_btGhostObject_setWorldTransform_1=function(){return(Ed=b._emscripten_bind_btGhostObject_setWorldTransform_1=b.asm.Jb).apply(null, +arguments)},Fd=b._emscripten_bind_btGhostObject_setCollisionShape_1=function(){return(Fd=b._emscripten_bind_btGhostObject_setCollisionShape_1=b.asm.Kb).apply(null,arguments)},Gd=b._emscripten_bind_btGhostObject_setCcdMotionThreshold_1=function(){return(Gd=b._emscripten_bind_btGhostObject_setCcdMotionThreshold_1=b.asm.Lb).apply(null,arguments)},Hd=b._emscripten_bind_btGhostObject_setCcdSweptSphereRadius_1=function(){return(Hd=b._emscripten_bind_btGhostObject_setCcdSweptSphereRadius_1=b.asm.Mb).apply(null, +arguments)},Id=b._emscripten_bind_btGhostObject_getUserIndex_0=function(){return(Id=b._emscripten_bind_btGhostObject_getUserIndex_0=b.asm.Nb).apply(null,arguments)},Jd=b._emscripten_bind_btGhostObject_setUserIndex_1=function(){return(Jd=b._emscripten_bind_btGhostObject_setUserIndex_1=b.asm.Ob).apply(null,arguments)},Kd=b._emscripten_bind_btGhostObject_getUserPointer_0=function(){return(Kd=b._emscripten_bind_btGhostObject_getUserPointer_0=b.asm.Pb).apply(null,arguments)},Ld=b._emscripten_bind_btGhostObject_setUserPointer_1= +function(){return(Ld=b._emscripten_bind_btGhostObject_setUserPointer_1=b.asm.Qb).apply(null,arguments)},Md=b._emscripten_bind_btGhostObject_getBroadphaseHandle_0=function(){return(Md=b._emscripten_bind_btGhostObject_getBroadphaseHandle_0=b.asm.Rb).apply(null,arguments)},Nd=b._emscripten_bind_btGhostObject___destroy___0=function(){return(Nd=b._emscripten_bind_btGhostObject___destroy___0=b.asm.Sb).apply(null,arguments)},Od=b._emscripten_bind_btConeShape_btConeShape_2=function(){return(Od=b._emscripten_bind_btConeShape_btConeShape_2= +b.asm.Tb).apply(null,arguments)},Pd=b._emscripten_bind_btConeShape_setLocalScaling_1=function(){return(Pd=b._emscripten_bind_btConeShape_setLocalScaling_1=b.asm.Ub).apply(null,arguments)},Qd=b._emscripten_bind_btConeShape_getLocalScaling_0=function(){return(Qd=b._emscripten_bind_btConeShape_getLocalScaling_0=b.asm.Vb).apply(null,arguments)},Rd=b._emscripten_bind_btConeShape_calculateLocalInertia_2=function(){return(Rd=b._emscripten_bind_btConeShape_calculateLocalInertia_2=b.asm.Wb).apply(null,arguments)}, +Sd=b._emscripten_bind_btConeShape___destroy___0=function(){return(Sd=b._emscripten_bind_btConeShape___destroy___0=b.asm.Xb).apply(null,arguments)},Td=b._emscripten_bind_btActionInterface_updateAction_2=function(){return(Td=b._emscripten_bind_btActionInterface_updateAction_2=b.asm.Yb).apply(null,arguments)},Ud=b._emscripten_bind_btActionInterface___destroy___0=function(){return(Ud=b._emscripten_bind_btActionInterface___destroy___0=b.asm.Zb).apply(null,arguments)},Vd=b._emscripten_bind_btVector3_btVector3_0= +function(){return(Vd=b._emscripten_bind_btVector3_btVector3_0=b.asm._b).apply(null,arguments)},Wd=b._emscripten_bind_btVector3_btVector3_3=function(){return(Wd=b._emscripten_bind_btVector3_btVector3_3=b.asm.$b).apply(null,arguments)},Xd=b._emscripten_bind_btVector3_length_0=function(){return(Xd=b._emscripten_bind_btVector3_length_0=b.asm.ac).apply(null,arguments)},Yd=b._emscripten_bind_btVector3_x_0=function(){return(Yd=b._emscripten_bind_btVector3_x_0=b.asm.bc).apply(null,arguments)},Zd=b._emscripten_bind_btVector3_y_0= +function(){return(Zd=b._emscripten_bind_btVector3_y_0=b.asm.cc).apply(null,arguments)},$d=b._emscripten_bind_btVector3_z_0=function(){return($d=b._emscripten_bind_btVector3_z_0=b.asm.dc).apply(null,arguments)},ae=b._emscripten_bind_btVector3_setX_1=function(){return(ae=b._emscripten_bind_btVector3_setX_1=b.asm.ec).apply(null,arguments)},be=b._emscripten_bind_btVector3_setY_1=function(){return(be=b._emscripten_bind_btVector3_setY_1=b.asm.fc).apply(null,arguments)},ce=b._emscripten_bind_btVector3_setZ_1= +function(){return(ce=b._emscripten_bind_btVector3_setZ_1=b.asm.gc).apply(null,arguments)},de=b._emscripten_bind_btVector3_setValue_3=function(){return(de=b._emscripten_bind_btVector3_setValue_3=b.asm.hc).apply(null,arguments)},ee=b._emscripten_bind_btVector3_normalize_0=function(){return(ee=b._emscripten_bind_btVector3_normalize_0=b.asm.ic).apply(null,arguments)},fe=b._emscripten_bind_btVector3_rotate_2=function(){return(fe=b._emscripten_bind_btVector3_rotate_2=b.asm.jc).apply(null,arguments)},ge= +b._emscripten_bind_btVector3_dot_1=function(){return(ge=b._emscripten_bind_btVector3_dot_1=b.asm.kc).apply(null,arguments)},he=b._emscripten_bind_btVector3_op_mul_1=function(){return(he=b._emscripten_bind_btVector3_op_mul_1=b.asm.lc).apply(null,arguments)},ie=b._emscripten_bind_btVector3_op_add_1=function(){return(ie=b._emscripten_bind_btVector3_op_add_1=b.asm.mc).apply(null,arguments)},je=b._emscripten_bind_btVector3_op_sub_1=function(){return(je=b._emscripten_bind_btVector3_op_sub_1=b.asm.nc).apply(null, +arguments)},ke=b._emscripten_bind_btVector3___destroy___0=function(){return(ke=b._emscripten_bind_btVector3___destroy___0=b.asm.oc).apply(null,arguments)},le=b._emscripten_bind_btVehicleRaycaster_castRay_3=function(){return(le=b._emscripten_bind_btVehicleRaycaster_castRay_3=b.asm.pc).apply(null,arguments)},me=b._emscripten_bind_btVehicleRaycaster___destroy___0=function(){return(me=b._emscripten_bind_btVehicleRaycaster___destroy___0=b.asm.qc).apply(null,arguments)},ne=b._emscripten_bind_btQuadWord_x_0= +function(){return(ne=b._emscripten_bind_btQuadWord_x_0=b.asm.rc).apply(null,arguments)},oe=b._emscripten_bind_btQuadWord_y_0=function(){return(oe=b._emscripten_bind_btQuadWord_y_0=b.asm.sc).apply(null,arguments)},pe=b._emscripten_bind_btQuadWord_z_0=function(){return(pe=b._emscripten_bind_btQuadWord_z_0=b.asm.tc).apply(null,arguments)},qe=b._emscripten_bind_btQuadWord_w_0=function(){return(qe=b._emscripten_bind_btQuadWord_w_0=b.asm.uc).apply(null,arguments)},re=b._emscripten_bind_btQuadWord_setX_1= +function(){return(re=b._emscripten_bind_btQuadWord_setX_1=b.asm.vc).apply(null,arguments)},se=b._emscripten_bind_btQuadWord_setY_1=function(){return(se=b._emscripten_bind_btQuadWord_setY_1=b.asm.wc).apply(null,arguments)},te=b._emscripten_bind_btQuadWord_setZ_1=function(){return(te=b._emscripten_bind_btQuadWord_setZ_1=b.asm.xc).apply(null,arguments)},ue=b._emscripten_bind_btQuadWord_setW_1=function(){return(ue=b._emscripten_bind_btQuadWord_setW_1=b.asm.yc).apply(null,arguments)},ve=b._emscripten_bind_btQuadWord___destroy___0= +function(){return(ve=b._emscripten_bind_btQuadWord___destroy___0=b.asm.zc).apply(null,arguments)},we=b._emscripten_bind_btCylinderShape_btCylinderShape_1=function(){return(we=b._emscripten_bind_btCylinderShape_btCylinderShape_1=b.asm.Ac).apply(null,arguments)},xe=b._emscripten_bind_btCylinderShape_setMargin_1=function(){return(xe=b._emscripten_bind_btCylinderShape_setMargin_1=b.asm.Bc).apply(null,arguments)},ye=b._emscripten_bind_btCylinderShape_getMargin_0=function(){return(ye=b._emscripten_bind_btCylinderShape_getMargin_0= +b.asm.Cc).apply(null,arguments)},ze=b._emscripten_bind_btCylinderShape_setLocalScaling_1=function(){return(ze=b._emscripten_bind_btCylinderShape_setLocalScaling_1=b.asm.Dc).apply(null,arguments)},Ae=b._emscripten_bind_btCylinderShape_getLocalScaling_0=function(){return(Ae=b._emscripten_bind_btCylinderShape_getLocalScaling_0=b.asm.Ec).apply(null,arguments)},Be=b._emscripten_bind_btCylinderShape_calculateLocalInertia_2=function(){return(Be=b._emscripten_bind_btCylinderShape_calculateLocalInertia_2= +b.asm.Fc).apply(null,arguments)},Ce=b._emscripten_bind_btCylinderShape___destroy___0=function(){return(Ce=b._emscripten_bind_btCylinderShape___destroy___0=b.asm.Gc).apply(null,arguments)},De=b._emscripten_bind_btDiscreteDynamicsWorld_btDiscreteDynamicsWorld_4=function(){return(De=b._emscripten_bind_btDiscreteDynamicsWorld_btDiscreteDynamicsWorld_4=b.asm.Hc).apply(null,arguments)},Ee=b._emscripten_bind_btDiscreteDynamicsWorld_setGravity_1=function(){return(Ee=b._emscripten_bind_btDiscreteDynamicsWorld_setGravity_1= +b.asm.Ic).apply(null,arguments)},Fe=b._emscripten_bind_btDiscreteDynamicsWorld_getGravity_0=function(){return(Fe=b._emscripten_bind_btDiscreteDynamicsWorld_getGravity_0=b.asm.Jc).apply(null,arguments)},Ge=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_1=function(){return(Ge=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_1=b.asm.Kc).apply(null,arguments)},He=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_3=function(){return(He=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_3= +b.asm.Lc).apply(null,arguments)},Ie=b._emscripten_bind_btDiscreteDynamicsWorld_removeRigidBody_1=function(){return(Ie=b._emscripten_bind_btDiscreteDynamicsWorld_removeRigidBody_1=b.asm.Mc).apply(null,arguments)},Je=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_1=function(){return(Je=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_1=b.asm.Nc).apply(null,arguments)},Ke=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_2=function(){return(Ke=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_2= +b.asm.Oc).apply(null,arguments)},Le=b._emscripten_bind_btDiscreteDynamicsWorld_removeConstraint_1=function(){return(Le=b._emscripten_bind_btDiscreteDynamicsWorld_removeConstraint_1=b.asm.Pc).apply(null,arguments)},Me=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_1=function(){return(Me=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_1=b.asm.Qc).apply(null,arguments)},Ne=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_2=function(){return(Ne=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_2= +b.asm.Rc).apply(null,arguments)},Oe=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_3=function(){return(Oe=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_3=b.asm.Sc).apply(null,arguments)},Pe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactAddedCallback_1=function(){return(Pe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactAddedCallback_1=b.asm.Tc).apply(null,arguments)},Qe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactProcessedCallback_1=function(){return(Qe= +b._emscripten_bind_btDiscreteDynamicsWorld_setContactProcessedCallback_1=b.asm.Uc).apply(null,arguments)},Re=b._emscripten_bind_btDiscreteDynamicsWorld_setContactDestroyedCallback_1=function(){return(Re=b._emscripten_bind_btDiscreteDynamicsWorld_setContactDestroyedCallback_1=b.asm.Vc).apply(null,arguments)},Se=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatcher_0=function(){return(Se=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatcher_0=b.asm.Wc).apply(null,arguments)},Te=b._emscripten_bind_btDiscreteDynamicsWorld_rayTest_3= +function(){return(Te=b._emscripten_bind_btDiscreteDynamicsWorld_rayTest_3=b.asm.Xc).apply(null,arguments)},Ue=b._emscripten_bind_btDiscreteDynamicsWorld_getPairCache_0=function(){return(Ue=b._emscripten_bind_btDiscreteDynamicsWorld_getPairCache_0=b.asm.Yc).apply(null,arguments)},Ve=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatchInfo_0=function(){return(Ve=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatchInfo_0=b.asm.Zc).apply(null,arguments)},We=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_1= +function(){return(We=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_1=b.asm._c).apply(null,arguments)},Xe=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_2=function(){return(Xe=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_2=b.asm.$c).apply(null,arguments)},Ye=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_3=function(){return(Ye=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_3=b.asm.ad).apply(null,arguments)},Ze=b._emscripten_bind_btDiscreteDynamicsWorld_removeCollisionObject_1= +function(){return(Ze=b._emscripten_bind_btDiscreteDynamicsWorld_removeCollisionObject_1=b.asm.bd).apply(null,arguments)},$e=b._emscripten_bind_btDiscreteDynamicsWorld_getBroadphase_0=function(){return($e=b._emscripten_bind_btDiscreteDynamicsWorld_getBroadphase_0=b.asm.cd).apply(null,arguments)},af=b._emscripten_bind_btDiscreteDynamicsWorld_convexSweepTest_5=function(){return(af=b._emscripten_bind_btDiscreteDynamicsWorld_convexSweepTest_5=b.asm.dd).apply(null,arguments)},bf=b._emscripten_bind_btDiscreteDynamicsWorld_contactPairTest_3= +function(){return(bf=b._emscripten_bind_btDiscreteDynamicsWorld_contactPairTest_3=b.asm.ed).apply(null,arguments)},cf=b._emscripten_bind_btDiscreteDynamicsWorld_contactTest_2=function(){return(cf=b._emscripten_bind_btDiscreteDynamicsWorld_contactTest_2=b.asm.fd).apply(null,arguments)},df=b._emscripten_bind_btDiscreteDynamicsWorld_updateSingleAabb_1=function(){return(df=b._emscripten_bind_btDiscreteDynamicsWorld_updateSingleAabb_1=b.asm.gd).apply(null,arguments)},ef=b._emscripten_bind_btDiscreteDynamicsWorld_setDebugDrawer_1= +function(){return(ef=b._emscripten_bind_btDiscreteDynamicsWorld_setDebugDrawer_1=b.asm.hd).apply(null,arguments)},ff=b._emscripten_bind_btDiscreteDynamicsWorld_getDebugDrawer_0=function(){return(ff=b._emscripten_bind_btDiscreteDynamicsWorld_getDebugDrawer_0=b.asm.id).apply(null,arguments)},gf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawWorld_0=function(){return(gf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawWorld_0=b.asm.jd).apply(null,arguments)},hf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawObject_3= +function(){return(hf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawObject_3=b.asm.kd).apply(null,arguments)},jf=b._emscripten_bind_btDiscreteDynamicsWorld_addAction_1=function(){return(jf=b._emscripten_bind_btDiscreteDynamicsWorld_addAction_1=b.asm.ld).apply(null,arguments)},kf=b._emscripten_bind_btDiscreteDynamicsWorld_removeAction_1=function(){return(kf=b._emscripten_bind_btDiscreteDynamicsWorld_removeAction_1=b.asm.md).apply(null,arguments)},lf=b._emscripten_bind_btDiscreteDynamicsWorld_getSolverInfo_0= +function(){return(lf=b._emscripten_bind_btDiscreteDynamicsWorld_getSolverInfo_0=b.asm.nd).apply(null,arguments)},mf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_1=function(){return(mf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_1=b.asm.od).apply(null,arguments)},nf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_2=function(){return(nf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_2=b.asm.pd).apply(null,arguments)}, +of=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_3=function(){return(of=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_3=b.asm.qd).apply(null,arguments)},pf=b._emscripten_bind_btDiscreteDynamicsWorld___destroy___0=function(){return(pf=b._emscripten_bind_btDiscreteDynamicsWorld___destroy___0=b.asm.rd).apply(null,arguments)},qf=b._emscripten_bind_btConvexShape_setLocalScaling_1=function(){return(qf=b._emscripten_bind_btConvexShape_setLocalScaling_1=b.asm.sd).apply(null, +arguments)},rf=b._emscripten_bind_btConvexShape_getLocalScaling_0=function(){return(rf=b._emscripten_bind_btConvexShape_getLocalScaling_0=b.asm.td).apply(null,arguments)},sf=b._emscripten_bind_btConvexShape_calculateLocalInertia_2=function(){return(sf=b._emscripten_bind_btConvexShape_calculateLocalInertia_2=b.asm.ud).apply(null,arguments)},tf=b._emscripten_bind_btConvexShape_setMargin_1=function(){return(tf=b._emscripten_bind_btConvexShape_setMargin_1=b.asm.vd).apply(null,arguments)},uf=b._emscripten_bind_btConvexShape_getMargin_0= +function(){return(uf=b._emscripten_bind_btConvexShape_getMargin_0=b.asm.wd).apply(null,arguments)},vf=b._emscripten_bind_btConvexShape___destroy___0=function(){return(vf=b._emscripten_bind_btConvexShape___destroy___0=b.asm.xd).apply(null,arguments)},wf=b._emscripten_bind_btDispatcher_getNumManifolds_0=function(){return(wf=b._emscripten_bind_btDispatcher_getNumManifolds_0=b.asm.yd).apply(null,arguments)},xf=b._emscripten_bind_btDispatcher_getManifoldByIndexInternal_1=function(){return(xf=b._emscripten_bind_btDispatcher_getManifoldByIndexInternal_1= +b.asm.zd).apply(null,arguments)},yf=b._emscripten_bind_btDispatcher___destroy___0=function(){return(yf=b._emscripten_bind_btDispatcher___destroy___0=b.asm.Ad).apply(null,arguments)},zf=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_3=function(){return(zf=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_3=b.asm.Bd).apply(null,arguments)},Af=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_5=function(){return(Af=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_5= +b.asm.Cd).apply(null,arguments)},Bf=b._emscripten_bind_btGeneric6DofConstraint_setLinearLowerLimit_1=function(){return(Bf=b._emscripten_bind_btGeneric6DofConstraint_setLinearLowerLimit_1=b.asm.Dd).apply(null,arguments)},Cf=b._emscripten_bind_btGeneric6DofConstraint_setLinearUpperLimit_1=function(){return(Cf=b._emscripten_bind_btGeneric6DofConstraint_setLinearUpperLimit_1=b.asm.Ed).apply(null,arguments)},Df=b._emscripten_bind_btGeneric6DofConstraint_setAngularLowerLimit_1=function(){return(Df=b._emscripten_bind_btGeneric6DofConstraint_setAngularLowerLimit_1= +b.asm.Fd).apply(null,arguments)},Ef=b._emscripten_bind_btGeneric6DofConstraint_setAngularUpperLimit_1=function(){return(Ef=b._emscripten_bind_btGeneric6DofConstraint_setAngularUpperLimit_1=b.asm.Gd).apply(null,arguments)},Ff=b._emscripten_bind_btGeneric6DofConstraint_getFrameOffsetA_0=function(){return(Ff=b._emscripten_bind_btGeneric6DofConstraint_getFrameOffsetA_0=b.asm.Hd).apply(null,arguments)},Gf=b._emscripten_bind_btGeneric6DofConstraint_enableFeedback_1=function(){return(Gf=b._emscripten_bind_btGeneric6DofConstraint_enableFeedback_1= +b.asm.Id).apply(null,arguments)},Hf=b._emscripten_bind_btGeneric6DofConstraint_getBreakingImpulseThreshold_0=function(){return(Hf=b._emscripten_bind_btGeneric6DofConstraint_getBreakingImpulseThreshold_0=b.asm.Jd).apply(null,arguments)},If=b._emscripten_bind_btGeneric6DofConstraint_setBreakingImpulseThreshold_1=function(){return(If=b._emscripten_bind_btGeneric6DofConstraint_setBreakingImpulseThreshold_1=b.asm.Kd).apply(null,arguments)},Jf=b._emscripten_bind_btGeneric6DofConstraint_getParam_2=function(){return(Jf= +b._emscripten_bind_btGeneric6DofConstraint_getParam_2=b.asm.Ld).apply(null,arguments)},Kf=b._emscripten_bind_btGeneric6DofConstraint_setParam_3=function(){return(Kf=b._emscripten_bind_btGeneric6DofConstraint_setParam_3=b.asm.Md).apply(null,arguments)},Lf=b._emscripten_bind_btGeneric6DofConstraint___destroy___0=function(){return(Lf=b._emscripten_bind_btGeneric6DofConstraint___destroy___0=b.asm.Nd).apply(null,arguments)},Mf=b._emscripten_bind_btStridingMeshInterface_setScaling_1=function(){return(Mf= +b._emscripten_bind_btStridingMeshInterface_setScaling_1=b.asm.Od).apply(null,arguments)},Nf=b._emscripten_bind_btStridingMeshInterface___destroy___0=function(){return(Nf=b._emscripten_bind_btStridingMeshInterface___destroy___0=b.asm.Pd).apply(null,arguments)},Of=b._emscripten_bind_btMotionState_getWorldTransform_1=function(){return(Of=b._emscripten_bind_btMotionState_getWorldTransform_1=b.asm.Qd).apply(null,arguments)},Pf=b._emscripten_bind_btMotionState_setWorldTransform_1=function(){return(Pf=b._emscripten_bind_btMotionState_setWorldTransform_1= +b.asm.Rd).apply(null,arguments)},Qf=b._emscripten_bind_btMotionState___destroy___0=function(){return(Qf=b._emscripten_bind_btMotionState___destroy___0=b.asm.Sd).apply(null,arguments)},Rf=b._emscripten_bind_ConvexResultCallback_hasHit_0=function(){return(Rf=b._emscripten_bind_ConvexResultCallback_hasHit_0=b.asm.Td).apply(null,arguments)},Sf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterGroup_0=function(){return(Sf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterGroup_0= +b.asm.Ud).apply(null,arguments)},Tf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterGroup_1=function(){return(Tf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterGroup_1=b.asm.Vd).apply(null,arguments)},Uf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterMask_0=function(){return(Uf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterMask_0=b.asm.Wd).apply(null,arguments)},Vf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterMask_1=function(){return(Vf= +b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterMask_1=b.asm.Xd).apply(null,arguments)},Wf=b._emscripten_bind_ConvexResultCallback_get_m_closestHitFraction_0=function(){return(Wf=b._emscripten_bind_ConvexResultCallback_get_m_closestHitFraction_0=b.asm.Yd).apply(null,arguments)},Xf=b._emscripten_bind_ConvexResultCallback_set_m_closestHitFraction_1=function(){return(Xf=b._emscripten_bind_ConvexResultCallback_set_m_closestHitFraction_1=b.asm.Zd).apply(null,arguments)},Yf=b._emscripten_bind_ConvexResultCallback___destroy___0= +function(){return(Yf=b._emscripten_bind_ConvexResultCallback___destroy___0=b.asm._d).apply(null,arguments)},Zf=b._emscripten_bind_ContactResultCallback_addSingleResult_7=function(){return(Zf=b._emscripten_bind_ContactResultCallback_addSingleResult_7=b.asm.$d).apply(null,arguments)},$f=b._emscripten_bind_ContactResultCallback___destroy___0=function(){return($f=b._emscripten_bind_ContactResultCallback___destroy___0=b.asm.ae).apply(null,arguments)},ag=b._emscripten_bind_btSoftBodySolver___destroy___0= +function(){return(ag=b._emscripten_bind_btSoftBodySolver___destroy___0=b.asm.be).apply(null,arguments)},bg=b._emscripten_bind_RayResultCallback_hasHit_0=function(){return(bg=b._emscripten_bind_RayResultCallback_hasHit_0=b.asm.ce).apply(null,arguments)},cg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterGroup_0=function(){return(cg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterGroup_0=b.asm.de).apply(null,arguments)},dg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterGroup_1= +function(){return(dg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterGroup_1=b.asm.ee).apply(null,arguments)},eg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterMask_0=function(){return(eg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterMask_0=b.asm.fe).apply(null,arguments)},fg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterMask_1=function(){return(fg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterMask_1=b.asm.ge).apply(null,arguments)},gg=b._emscripten_bind_RayResultCallback_get_m_closestHitFraction_0= +function(){return(gg=b._emscripten_bind_RayResultCallback_get_m_closestHitFraction_0=b.asm.he).apply(null,arguments)},hg=b._emscripten_bind_RayResultCallback_set_m_closestHitFraction_1=function(){return(hg=b._emscripten_bind_RayResultCallback_set_m_closestHitFraction_1=b.asm.ie).apply(null,arguments)},ig=b._emscripten_bind_RayResultCallback_get_m_collisionObject_0=function(){return(ig=b._emscripten_bind_RayResultCallback_get_m_collisionObject_0=b.asm.je).apply(null,arguments)},jg=b._emscripten_bind_RayResultCallback_set_m_collisionObject_1= +function(){return(jg=b._emscripten_bind_RayResultCallback_set_m_collisionObject_1=b.asm.ke).apply(null,arguments)},kg=b._emscripten_bind_RayResultCallback___destroy___0=function(){return(kg=b._emscripten_bind_RayResultCallback___destroy___0=b.asm.le).apply(null,arguments)},lg=b._emscripten_bind_btMatrix3x3_setEulerZYX_3=function(){return(lg=b._emscripten_bind_btMatrix3x3_setEulerZYX_3=b.asm.me).apply(null,arguments)},mg=b._emscripten_bind_btMatrix3x3_getRotation_1=function(){return(mg=b._emscripten_bind_btMatrix3x3_getRotation_1= +b.asm.ne).apply(null,arguments)},ng=b._emscripten_bind_btMatrix3x3_getRow_1=function(){return(ng=b._emscripten_bind_btMatrix3x3_getRow_1=b.asm.oe).apply(null,arguments)},og=b._emscripten_bind_btMatrix3x3___destroy___0=function(){return(og=b._emscripten_bind_btMatrix3x3___destroy___0=b.asm.pe).apply(null,arguments)},pg=b._emscripten_bind_btScalarArray_size_0=function(){return(pg=b._emscripten_bind_btScalarArray_size_0=b.asm.qe).apply(null,arguments)},qg=b._emscripten_bind_btScalarArray_at_1=function(){return(qg= +b._emscripten_bind_btScalarArray_at_1=b.asm.re).apply(null,arguments)},rg=b._emscripten_bind_btScalarArray___destroy___0=function(){return(rg=b._emscripten_bind_btScalarArray___destroy___0=b.asm.se).apply(null,arguments)},sg=b._emscripten_bind_Material_get_m_kLST_0=function(){return(sg=b._emscripten_bind_Material_get_m_kLST_0=b.asm.te).apply(null,arguments)},tg=b._emscripten_bind_Material_set_m_kLST_1=function(){return(tg=b._emscripten_bind_Material_set_m_kLST_1=b.asm.ue).apply(null,arguments)},ug= +b._emscripten_bind_Material_get_m_kAST_0=function(){return(ug=b._emscripten_bind_Material_get_m_kAST_0=b.asm.ve).apply(null,arguments)},vg=b._emscripten_bind_Material_set_m_kAST_1=function(){return(vg=b._emscripten_bind_Material_set_m_kAST_1=b.asm.we).apply(null,arguments)},wg=b._emscripten_bind_Material_get_m_kVST_0=function(){return(wg=b._emscripten_bind_Material_get_m_kVST_0=b.asm.xe).apply(null,arguments)},xg=b._emscripten_bind_Material_set_m_kVST_1=function(){return(xg=b._emscripten_bind_Material_set_m_kVST_1= +b.asm.ye).apply(null,arguments)},yg=b._emscripten_bind_Material_get_m_flags_0=function(){return(yg=b._emscripten_bind_Material_get_m_flags_0=b.asm.ze).apply(null,arguments)},zg=b._emscripten_bind_Material_set_m_flags_1=function(){return(zg=b._emscripten_bind_Material_set_m_flags_1=b.asm.Ae).apply(null,arguments)},Ag=b._emscripten_bind_Material___destroy___0=function(){return(Ag=b._emscripten_bind_Material___destroy___0=b.asm.Be).apply(null,arguments)},Bg=b._emscripten_bind_btDispatcherInfo_get_m_timeStep_0= +function(){return(Bg=b._emscripten_bind_btDispatcherInfo_get_m_timeStep_0=b.asm.Ce).apply(null,arguments)},Cg=b._emscripten_bind_btDispatcherInfo_set_m_timeStep_1=function(){return(Cg=b._emscripten_bind_btDispatcherInfo_set_m_timeStep_1=b.asm.De).apply(null,arguments)},Dg=b._emscripten_bind_btDispatcherInfo_get_m_stepCount_0=function(){return(Dg=b._emscripten_bind_btDispatcherInfo_get_m_stepCount_0=b.asm.Ee).apply(null,arguments)},Eg=b._emscripten_bind_btDispatcherInfo_set_m_stepCount_1=function(){return(Eg= +b._emscripten_bind_btDispatcherInfo_set_m_stepCount_1=b.asm.Fe).apply(null,arguments)},Fg=b._emscripten_bind_btDispatcherInfo_get_m_dispatchFunc_0=function(){return(Fg=b._emscripten_bind_btDispatcherInfo_get_m_dispatchFunc_0=b.asm.Ge).apply(null,arguments)},Gg=b._emscripten_bind_btDispatcherInfo_set_m_dispatchFunc_1=function(){return(Gg=b._emscripten_bind_btDispatcherInfo_set_m_dispatchFunc_1=b.asm.He).apply(null,arguments)},Hg=b._emscripten_bind_btDispatcherInfo_get_m_timeOfImpact_0=function(){return(Hg= +b._emscripten_bind_btDispatcherInfo_get_m_timeOfImpact_0=b.asm.Ie).apply(null,arguments)},Ig=b._emscripten_bind_btDispatcherInfo_set_m_timeOfImpact_1=function(){return(Ig=b._emscripten_bind_btDispatcherInfo_set_m_timeOfImpact_1=b.asm.Je).apply(null,arguments)},Jg=b._emscripten_bind_btDispatcherInfo_get_m_useContinuous_0=function(){return(Jg=b._emscripten_bind_btDispatcherInfo_get_m_useContinuous_0=b.asm.Ke).apply(null,arguments)},Kg=b._emscripten_bind_btDispatcherInfo_set_m_useContinuous_1=function(){return(Kg= +b._emscripten_bind_btDispatcherInfo_set_m_useContinuous_1=b.asm.Le).apply(null,arguments)},Lg=b._emscripten_bind_btDispatcherInfo_get_m_enableSatConvex_0=function(){return(Lg=b._emscripten_bind_btDispatcherInfo_get_m_enableSatConvex_0=b.asm.Me).apply(null,arguments)},Mg=b._emscripten_bind_btDispatcherInfo_set_m_enableSatConvex_1=function(){return(Mg=b._emscripten_bind_btDispatcherInfo_set_m_enableSatConvex_1=b.asm.Ne).apply(null,arguments)},Ng=b._emscripten_bind_btDispatcherInfo_get_m_enableSPU_0= +function(){return(Ng=b._emscripten_bind_btDispatcherInfo_get_m_enableSPU_0=b.asm.Oe).apply(null,arguments)},Og=b._emscripten_bind_btDispatcherInfo_set_m_enableSPU_1=function(){return(Og=b._emscripten_bind_btDispatcherInfo_set_m_enableSPU_1=b.asm.Pe).apply(null,arguments)},Pg=b._emscripten_bind_btDispatcherInfo_get_m_useEpa_0=function(){return(Pg=b._emscripten_bind_btDispatcherInfo_get_m_useEpa_0=b.asm.Qe).apply(null,arguments)},Qg=b._emscripten_bind_btDispatcherInfo_set_m_useEpa_1=function(){return(Qg= +b._emscripten_bind_btDispatcherInfo_set_m_useEpa_1=b.asm.Re).apply(null,arguments)},Rg=b._emscripten_bind_btDispatcherInfo_get_m_allowedCcdPenetration_0=function(){return(Rg=b._emscripten_bind_btDispatcherInfo_get_m_allowedCcdPenetration_0=b.asm.Se).apply(null,arguments)},Sg=b._emscripten_bind_btDispatcherInfo_set_m_allowedCcdPenetration_1=function(){return(Sg=b._emscripten_bind_btDispatcherInfo_set_m_allowedCcdPenetration_1=b.asm.Te).apply(null,arguments)},Tg=b._emscripten_bind_btDispatcherInfo_get_m_useConvexConservativeDistanceUtil_0= +function(){return(Tg=b._emscripten_bind_btDispatcherInfo_get_m_useConvexConservativeDistanceUtil_0=b.asm.Ue).apply(null,arguments)},Ug=b._emscripten_bind_btDispatcherInfo_set_m_useConvexConservativeDistanceUtil_1=function(){return(Ug=b._emscripten_bind_btDispatcherInfo_set_m_useConvexConservativeDistanceUtil_1=b.asm.Ve).apply(null,arguments)},Vg=b._emscripten_bind_btDispatcherInfo_get_m_convexConservativeDistanceThreshold_0=function(){return(Vg=b._emscripten_bind_btDispatcherInfo_get_m_convexConservativeDistanceThreshold_0= +b.asm.We).apply(null,arguments)},Wg=b._emscripten_bind_btDispatcherInfo_set_m_convexConservativeDistanceThreshold_1=function(){return(Wg=b._emscripten_bind_btDispatcherInfo_set_m_convexConservativeDistanceThreshold_1=b.asm.Xe).apply(null,arguments)},Xg=b._emscripten_bind_btDispatcherInfo___destroy___0=function(){return(Xg=b._emscripten_bind_btDispatcherInfo___destroy___0=b.asm.Ye).apply(null,arguments)},Yg=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_chassisConnectionCS_0=function(){return(Yg= +b._emscripten_bind_btWheelInfoConstructionInfo_get_m_chassisConnectionCS_0=b.asm.Ze).apply(null,arguments)},Zg=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_chassisConnectionCS_1=function(){return(Zg=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_chassisConnectionCS_1=b.asm._e).apply(null,arguments)},$g=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelDirectionCS_0=function(){return($g=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelDirectionCS_0=b.asm.$e).apply(null, +arguments)},ah=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelDirectionCS_1=function(){return(ah=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelDirectionCS_1=b.asm.af).apply(null,arguments)},bh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelAxleCS_0=function(){return(bh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelAxleCS_0=b.asm.bf).apply(null,arguments)},ch=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelAxleCS_1=function(){return(ch=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelAxleCS_1= +b.asm.cf).apply(null,arguments)},dh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionRestLength_0=function(){return(dh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionRestLength_0=b.asm.df).apply(null,arguments)},eh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionRestLength_1=function(){return(eh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionRestLength_1=b.asm.ef).apply(null,arguments)},fh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionTravelCm_0= +function(){return(fh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionTravelCm_0=b.asm.ff).apply(null,arguments)},gh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionTravelCm_1=function(){return(gh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionTravelCm_1=b.asm.gf).apply(null,arguments)},hh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelRadius_0=function(){return(hh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelRadius_0=b.asm.hf).apply(null, +arguments)},ih=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelRadius_1=function(){return(ih=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelRadius_1=b.asm.jf).apply(null,arguments)},jh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionStiffness_0=function(){return(jh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionStiffness_0=b.asm.kf).apply(null,arguments)},kh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionStiffness_1=function(){return(kh= +b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionStiffness_1=b.asm.lf).apply(null,arguments)},lh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingCompression_0=function(){return(lh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingCompression_0=b.asm.mf).apply(null,arguments)},mh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingCompression_1=function(){return(mh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingCompression_1= +b.asm.nf).apply(null,arguments)},nh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingRelaxation_0=function(){return(nh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingRelaxation_0=b.asm.of).apply(null,arguments)},oh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingRelaxation_1=function(){return(oh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingRelaxation_1=b.asm.pf).apply(null,arguments)},ph=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_frictionSlip_0= +function(){return(ph=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_frictionSlip_0=b.asm.qf).apply(null,arguments)},qh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_frictionSlip_1=function(){return(qh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_frictionSlip_1=b.asm.rf).apply(null,arguments)},rh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionForce_0=function(){return(rh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionForce_0=b.asm.sf).apply(null, +arguments)},sh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionForce_1=function(){return(sh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionForce_1=b.asm.tf).apply(null,arguments)},th=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_bIsFrontWheel_0=function(){return(th=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_bIsFrontWheel_0=b.asm.uf).apply(null,arguments)},uh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_bIsFrontWheel_1=function(){return(uh= +b._emscripten_bind_btWheelInfoConstructionInfo_set_m_bIsFrontWheel_1=b.asm.vf).apply(null,arguments)},vh=b._emscripten_bind_btWheelInfoConstructionInfo___destroy___0=function(){return(vh=b._emscripten_bind_btWheelInfoConstructionInfo___destroy___0=b.asm.wf).apply(null,arguments)},wh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_1=function(){return(wh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_1=b.asm.xf).apply(null,arguments)},xh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_2= +function(){return(xh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_2=b.asm.yf).apply(null,arguments)},yh=b._emscripten_bind_btConvexTriangleMeshShape_setLocalScaling_1=function(){return(yh=b._emscripten_bind_btConvexTriangleMeshShape_setLocalScaling_1=b.asm.zf).apply(null,arguments)},zh=b._emscripten_bind_btConvexTriangleMeshShape_getLocalScaling_0=function(){return(zh=b._emscripten_bind_btConvexTriangleMeshShape_getLocalScaling_0=b.asm.Af).apply(null,arguments)},Ah=b._emscripten_bind_btConvexTriangleMeshShape_calculateLocalInertia_2= +function(){return(Ah=b._emscripten_bind_btConvexTriangleMeshShape_calculateLocalInertia_2=b.asm.Bf).apply(null,arguments)},Bh=b._emscripten_bind_btConvexTriangleMeshShape_setMargin_1=function(){return(Bh=b._emscripten_bind_btConvexTriangleMeshShape_setMargin_1=b.asm.Cf).apply(null,arguments)},Ch=b._emscripten_bind_btConvexTriangleMeshShape_getMargin_0=function(){return(Ch=b._emscripten_bind_btConvexTriangleMeshShape_getMargin_0=b.asm.Df).apply(null,arguments)},Dh=b._emscripten_bind_btConvexTriangleMeshShape___destroy___0= +function(){return(Dh=b._emscripten_bind_btConvexTriangleMeshShape___destroy___0=b.asm.Ef).apply(null,arguments)},Eh=b._emscripten_bind_btBroadphaseInterface_getOverlappingPairCache_0=function(){return(Eh=b._emscripten_bind_btBroadphaseInterface_getOverlappingPairCache_0=b.asm.Ff).apply(null,arguments)},Fh=b._emscripten_bind_btBroadphaseInterface___destroy___0=function(){return(Fh=b._emscripten_bind_btBroadphaseInterface___destroy___0=b.asm.Gf).apply(null,arguments)},Gh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_3= +function(){return(Gh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_3=b.asm.Hf).apply(null,arguments)},Hh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_4=function(){return(Hh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_4=b.asm.If).apply(null,arguments)},Ih=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearDamping_0=function(){return(Ih=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearDamping_0= +b.asm.Jf).apply(null,arguments)},Jh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearDamping_1=function(){return(Jh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearDamping_1=b.asm.Kf).apply(null,arguments)},Kh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularDamping_0=function(){return(Kh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularDamping_0=b.asm.Lf).apply(null,arguments)},Lh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularDamping_1=function(){return(Lh= +b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularDamping_1=b.asm.Mf).apply(null,arguments)},Mh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_friction_0=function(){return(Mh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_friction_0=b.asm.Nf).apply(null,arguments)},Nh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_friction_1=function(){return(Nh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_friction_1=b.asm.Of).apply(null,arguments)},Oh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_rollingFriction_0= +function(){return(Oh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_rollingFriction_0=b.asm.Pf).apply(null,arguments)},Ph=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_rollingFriction_1=function(){return(Ph=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_rollingFriction_1=b.asm.Qf).apply(null,arguments)},Qh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_restitution_0=function(){return(Qh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_restitution_0=b.asm.Rf).apply(null, +arguments)},Rh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_restitution_1=function(){return(Rh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_restitution_1=b.asm.Sf).apply(null,arguments)},Sh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearSleepingThreshold_0=function(){return(Sh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearSleepingThreshold_0=b.asm.Tf).apply(null,arguments)},Th=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearSleepingThreshold_1=function(){return(Th= +b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearSleepingThreshold_1=b.asm.Uf).apply(null,arguments)},Uh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularSleepingThreshold_0=function(){return(Uh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularSleepingThreshold_0=b.asm.Vf).apply(null,arguments)},Vh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularSleepingThreshold_1=function(){return(Vh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularSleepingThreshold_1= +b.asm.Wf).apply(null,arguments)},Wh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDamping_0=function(){return(Wh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDamping_0=b.asm.Xf).apply(null,arguments)},Xh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDamping_1=function(){return(Xh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDamping_1=b.asm.Yf).apply(null,arguments)},Yh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDampingFactor_0= +function(){return(Yh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDampingFactor_0=b.asm.Zf).apply(null,arguments)},Zh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDampingFactor_1=function(){return(Zh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDampingFactor_1=b.asm._f).apply(null,arguments)},$h=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalLinearDampingThresholdSqr_0=function(){return($h=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalLinearDampingThresholdSqr_0= +b.asm.$f).apply(null,arguments)},ai=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalLinearDampingThresholdSqr_1=function(){return(ai=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalLinearDampingThresholdSqr_1=b.asm.ag).apply(null,arguments)},bi=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingThresholdSqr_0=function(){return(bi=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingThresholdSqr_0=b.asm.bg).apply(null, +arguments)},ci=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingThresholdSqr_1=function(){return(ci=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingThresholdSqr_1=b.asm.cg).apply(null,arguments)},di=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingFactor_0=function(){return(di=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingFactor_0=b.asm.dg).apply(null,arguments)},ei=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingFactor_1= +function(){return(ei=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingFactor_1=b.asm.eg).apply(null,arguments)},fi=b._emscripten_bind_btRigidBodyConstructionInfo___destroy___0=function(){return(fi=b._emscripten_bind_btRigidBodyConstructionInfo___destroy___0=b.asm.fg).apply(null,arguments)},gi=b._emscripten_bind_btCollisionConfiguration___destroy___0=function(){return(gi=b._emscripten_bind_btCollisionConfiguration___destroy___0=b.asm.gg).apply(null,arguments)},hi=b._emscripten_bind_btPersistentManifold_btPersistentManifold_0= +function(){return(hi=b._emscripten_bind_btPersistentManifold_btPersistentManifold_0=b.asm.hg).apply(null,arguments)},ii=b._emscripten_bind_btPersistentManifold_getBody0_0=function(){return(ii=b._emscripten_bind_btPersistentManifold_getBody0_0=b.asm.ig).apply(null,arguments)},ji=b._emscripten_bind_btPersistentManifold_getBody1_0=function(){return(ji=b._emscripten_bind_btPersistentManifold_getBody1_0=b.asm.jg).apply(null,arguments)},ki=b._emscripten_bind_btPersistentManifold_getNumContacts_0=function(){return(ki= +b._emscripten_bind_btPersistentManifold_getNumContacts_0=b.asm.kg).apply(null,arguments)},li=b._emscripten_bind_btPersistentManifold_getContactPoint_1=function(){return(li=b._emscripten_bind_btPersistentManifold_getContactPoint_1=b.asm.lg).apply(null,arguments)},mi=b._emscripten_bind_btPersistentManifold___destroy___0=function(){return(mi=b._emscripten_bind_btPersistentManifold___destroy___0=b.asm.mg).apply(null,arguments)},ni=b._emscripten_bind_btCompoundShape_btCompoundShape_0=function(){return(ni= +b._emscripten_bind_btCompoundShape_btCompoundShape_0=b.asm.ng).apply(null,arguments)},oi=b._emscripten_bind_btCompoundShape_btCompoundShape_1=function(){return(oi=b._emscripten_bind_btCompoundShape_btCompoundShape_1=b.asm.og).apply(null,arguments)},pi=b._emscripten_bind_btCompoundShape_addChildShape_2=function(){return(pi=b._emscripten_bind_btCompoundShape_addChildShape_2=b.asm.pg).apply(null,arguments)},qi=b._emscripten_bind_btCompoundShape_removeChildShape_1=function(){return(qi=b._emscripten_bind_btCompoundShape_removeChildShape_1= +b.asm.qg).apply(null,arguments)},ri=b._emscripten_bind_btCompoundShape_removeChildShapeByIndex_1=function(){return(ri=b._emscripten_bind_btCompoundShape_removeChildShapeByIndex_1=b.asm.rg).apply(null,arguments)},si=b._emscripten_bind_btCompoundShape_getNumChildShapes_0=function(){return(si=b._emscripten_bind_btCompoundShape_getNumChildShapes_0=b.asm.sg).apply(null,arguments)},ti=b._emscripten_bind_btCompoundShape_getChildShape_1=function(){return(ti=b._emscripten_bind_btCompoundShape_getChildShape_1= +b.asm.tg).apply(null,arguments)},ui=b._emscripten_bind_btCompoundShape_updateChildTransform_2=function(){return(ui=b._emscripten_bind_btCompoundShape_updateChildTransform_2=b.asm.ug).apply(null,arguments)},vi=b._emscripten_bind_btCompoundShape_updateChildTransform_3=function(){return(vi=b._emscripten_bind_btCompoundShape_updateChildTransform_3=b.asm.vg).apply(null,arguments)},wi=b._emscripten_bind_btCompoundShape_setMargin_1=function(){return(wi=b._emscripten_bind_btCompoundShape_setMargin_1=b.asm.wg).apply(null, +arguments)},xi=b._emscripten_bind_btCompoundShape_getMargin_0=function(){return(xi=b._emscripten_bind_btCompoundShape_getMargin_0=b.asm.xg).apply(null,arguments)},yi=b._emscripten_bind_btCompoundShape_setLocalScaling_1=function(){return(yi=b._emscripten_bind_btCompoundShape_setLocalScaling_1=b.asm.yg).apply(null,arguments)},zi=b._emscripten_bind_btCompoundShape_getLocalScaling_0=function(){return(zi=b._emscripten_bind_btCompoundShape_getLocalScaling_0=b.asm.zg).apply(null,arguments)},Ai=b._emscripten_bind_btCompoundShape_calculateLocalInertia_2= +function(){return(Ai=b._emscripten_bind_btCompoundShape_calculateLocalInertia_2=b.asm.Ag).apply(null,arguments)},Bi=b._emscripten_bind_btCompoundShape___destroy___0=function(){return(Bi=b._emscripten_bind_btCompoundShape___destroy___0=b.asm.Bg).apply(null,arguments)},Ci=b._emscripten_bind_ClosestConvexResultCallback_ClosestConvexResultCallback_2=function(){return(Ci=b._emscripten_bind_ClosestConvexResultCallback_ClosestConvexResultCallback_2=b.asm.Cg).apply(null,arguments)},Di=b._emscripten_bind_ClosestConvexResultCallback_hasHit_0= +function(){return(Di=b._emscripten_bind_ClosestConvexResultCallback_hasHit_0=b.asm.Dg).apply(null,arguments)},Ei=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexFromWorld_0=function(){return(Ei=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexFromWorld_0=b.asm.Eg).apply(null,arguments)},Fi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexFromWorld_1=function(){return(Fi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexFromWorld_1=b.asm.Fg).apply(null,arguments)}, +Gi=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexToWorld_0=function(){return(Gi=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexToWorld_0=b.asm.Gg).apply(null,arguments)},Hi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexToWorld_1=function(){return(Hi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexToWorld_1=b.asm.Hg).apply(null,arguments)},Ii=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitNormalWorld_0=function(){return(Ii=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitNormalWorld_0= +b.asm.Ig).apply(null,arguments)},Ji=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitNormalWorld_1=function(){return(Ji=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitNormalWorld_1=b.asm.Jg).apply(null,arguments)},Ki=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitPointWorld_0=function(){return(Ki=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitPointWorld_0=b.asm.Kg).apply(null,arguments)},Li=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitPointWorld_1=function(){return(Li= +b._emscripten_bind_ClosestConvexResultCallback_set_m_hitPointWorld_1=b.asm.Lg).apply(null,arguments)},Mi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterGroup_0=function(){return(Mi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterGroup_0=b.asm.Mg).apply(null,arguments)},Ni=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterGroup_1=function(){return(Ni=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterGroup_1=b.asm.Ng).apply(null, +arguments)},Oi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterMask_0=function(){return(Oi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterMask_0=b.asm.Og).apply(null,arguments)},Pi=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterMask_1=function(){return(Pi=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterMask_1=b.asm.Pg).apply(null,arguments)},Qi=b._emscripten_bind_ClosestConvexResultCallback_get_m_closestHitFraction_0= +function(){return(Qi=b._emscripten_bind_ClosestConvexResultCallback_get_m_closestHitFraction_0=b.asm.Qg).apply(null,arguments)},Ri=b._emscripten_bind_ClosestConvexResultCallback_set_m_closestHitFraction_1=function(){return(Ri=b._emscripten_bind_ClosestConvexResultCallback_set_m_closestHitFraction_1=b.asm.Rg).apply(null,arguments)},Si=b._emscripten_bind_ClosestConvexResultCallback___destroy___0=function(){return(Si=b._emscripten_bind_ClosestConvexResultCallback___destroy___0=b.asm.Sg).apply(null,arguments)}, +Ti=b._emscripten_bind_AllHitsRayResultCallback_AllHitsRayResultCallback_2=function(){return(Ti=b._emscripten_bind_AllHitsRayResultCallback_AllHitsRayResultCallback_2=b.asm.Tg).apply(null,arguments)},Ui=b._emscripten_bind_AllHitsRayResultCallback_hasHit_0=function(){return(Ui=b._emscripten_bind_AllHitsRayResultCallback_hasHit_0=b.asm.Ug).apply(null,arguments)},Vi=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObjects_0=function(){return(Vi=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObjects_0= +b.asm.Vg).apply(null,arguments)},Wi=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObjects_1=function(){return(Wi=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObjects_1=b.asm.Wg).apply(null,arguments)},Xi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayFromWorld_0=function(){return(Xi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayFromWorld_0=b.asm.Xg).apply(null,arguments)},Yi=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayFromWorld_1=function(){return(Yi= +b._emscripten_bind_AllHitsRayResultCallback_set_m_rayFromWorld_1=b.asm.Yg).apply(null,arguments)},Zi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayToWorld_0=function(){return(Zi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayToWorld_0=b.asm.Zg).apply(null,arguments)},$i=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayToWorld_1=function(){return($i=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayToWorld_1=b.asm._g).apply(null,arguments)},aj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitNormalWorld_0= +function(){return(aj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitNormalWorld_0=b.asm.$g).apply(null,arguments)},bj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitNormalWorld_1=function(){return(bj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitNormalWorld_1=b.asm.ah).apply(null,arguments)},cj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitPointWorld_0=function(){return(cj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitPointWorld_0=b.asm.bh).apply(null,arguments)}, +dj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitPointWorld_1=function(){return(dj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitPointWorld_1=b.asm.ch).apply(null,arguments)},ej=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitFractions_0=function(){return(ej=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitFractions_0=b.asm.dh).apply(null,arguments)},fj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitFractions_1=function(){return(fj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitFractions_1= +b.asm.eh).apply(null,arguments)},gj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterGroup_0=function(){return(gj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterGroup_0=b.asm.fh).apply(null,arguments)},hj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterGroup_1=function(){return(hj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterGroup_1=b.asm.gh).apply(null,arguments)},ij=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterMask_0= +function(){return(ij=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterMask_0=b.asm.hh).apply(null,arguments)},jj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterMask_1=function(){return(jj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterMask_1=b.asm.ih).apply(null,arguments)},kj=b._emscripten_bind_AllHitsRayResultCallback_get_m_closestHitFraction_0=function(){return(kj=b._emscripten_bind_AllHitsRayResultCallback_get_m_closestHitFraction_0=b.asm.jh).apply(null, +arguments)},lj=b._emscripten_bind_AllHitsRayResultCallback_set_m_closestHitFraction_1=function(){return(lj=b._emscripten_bind_AllHitsRayResultCallback_set_m_closestHitFraction_1=b.asm.kh).apply(null,arguments)},mj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObject_0=function(){return(mj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObject_0=b.asm.lh).apply(null,arguments)},nj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObject_1=function(){return(nj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObject_1= +b.asm.mh).apply(null,arguments)},oj=b._emscripten_bind_AllHitsRayResultCallback___destroy___0=function(){return(oj=b._emscripten_bind_AllHitsRayResultCallback___destroy___0=b.asm.nh).apply(null,arguments)},pj=b._emscripten_bind_tMaterialArray_size_0=function(){return(pj=b._emscripten_bind_tMaterialArray_size_0=b.asm.oh).apply(null,arguments)},qj=b._emscripten_bind_tMaterialArray_at_1=function(){return(qj=b._emscripten_bind_tMaterialArray_at_1=b.asm.ph).apply(null,arguments)},rj=b._emscripten_bind_tMaterialArray___destroy___0= +function(){return(rj=b._emscripten_bind_tMaterialArray___destroy___0=b.asm.qh).apply(null,arguments)},sj=b._emscripten_bind_btDefaultVehicleRaycaster_btDefaultVehicleRaycaster_1=function(){return(sj=b._emscripten_bind_btDefaultVehicleRaycaster_btDefaultVehicleRaycaster_1=b.asm.rh).apply(null,arguments)},tj=b._emscripten_bind_btDefaultVehicleRaycaster_castRay_3=function(){return(tj=b._emscripten_bind_btDefaultVehicleRaycaster_castRay_3=b.asm.sh).apply(null,arguments)},uj=b._emscripten_bind_btDefaultVehicleRaycaster___destroy___0= +function(){return(uj=b._emscripten_bind_btDefaultVehicleRaycaster___destroy___0=b.asm.th).apply(null,arguments)},vj=b._emscripten_bind_btEmptyShape_btEmptyShape_0=function(){return(vj=b._emscripten_bind_btEmptyShape_btEmptyShape_0=b.asm.uh).apply(null,arguments)},wj=b._emscripten_bind_btEmptyShape_setLocalScaling_1=function(){return(wj=b._emscripten_bind_btEmptyShape_setLocalScaling_1=b.asm.vh).apply(null,arguments)},xj=b._emscripten_bind_btEmptyShape_getLocalScaling_0=function(){return(xj=b._emscripten_bind_btEmptyShape_getLocalScaling_0= +b.asm.wh).apply(null,arguments)},yj=b._emscripten_bind_btEmptyShape_calculateLocalInertia_2=function(){return(yj=b._emscripten_bind_btEmptyShape_calculateLocalInertia_2=b.asm.xh).apply(null,arguments)},zj=b._emscripten_bind_btEmptyShape___destroy___0=function(){return(zj=b._emscripten_bind_btEmptyShape___destroy___0=b.asm.yh).apply(null,arguments)},Aj=b._emscripten_bind_btConstraintSetting_btConstraintSetting_0=function(){return(Aj=b._emscripten_bind_btConstraintSetting_btConstraintSetting_0=b.asm.zh).apply(null, +arguments)},Bj=b._emscripten_bind_btConstraintSetting_get_m_tau_0=function(){return(Bj=b._emscripten_bind_btConstraintSetting_get_m_tau_0=b.asm.Ah).apply(null,arguments)},Cj=b._emscripten_bind_btConstraintSetting_set_m_tau_1=function(){return(Cj=b._emscripten_bind_btConstraintSetting_set_m_tau_1=b.asm.Bh).apply(null,arguments)},Dj=b._emscripten_bind_btConstraintSetting_get_m_damping_0=function(){return(Dj=b._emscripten_bind_btConstraintSetting_get_m_damping_0=b.asm.Ch).apply(null,arguments)},Ej=b._emscripten_bind_btConstraintSetting_set_m_damping_1= +function(){return(Ej=b._emscripten_bind_btConstraintSetting_set_m_damping_1=b.asm.Dh).apply(null,arguments)},Fj=b._emscripten_bind_btConstraintSetting_get_m_impulseClamp_0=function(){return(Fj=b._emscripten_bind_btConstraintSetting_get_m_impulseClamp_0=b.asm.Eh).apply(null,arguments)},Gj=b._emscripten_bind_btConstraintSetting_set_m_impulseClamp_1=function(){return(Gj=b._emscripten_bind_btConstraintSetting_set_m_impulseClamp_1=b.asm.Fh).apply(null,arguments)},Hj=b._emscripten_bind_btConstraintSetting___destroy___0= +function(){return(Hj=b._emscripten_bind_btConstraintSetting___destroy___0=b.asm.Gh).apply(null,arguments)},Ij=b._emscripten_bind_LocalShapeInfo_get_m_shapePart_0=function(){return(Ij=b._emscripten_bind_LocalShapeInfo_get_m_shapePart_0=b.asm.Hh).apply(null,arguments)},Jj=b._emscripten_bind_LocalShapeInfo_set_m_shapePart_1=function(){return(Jj=b._emscripten_bind_LocalShapeInfo_set_m_shapePart_1=b.asm.Ih).apply(null,arguments)},Kj=b._emscripten_bind_LocalShapeInfo_get_m_triangleIndex_0=function(){return(Kj= +b._emscripten_bind_LocalShapeInfo_get_m_triangleIndex_0=b.asm.Jh).apply(null,arguments)},Lj=b._emscripten_bind_LocalShapeInfo_set_m_triangleIndex_1=function(){return(Lj=b._emscripten_bind_LocalShapeInfo_set_m_triangleIndex_1=b.asm.Kh).apply(null,arguments)},Mj=b._emscripten_bind_LocalShapeInfo___destroy___0=function(){return(Mj=b._emscripten_bind_LocalShapeInfo___destroy___0=b.asm.Lh).apply(null,arguments)},Nj=b._emscripten_bind_btRigidBody_btRigidBody_1=function(){return(Nj=b._emscripten_bind_btRigidBody_btRigidBody_1= +b.asm.Mh).apply(null,arguments)},Oj=b._emscripten_bind_btRigidBody_getCenterOfMassTransform_0=function(){return(Oj=b._emscripten_bind_btRigidBody_getCenterOfMassTransform_0=b.asm.Nh).apply(null,arguments)},Pj=b._emscripten_bind_btRigidBody_setCenterOfMassTransform_1=function(){return(Pj=b._emscripten_bind_btRigidBody_setCenterOfMassTransform_1=b.asm.Oh).apply(null,arguments)},Qj=b._emscripten_bind_btRigidBody_setSleepingThresholds_2=function(){return(Qj=b._emscripten_bind_btRigidBody_setSleepingThresholds_2= +b.asm.Ph).apply(null,arguments)},Rj=b._emscripten_bind_btRigidBody_getLinearDamping_0=function(){return(Rj=b._emscripten_bind_btRigidBody_getLinearDamping_0=b.asm.Qh).apply(null,arguments)},Sj=b._emscripten_bind_btRigidBody_getAngularDamping_0=function(){return(Sj=b._emscripten_bind_btRigidBody_getAngularDamping_0=b.asm.Rh).apply(null,arguments)},Tj=b._emscripten_bind_btRigidBody_setDamping_2=function(){return(Tj=b._emscripten_bind_btRigidBody_setDamping_2=b.asm.Sh).apply(null,arguments)},Uj=b._emscripten_bind_btRigidBody_setMassProps_2= +function(){return(Uj=b._emscripten_bind_btRigidBody_setMassProps_2=b.asm.Th).apply(null,arguments)},Vj=b._emscripten_bind_btRigidBody_getLinearFactor_0=function(){return(Vj=b._emscripten_bind_btRigidBody_getLinearFactor_0=b.asm.Uh).apply(null,arguments)},Wj=b._emscripten_bind_btRigidBody_setLinearFactor_1=function(){return(Wj=b._emscripten_bind_btRigidBody_setLinearFactor_1=b.asm.Vh).apply(null,arguments)},Xj=b._emscripten_bind_btRigidBody_applyTorque_1=function(){return(Xj=b._emscripten_bind_btRigidBody_applyTorque_1= +b.asm.Wh).apply(null,arguments)},Yj=b._emscripten_bind_btRigidBody_applyLocalTorque_1=function(){return(Yj=b._emscripten_bind_btRigidBody_applyLocalTorque_1=b.asm.Xh).apply(null,arguments)},Zj=b._emscripten_bind_btRigidBody_applyForce_2=function(){return(Zj=b._emscripten_bind_btRigidBody_applyForce_2=b.asm.Yh).apply(null,arguments)},ak=b._emscripten_bind_btRigidBody_applyCentralForce_1=function(){return(ak=b._emscripten_bind_btRigidBody_applyCentralForce_1=b.asm.Zh).apply(null,arguments)},bk=b._emscripten_bind_btRigidBody_applyCentralLocalForce_1= +function(){return(bk=b._emscripten_bind_btRigidBody_applyCentralLocalForce_1=b.asm._h).apply(null,arguments)},ck=b._emscripten_bind_btRigidBody_applyTorqueImpulse_1=function(){return(ck=b._emscripten_bind_btRigidBody_applyTorqueImpulse_1=b.asm.$h).apply(null,arguments)},dk=b._emscripten_bind_btRigidBody_applyImpulse_2=function(){return(dk=b._emscripten_bind_btRigidBody_applyImpulse_2=b.asm.ai).apply(null,arguments)},ek=b._emscripten_bind_btRigidBody_applyCentralImpulse_1=function(){return(ek=b._emscripten_bind_btRigidBody_applyCentralImpulse_1= +b.asm.bi).apply(null,arguments)},fk=b._emscripten_bind_btRigidBody_updateInertiaTensor_0=function(){return(fk=b._emscripten_bind_btRigidBody_updateInertiaTensor_0=b.asm.ci).apply(null,arguments)},gk=b._emscripten_bind_btRigidBody_getLinearVelocity_0=function(){return(gk=b._emscripten_bind_btRigidBody_getLinearVelocity_0=b.asm.di).apply(null,arguments)},hk=b._emscripten_bind_btRigidBody_getAngularVelocity_0=function(){return(hk=b._emscripten_bind_btRigidBody_getAngularVelocity_0=b.asm.ei).apply(null, +arguments)},ik=b._emscripten_bind_btRigidBody_setLinearVelocity_1=function(){return(ik=b._emscripten_bind_btRigidBody_setLinearVelocity_1=b.asm.fi).apply(null,arguments)},jk=b._emscripten_bind_btRigidBody_setAngularVelocity_1=function(){return(jk=b._emscripten_bind_btRigidBody_setAngularVelocity_1=b.asm.gi).apply(null,arguments)},kk=b._emscripten_bind_btRigidBody_getMotionState_0=function(){return(kk=b._emscripten_bind_btRigidBody_getMotionState_0=b.asm.hi).apply(null,arguments)},lk=b._emscripten_bind_btRigidBody_setMotionState_1= +function(){return(lk=b._emscripten_bind_btRigidBody_setMotionState_1=b.asm.ii).apply(null,arguments)},mk=b._emscripten_bind_btRigidBody_getAngularFactor_0=function(){return(mk=b._emscripten_bind_btRigidBody_getAngularFactor_0=b.asm.ji).apply(null,arguments)},nk=b._emscripten_bind_btRigidBody_setAngularFactor_1=function(){return(nk=b._emscripten_bind_btRigidBody_setAngularFactor_1=b.asm.ki).apply(null,arguments)},ok=b._emscripten_bind_btRigidBody_upcast_1=function(){return(ok=b._emscripten_bind_btRigidBody_upcast_1= +b.asm.li).apply(null,arguments)},pk=b._emscripten_bind_btRigidBody_getAabb_2=function(){return(pk=b._emscripten_bind_btRigidBody_getAabb_2=b.asm.mi).apply(null,arguments)},qk=b._emscripten_bind_btRigidBody_applyGravity_0=function(){return(qk=b._emscripten_bind_btRigidBody_applyGravity_0=b.asm.ni).apply(null,arguments)},rk=b._emscripten_bind_btRigidBody_getGravity_0=function(){return(rk=b._emscripten_bind_btRigidBody_getGravity_0=b.asm.oi).apply(null,arguments)},sk=b._emscripten_bind_btRigidBody_setGravity_1= +function(){return(sk=b._emscripten_bind_btRigidBody_setGravity_1=b.asm.pi).apply(null,arguments)},tk=b._emscripten_bind_btRigidBody_getBroadphaseProxy_0=function(){return(tk=b._emscripten_bind_btRigidBody_getBroadphaseProxy_0=b.asm.qi).apply(null,arguments)},uk=b._emscripten_bind_btRigidBody_clearForces_0=function(){return(uk=b._emscripten_bind_btRigidBody_clearForces_0=b.asm.ri).apply(null,arguments)},vk=b._emscripten_bind_btRigidBody_setAnisotropicFriction_2=function(){return(vk=b._emscripten_bind_btRigidBody_setAnisotropicFriction_2= +b.asm.si).apply(null,arguments)},wk=b._emscripten_bind_btRigidBody_getCollisionShape_0=function(){return(wk=b._emscripten_bind_btRigidBody_getCollisionShape_0=b.asm.ti).apply(null,arguments)},xk=b._emscripten_bind_btRigidBody_setContactProcessingThreshold_1=function(){return(xk=b._emscripten_bind_btRigidBody_setContactProcessingThreshold_1=b.asm.ui).apply(null,arguments)},yk=b._emscripten_bind_btRigidBody_setActivationState_1=function(){return(yk=b._emscripten_bind_btRigidBody_setActivationState_1= +b.asm.vi).apply(null,arguments)},zk=b._emscripten_bind_btRigidBody_forceActivationState_1=function(){return(zk=b._emscripten_bind_btRigidBody_forceActivationState_1=b.asm.wi).apply(null,arguments)},Ak=b._emscripten_bind_btRigidBody_activate_0=function(){return(Ak=b._emscripten_bind_btRigidBody_activate_0=b.asm.xi).apply(null,arguments)},Bk=b._emscripten_bind_btRigidBody_activate_1=function(){return(Bk=b._emscripten_bind_btRigidBody_activate_1=b.asm.yi).apply(null,arguments)},Ck=b._emscripten_bind_btRigidBody_isActive_0= +function(){return(Ck=b._emscripten_bind_btRigidBody_isActive_0=b.asm.zi).apply(null,arguments)},Dk=b._emscripten_bind_btRigidBody_isKinematicObject_0=function(){return(Dk=b._emscripten_bind_btRigidBody_isKinematicObject_0=b.asm.Ai).apply(null,arguments)},Ek=b._emscripten_bind_btRigidBody_isStaticObject_0=function(){return(Ek=b._emscripten_bind_btRigidBody_isStaticObject_0=b.asm.Bi).apply(null,arguments)},Fk=b._emscripten_bind_btRigidBody_isStaticOrKinematicObject_0=function(){return(Fk=b._emscripten_bind_btRigidBody_isStaticOrKinematicObject_0= +b.asm.Ci).apply(null,arguments)},Gk=b._emscripten_bind_btRigidBody_getRestitution_0=function(){return(Gk=b._emscripten_bind_btRigidBody_getRestitution_0=b.asm.Di).apply(null,arguments)},Hk=b._emscripten_bind_btRigidBody_getFriction_0=function(){return(Hk=b._emscripten_bind_btRigidBody_getFriction_0=b.asm.Ei).apply(null,arguments)},Ik=b._emscripten_bind_btRigidBody_getRollingFriction_0=function(){return(Ik=b._emscripten_bind_btRigidBody_getRollingFriction_0=b.asm.Fi).apply(null,arguments)},Jk=b._emscripten_bind_btRigidBody_setRestitution_1= +function(){return(Jk=b._emscripten_bind_btRigidBody_setRestitution_1=b.asm.Gi).apply(null,arguments)},Kk=b._emscripten_bind_btRigidBody_setFriction_1=function(){return(Kk=b._emscripten_bind_btRigidBody_setFriction_1=b.asm.Hi).apply(null,arguments)},Lk=b._emscripten_bind_btRigidBody_setRollingFriction_1=function(){return(Lk=b._emscripten_bind_btRigidBody_setRollingFriction_1=b.asm.Ii).apply(null,arguments)},Mk=b._emscripten_bind_btRigidBody_getWorldTransform_0=function(){return(Mk=b._emscripten_bind_btRigidBody_getWorldTransform_0= +b.asm.Ji).apply(null,arguments)},Nk=b._emscripten_bind_btRigidBody_getCollisionFlags_0=function(){return(Nk=b._emscripten_bind_btRigidBody_getCollisionFlags_0=b.asm.Ki).apply(null,arguments)},Ok=b._emscripten_bind_btRigidBody_setCollisionFlags_1=function(){return(Ok=b._emscripten_bind_btRigidBody_setCollisionFlags_1=b.asm.Li).apply(null,arguments)},Pk=b._emscripten_bind_btRigidBody_setWorldTransform_1=function(){return(Pk=b._emscripten_bind_btRigidBody_setWorldTransform_1=b.asm.Mi).apply(null,arguments)}, +Qk=b._emscripten_bind_btRigidBody_setCollisionShape_1=function(){return(Qk=b._emscripten_bind_btRigidBody_setCollisionShape_1=b.asm.Ni).apply(null,arguments)},Rk=b._emscripten_bind_btRigidBody_setCcdMotionThreshold_1=function(){return(Rk=b._emscripten_bind_btRigidBody_setCcdMotionThreshold_1=b.asm.Oi).apply(null,arguments)},Sk=b._emscripten_bind_btRigidBody_setCcdSweptSphereRadius_1=function(){return(Sk=b._emscripten_bind_btRigidBody_setCcdSweptSphereRadius_1=b.asm.Pi).apply(null,arguments)},Tk=b._emscripten_bind_btRigidBody_getUserIndex_0= +function(){return(Tk=b._emscripten_bind_btRigidBody_getUserIndex_0=b.asm.Qi).apply(null,arguments)},Uk=b._emscripten_bind_btRigidBody_setUserIndex_1=function(){return(Uk=b._emscripten_bind_btRigidBody_setUserIndex_1=b.asm.Ri).apply(null,arguments)},Vk=b._emscripten_bind_btRigidBody_getUserPointer_0=function(){return(Vk=b._emscripten_bind_btRigidBody_getUserPointer_0=b.asm.Si).apply(null,arguments)},Wk=b._emscripten_bind_btRigidBody_setUserPointer_1=function(){return(Wk=b._emscripten_bind_btRigidBody_setUserPointer_1= +b.asm.Ti).apply(null,arguments)},Xk=b._emscripten_bind_btRigidBody_getBroadphaseHandle_0=function(){return(Xk=b._emscripten_bind_btRigidBody_getBroadphaseHandle_0=b.asm.Ui).apply(null,arguments)},Yk=b._emscripten_bind_btRigidBody___destroy___0=function(){return(Yk=b._emscripten_bind_btRigidBody___destroy___0=b.asm.Vi).apply(null,arguments)},Zk=b._emscripten_bind_btIndexedMeshArray_size_0=function(){return(Zk=b._emscripten_bind_btIndexedMeshArray_size_0=b.asm.Wi).apply(null,arguments)},$k=b._emscripten_bind_btIndexedMeshArray_at_1= +function(){return($k=b._emscripten_bind_btIndexedMeshArray_at_1=b.asm.Xi).apply(null,arguments)},al=b._emscripten_bind_btIndexedMeshArray___destroy___0=function(){return(al=b._emscripten_bind_btIndexedMeshArray___destroy___0=b.asm.Yi).apply(null,arguments)},bl=b._emscripten_bind_btDbvtBroadphase_btDbvtBroadphase_0=function(){return(bl=b._emscripten_bind_btDbvtBroadphase_btDbvtBroadphase_0=b.asm.Zi).apply(null,arguments)},cl=b._emscripten_bind_btDbvtBroadphase___destroy___0=function(){return(cl=b._emscripten_bind_btDbvtBroadphase___destroy___0= +b.asm._i).apply(null,arguments)},dl=b._emscripten_bind_btHeightfieldTerrainShape_btHeightfieldTerrainShape_9=function(){return(dl=b._emscripten_bind_btHeightfieldTerrainShape_btHeightfieldTerrainShape_9=b.asm.$i).apply(null,arguments)},el=b._emscripten_bind_btHeightfieldTerrainShape_setMargin_1=function(){return(el=b._emscripten_bind_btHeightfieldTerrainShape_setMargin_1=b.asm.aj).apply(null,arguments)},fl=b._emscripten_bind_btHeightfieldTerrainShape_getMargin_0=function(){return(fl=b._emscripten_bind_btHeightfieldTerrainShape_getMargin_0= +b.asm.bj).apply(null,arguments)},gl=b._emscripten_bind_btHeightfieldTerrainShape_setLocalScaling_1=function(){return(gl=b._emscripten_bind_btHeightfieldTerrainShape_setLocalScaling_1=b.asm.cj).apply(null,arguments)},hl=b._emscripten_bind_btHeightfieldTerrainShape_getLocalScaling_0=function(){return(hl=b._emscripten_bind_btHeightfieldTerrainShape_getLocalScaling_0=b.asm.dj).apply(null,arguments)},il=b._emscripten_bind_btHeightfieldTerrainShape_calculateLocalInertia_2=function(){return(il=b._emscripten_bind_btHeightfieldTerrainShape_calculateLocalInertia_2= +b.asm.ej).apply(null,arguments)},jl=b._emscripten_bind_btHeightfieldTerrainShape___destroy___0=function(){return(jl=b._emscripten_bind_btHeightfieldTerrainShape___destroy___0=b.asm.fj).apply(null,arguments)},kl=b._emscripten_bind_btDefaultSoftBodySolver_btDefaultSoftBodySolver_0=function(){return(kl=b._emscripten_bind_btDefaultSoftBodySolver_btDefaultSoftBodySolver_0=b.asm.gj).apply(null,arguments)},ll=b._emscripten_bind_btDefaultSoftBodySolver___destroy___0=function(){return(ll=b._emscripten_bind_btDefaultSoftBodySolver___destroy___0= +b.asm.hj).apply(null,arguments)},ml=b._emscripten_bind_btCollisionDispatcher_btCollisionDispatcher_1=function(){return(ml=b._emscripten_bind_btCollisionDispatcher_btCollisionDispatcher_1=b.asm.ij).apply(null,arguments)},nl=b._emscripten_bind_btCollisionDispatcher_getNumManifolds_0=function(){return(nl=b._emscripten_bind_btCollisionDispatcher_getNumManifolds_0=b.asm.jj).apply(null,arguments)},ol=b._emscripten_bind_btCollisionDispatcher_getManifoldByIndexInternal_1=function(){return(ol=b._emscripten_bind_btCollisionDispatcher_getManifoldByIndexInternal_1= +b.asm.kj).apply(null,arguments)},pl=b._emscripten_bind_btCollisionDispatcher___destroy___0=function(){return(pl=b._emscripten_bind_btCollisionDispatcher___destroy___0=b.asm.lj).apply(null,arguments)},ql=b._emscripten_bind_btAxisSweep3_btAxisSweep3_2=function(){return(ql=b._emscripten_bind_btAxisSweep3_btAxisSweep3_2=b.asm.mj).apply(null,arguments)},rl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_3=function(){return(rl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_3=b.asm.nj).apply(null,arguments)}, +sl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_4=function(){return(sl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_4=b.asm.oj).apply(null,arguments)},tl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_5=function(){return(tl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_5=b.asm.pj).apply(null,arguments)},ul=b._emscripten_bind_btAxisSweep3___destroy___0=function(){return(ul=b._emscripten_bind_btAxisSweep3___destroy___0=b.asm.qj).apply(null,arguments)},vl=b._emscripten_bind_VoidPtr___destroy___0=function(){return(vl= +b._emscripten_bind_VoidPtr___destroy___0=b.asm.rj).apply(null,arguments)},wl=b._emscripten_bind_btSoftBodyWorldInfo_btSoftBodyWorldInfo_0=function(){return(wl=b._emscripten_bind_btSoftBodyWorldInfo_btSoftBodyWorldInfo_0=b.asm.sj).apply(null,arguments)},xl=b._emscripten_bind_btSoftBodyWorldInfo_get_air_density_0=function(){return(xl=b._emscripten_bind_btSoftBodyWorldInfo_get_air_density_0=b.asm.tj).apply(null,arguments)},yl=b._emscripten_bind_btSoftBodyWorldInfo_set_air_density_1=function(){return(yl= +b._emscripten_bind_btSoftBodyWorldInfo_set_air_density_1=b.asm.uj).apply(null,arguments)},zl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_density_0=function(){return(zl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_density_0=b.asm.vj).apply(null,arguments)},Al=b._emscripten_bind_btSoftBodyWorldInfo_set_water_density_1=function(){return(Al=b._emscripten_bind_btSoftBodyWorldInfo_set_water_density_1=b.asm.wj).apply(null,arguments)},Bl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_offset_0= +function(){return(Bl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_offset_0=b.asm.xj).apply(null,arguments)},Cl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_offset_1=function(){return(Cl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_offset_1=b.asm.yj).apply(null,arguments)},Dl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_maxDisplacement_0=function(){return(Dl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_maxDisplacement_0=b.asm.zj).apply(null,arguments)},El=b._emscripten_bind_btSoftBodyWorldInfo_set_m_maxDisplacement_1= +function(){return(El=b._emscripten_bind_btSoftBodyWorldInfo_set_m_maxDisplacement_1=b.asm.Aj).apply(null,arguments)},Fl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_normal_0=function(){return(Fl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_normal_0=b.asm.Bj).apply(null,arguments)},Gl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_normal_1=function(){return(Gl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_normal_1=b.asm.Cj).apply(null,arguments)},Hl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_broadphase_0= +function(){return(Hl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_broadphase_0=b.asm.Dj).apply(null,arguments)},Il=b._emscripten_bind_btSoftBodyWorldInfo_set_m_broadphase_1=function(){return(Il=b._emscripten_bind_btSoftBodyWorldInfo_set_m_broadphase_1=b.asm.Ej).apply(null,arguments)},Jl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_dispatcher_0=function(){return(Jl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_dispatcher_0=b.asm.Fj).apply(null,arguments)},Kl=b._emscripten_bind_btSoftBodyWorldInfo_set_m_dispatcher_1= +function(){return(Kl=b._emscripten_bind_btSoftBodyWorldInfo_set_m_dispatcher_1=b.asm.Gj).apply(null,arguments)},Ll=b._emscripten_bind_btSoftBodyWorldInfo_get_m_gravity_0=function(){return(Ll=b._emscripten_bind_btSoftBodyWorldInfo_get_m_gravity_0=b.asm.Hj).apply(null,arguments)},Ml=b._emscripten_bind_btSoftBodyWorldInfo_set_m_gravity_1=function(){return(Ml=b._emscripten_bind_btSoftBodyWorldInfo_set_m_gravity_1=b.asm.Ij).apply(null,arguments)},Nl=b._emscripten_bind_btSoftBodyWorldInfo___destroy___0= +function(){return(Nl=b._emscripten_bind_btSoftBodyWorldInfo___destroy___0=b.asm.Jj).apply(null,arguments)},Ol=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_2=function(){return(Ol=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_2=b.asm.Kj).apply(null,arguments)},Pl=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_4=function(){return(Pl=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_4=b.asm.Lj).apply(null,arguments)},Ql=b._emscripten_bind_btConeTwistConstraint_setLimit_2= +function(){return(Ql=b._emscripten_bind_btConeTwistConstraint_setLimit_2=b.asm.Mj).apply(null,arguments)},Rl=b._emscripten_bind_btConeTwistConstraint_setAngularOnly_1=function(){return(Rl=b._emscripten_bind_btConeTwistConstraint_setAngularOnly_1=b.asm.Nj).apply(null,arguments)},Sl=b._emscripten_bind_btConeTwistConstraint_setDamping_1=function(){return(Sl=b._emscripten_bind_btConeTwistConstraint_setDamping_1=b.asm.Oj).apply(null,arguments)},Tl=b._emscripten_bind_btConeTwistConstraint_enableMotor_1= +function(){return(Tl=b._emscripten_bind_btConeTwistConstraint_enableMotor_1=b.asm.Pj).apply(null,arguments)},Ul=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulse_1=function(){return(Ul=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulse_1=b.asm.Qj).apply(null,arguments)},Vl=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulseNormalized_1=function(){return(Vl=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulseNormalized_1=b.asm.Rj).apply(null,arguments)},Wl=b._emscripten_bind_btConeTwistConstraint_setMotorTarget_1= +function(){return(Wl=b._emscripten_bind_btConeTwistConstraint_setMotorTarget_1=b.asm.Sj).apply(null,arguments)},Xl=b._emscripten_bind_btConeTwistConstraint_setMotorTargetInConstraintSpace_1=function(){return(Xl=b._emscripten_bind_btConeTwistConstraint_setMotorTargetInConstraintSpace_1=b.asm.Tj).apply(null,arguments)},Yl=b._emscripten_bind_btConeTwistConstraint_enableFeedback_1=function(){return(Yl=b._emscripten_bind_btConeTwistConstraint_enableFeedback_1=b.asm.Uj).apply(null,arguments)},Zl=b._emscripten_bind_btConeTwistConstraint_getBreakingImpulseThreshold_0= +function(){return(Zl=b._emscripten_bind_btConeTwistConstraint_getBreakingImpulseThreshold_0=b.asm.Vj).apply(null,arguments)},$l=b._emscripten_bind_btConeTwistConstraint_setBreakingImpulseThreshold_1=function(){return($l=b._emscripten_bind_btConeTwistConstraint_setBreakingImpulseThreshold_1=b.asm.Wj).apply(null,arguments)},am=b._emscripten_bind_btConeTwistConstraint_getParam_2=function(){return(am=b._emscripten_bind_btConeTwistConstraint_getParam_2=b.asm.Xj).apply(null,arguments)},bm=b._emscripten_bind_btConeTwistConstraint_setParam_3= +function(){return(bm=b._emscripten_bind_btConeTwistConstraint_setParam_3=b.asm.Yj).apply(null,arguments)},cm=b._emscripten_bind_btConeTwistConstraint___destroy___0=function(){return(cm=b._emscripten_bind_btConeTwistConstraint___destroy___0=b.asm.Zj).apply(null,arguments)},dm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_2=function(){return(dm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_2=b.asm._j).apply(null,arguments)},em=b._emscripten_bind_btHingeConstraint_btHingeConstraint_3= +function(){return(em=b._emscripten_bind_btHingeConstraint_btHingeConstraint_3=b.asm.$j).apply(null,arguments)},fm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_4=function(){return(fm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_4=b.asm.ak).apply(null,arguments)},gm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_5=function(){return(gm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_5=b.asm.bk).apply(null,arguments)},hm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_6= +function(){return(hm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_6=b.asm.ck).apply(null,arguments)},im=b._emscripten_bind_btHingeConstraint_btHingeConstraint_7=function(){return(im=b._emscripten_bind_btHingeConstraint_btHingeConstraint_7=b.asm.dk).apply(null,arguments)},jm=b._emscripten_bind_btHingeConstraint_setLimit_4=function(){return(jm=b._emscripten_bind_btHingeConstraint_setLimit_4=b.asm.ek).apply(null,arguments)},km=b._emscripten_bind_btHingeConstraint_setLimit_5=function(){return(km= +b._emscripten_bind_btHingeConstraint_setLimit_5=b.asm.fk).apply(null,arguments)},lm=b._emscripten_bind_btHingeConstraint_enableAngularMotor_3=function(){return(lm=b._emscripten_bind_btHingeConstraint_enableAngularMotor_3=b.asm.gk).apply(null,arguments)},mm=b._emscripten_bind_btHingeConstraint_setAngularOnly_1=function(){return(mm=b._emscripten_bind_btHingeConstraint_setAngularOnly_1=b.asm.hk).apply(null,arguments)},nm=b._emscripten_bind_btHingeConstraint_enableMotor_1=function(){return(nm=b._emscripten_bind_btHingeConstraint_enableMotor_1= +b.asm.ik).apply(null,arguments)},om=b._emscripten_bind_btHingeConstraint_setMaxMotorImpulse_1=function(){return(om=b._emscripten_bind_btHingeConstraint_setMaxMotorImpulse_1=b.asm.jk).apply(null,arguments)},pm=b._emscripten_bind_btHingeConstraint_setMotorTarget_2=function(){return(pm=b._emscripten_bind_btHingeConstraint_setMotorTarget_2=b.asm.kk).apply(null,arguments)},qm=b._emscripten_bind_btHingeConstraint_enableFeedback_1=function(){return(qm=b._emscripten_bind_btHingeConstraint_enableFeedback_1= +b.asm.lk).apply(null,arguments)},rm=b._emscripten_bind_btHingeConstraint_getBreakingImpulseThreshold_0=function(){return(rm=b._emscripten_bind_btHingeConstraint_getBreakingImpulseThreshold_0=b.asm.mk).apply(null,arguments)},sm=b._emscripten_bind_btHingeConstraint_setBreakingImpulseThreshold_1=function(){return(sm=b._emscripten_bind_btHingeConstraint_setBreakingImpulseThreshold_1=b.asm.nk).apply(null,arguments)},tm=b._emscripten_bind_btHingeConstraint_getParam_2=function(){return(tm=b._emscripten_bind_btHingeConstraint_getParam_2= +b.asm.ok).apply(null,arguments)},um=b._emscripten_bind_btHingeConstraint_setParam_3=function(){return(um=b._emscripten_bind_btHingeConstraint_setParam_3=b.asm.pk).apply(null,arguments)},wm=b._emscripten_bind_btHingeConstraint___destroy___0=function(){return(wm=b._emscripten_bind_btHingeConstraint___destroy___0=b.asm.qk).apply(null,arguments)},xm=b._emscripten_bind_btConeShapeZ_btConeShapeZ_2=function(){return(xm=b._emscripten_bind_btConeShapeZ_btConeShapeZ_2=b.asm.rk).apply(null,arguments)},ym=b._emscripten_bind_btConeShapeZ_setLocalScaling_1= +function(){return(ym=b._emscripten_bind_btConeShapeZ_setLocalScaling_1=b.asm.sk).apply(null,arguments)},zm=b._emscripten_bind_btConeShapeZ_getLocalScaling_0=function(){return(zm=b._emscripten_bind_btConeShapeZ_getLocalScaling_0=b.asm.tk).apply(null,arguments)},Am=b._emscripten_bind_btConeShapeZ_calculateLocalInertia_2=function(){return(Am=b._emscripten_bind_btConeShapeZ_calculateLocalInertia_2=b.asm.uk).apply(null,arguments)},Bm=b._emscripten_bind_btConeShapeZ___destroy___0=function(){return(Bm=b._emscripten_bind_btConeShapeZ___destroy___0= +b.asm.vk).apply(null,arguments)},Cm=b._emscripten_bind_btConeShapeX_btConeShapeX_2=function(){return(Cm=b._emscripten_bind_btConeShapeX_btConeShapeX_2=b.asm.wk).apply(null,arguments)},Dm=b._emscripten_bind_btConeShapeX_setLocalScaling_1=function(){return(Dm=b._emscripten_bind_btConeShapeX_setLocalScaling_1=b.asm.xk).apply(null,arguments)},Em=b._emscripten_bind_btConeShapeX_getLocalScaling_0=function(){return(Em=b._emscripten_bind_btConeShapeX_getLocalScaling_0=b.asm.yk).apply(null,arguments)},Fm= +b._emscripten_bind_btConeShapeX_calculateLocalInertia_2=function(){return(Fm=b._emscripten_bind_btConeShapeX_calculateLocalInertia_2=b.asm.zk).apply(null,arguments)},Gm=b._emscripten_bind_btConeShapeX___destroy___0=function(){return(Gm=b._emscripten_bind_btConeShapeX___destroy___0=b.asm.Ak).apply(null,arguments)},Hm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_0=function(){return(Hm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_0=b.asm.Bk).apply(null,arguments)},Im=b._emscripten_bind_btTriangleMesh_btTriangleMesh_1= +function(){return(Im=b._emscripten_bind_btTriangleMesh_btTriangleMesh_1=b.asm.Ck).apply(null,arguments)},Jm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_2=function(){return(Jm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_2=b.asm.Dk).apply(null,arguments)},Km=b._emscripten_bind_btTriangleMesh_addTriangle_3=function(){return(Km=b._emscripten_bind_btTriangleMesh_addTriangle_3=b.asm.Ek).apply(null,arguments)},Lm=b._emscripten_bind_btTriangleMesh_addTriangle_4=function(){return(Lm=b._emscripten_bind_btTriangleMesh_addTriangle_4= +b.asm.Fk).apply(null,arguments)},Mm=b._emscripten_bind_btTriangleMesh_findOrAddVertex_2=function(){return(Mm=b._emscripten_bind_btTriangleMesh_findOrAddVertex_2=b.asm.Gk).apply(null,arguments)},Nm=b._emscripten_bind_btTriangleMesh_addIndex_1=function(){return(Nm=b._emscripten_bind_btTriangleMesh_addIndex_1=b.asm.Hk).apply(null,arguments)},Om=b._emscripten_bind_btTriangleMesh_getIndexedMeshArray_0=function(){return(Om=b._emscripten_bind_btTriangleMesh_getIndexedMeshArray_0=b.asm.Ik).apply(null,arguments)}, +Pm=b._emscripten_bind_btTriangleMesh_setScaling_1=function(){return(Pm=b._emscripten_bind_btTriangleMesh_setScaling_1=b.asm.Jk).apply(null,arguments)},Qm=b._emscripten_bind_btTriangleMesh___destroy___0=function(){return(Qm=b._emscripten_bind_btTriangleMesh___destroy___0=b.asm.Kk).apply(null,arguments)},Rm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_0=function(){return(Rm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_0=b.asm.Lk).apply(null,arguments)},Sm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_1= +function(){return(Sm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_1=b.asm.Mk).apply(null,arguments)},Tm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_2=function(){return(Tm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_2=b.asm.Nk).apply(null,arguments)},Um=b._emscripten_bind_btConvexHullShape_addPoint_1=function(){return(Um=b._emscripten_bind_btConvexHullShape_addPoint_1=b.asm.Ok).apply(null,arguments)},Vm=b._emscripten_bind_btConvexHullShape_addPoint_2=function(){return(Vm= +b._emscripten_bind_btConvexHullShape_addPoint_2=b.asm.Pk).apply(null,arguments)},Wm=b._emscripten_bind_btConvexHullShape_setMargin_1=function(){return(Wm=b._emscripten_bind_btConvexHullShape_setMargin_1=b.asm.Qk).apply(null,arguments)},Xm=b._emscripten_bind_btConvexHullShape_getMargin_0=function(){return(Xm=b._emscripten_bind_btConvexHullShape_getMargin_0=b.asm.Rk).apply(null,arguments)},Ym=b._emscripten_bind_btConvexHullShape_getNumVertices_0=function(){return(Ym=b._emscripten_bind_btConvexHullShape_getNumVertices_0= +b.asm.Sk).apply(null,arguments)},Zm=b._emscripten_bind_btConvexHullShape_initializePolyhedralFeatures_1=function(){return(Zm=b._emscripten_bind_btConvexHullShape_initializePolyhedralFeatures_1=b.asm.Tk).apply(null,arguments)},$m=b._emscripten_bind_btConvexHullShape_recalcLocalAabb_0=function(){return($m=b._emscripten_bind_btConvexHullShape_recalcLocalAabb_0=b.asm.Uk).apply(null,arguments)},an=b._emscripten_bind_btConvexHullShape_getConvexPolyhedron_0=function(){return(an=b._emscripten_bind_btConvexHullShape_getConvexPolyhedron_0= +b.asm.Vk).apply(null,arguments)},bn=b._emscripten_bind_btConvexHullShape_setLocalScaling_1=function(){return(bn=b._emscripten_bind_btConvexHullShape_setLocalScaling_1=b.asm.Wk).apply(null,arguments)},cn=b._emscripten_bind_btConvexHullShape_getLocalScaling_0=function(){return(cn=b._emscripten_bind_btConvexHullShape_getLocalScaling_0=b.asm.Xk).apply(null,arguments)},dn=b._emscripten_bind_btConvexHullShape_calculateLocalInertia_2=function(){return(dn=b._emscripten_bind_btConvexHullShape_calculateLocalInertia_2= +b.asm.Yk).apply(null,arguments)},en=b._emscripten_bind_btConvexHullShape___destroy___0=function(){return(en=b._emscripten_bind_btConvexHullShape___destroy___0=b.asm.Zk).apply(null,arguments)},fn=b._emscripten_bind_btVehicleTuning_btVehicleTuning_0=function(){return(fn=b._emscripten_bind_btVehicleTuning_btVehicleTuning_0=b.asm._k).apply(null,arguments)},gn=b._emscripten_bind_btVehicleTuning_get_m_suspensionStiffness_0=function(){return(gn=b._emscripten_bind_btVehicleTuning_get_m_suspensionStiffness_0= +b.asm.$k).apply(null,arguments)},hn=b._emscripten_bind_btVehicleTuning_set_m_suspensionStiffness_1=function(){return(hn=b._emscripten_bind_btVehicleTuning_set_m_suspensionStiffness_1=b.asm.al).apply(null,arguments)},jn=b._emscripten_bind_btVehicleTuning_get_m_suspensionCompression_0=function(){return(jn=b._emscripten_bind_btVehicleTuning_get_m_suspensionCompression_0=b.asm.bl).apply(null,arguments)},kn=b._emscripten_bind_btVehicleTuning_set_m_suspensionCompression_1=function(){return(kn=b._emscripten_bind_btVehicleTuning_set_m_suspensionCompression_1= +b.asm.cl).apply(null,arguments)},ln=b._emscripten_bind_btVehicleTuning_get_m_suspensionDamping_0=function(){return(ln=b._emscripten_bind_btVehicleTuning_get_m_suspensionDamping_0=b.asm.dl).apply(null,arguments)},mn=b._emscripten_bind_btVehicleTuning_set_m_suspensionDamping_1=function(){return(mn=b._emscripten_bind_btVehicleTuning_set_m_suspensionDamping_1=b.asm.el).apply(null,arguments)},nn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionTravelCm_0=function(){return(nn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionTravelCm_0= +b.asm.fl).apply(null,arguments)},on=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionTravelCm_1=function(){return(on=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionTravelCm_1=b.asm.gl).apply(null,arguments)},pn=b._emscripten_bind_btVehicleTuning_get_m_frictionSlip_0=function(){return(pn=b._emscripten_bind_btVehicleTuning_get_m_frictionSlip_0=b.asm.hl).apply(null,arguments)},qn=b._emscripten_bind_btVehicleTuning_set_m_frictionSlip_1=function(){return(qn=b._emscripten_bind_btVehicleTuning_set_m_frictionSlip_1= +b.asm.il).apply(null,arguments)},rn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionForce_0=function(){return(rn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionForce_0=b.asm.jl).apply(null,arguments)},sn=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionForce_1=function(){return(sn=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionForce_1=b.asm.kl).apply(null,arguments)},tn=b._emscripten_bind_btCollisionObjectWrapper_getWorldTransform_0=function(){return(tn=b._emscripten_bind_btCollisionObjectWrapper_getWorldTransform_0= +b.asm.ll).apply(null,arguments)},un=b._emscripten_bind_btCollisionObjectWrapper_getCollisionObject_0=function(){return(un=b._emscripten_bind_btCollisionObjectWrapper_getCollisionObject_0=b.asm.ml).apply(null,arguments)},vn=b._emscripten_bind_btCollisionObjectWrapper_getCollisionShape_0=function(){return(vn=b._emscripten_bind_btCollisionObjectWrapper_getCollisionShape_0=b.asm.nl).apply(null,arguments)},wn=b._emscripten_bind_btShapeHull_btShapeHull_1=function(){return(wn=b._emscripten_bind_btShapeHull_btShapeHull_1= +b.asm.ol).apply(null,arguments)},xn=b._emscripten_bind_btShapeHull_buildHull_1=function(){return(xn=b._emscripten_bind_btShapeHull_buildHull_1=b.asm.pl).apply(null,arguments)},yn=b._emscripten_bind_btShapeHull_numVertices_0=function(){return(yn=b._emscripten_bind_btShapeHull_numVertices_0=b.asm.ql).apply(null,arguments)},zn=b._emscripten_bind_btShapeHull_getVertexPointer_0=function(){return(zn=b._emscripten_bind_btShapeHull_getVertexPointer_0=b.asm.rl).apply(null,arguments)},An=b._emscripten_bind_btShapeHull___destroy___0= +function(){return(An=b._emscripten_bind_btShapeHull___destroy___0=b.asm.sl).apply(null,arguments)},Bn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_0=function(){return(Bn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_0=b.asm.tl).apply(null,arguments)},Cn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_1=function(){return(Cn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_1=b.asm.ul).apply(null,arguments)},Dn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_2= +function(){return(Dn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_2=b.asm.vl).apply(null,arguments)},En=b._emscripten_bind_btDefaultMotionState_getWorldTransform_1=function(){return(En=b._emscripten_bind_btDefaultMotionState_getWorldTransform_1=b.asm.wl).apply(null,arguments)},Fn=b._emscripten_bind_btDefaultMotionState_setWorldTransform_1=function(){return(Fn=b._emscripten_bind_btDefaultMotionState_setWorldTransform_1=b.asm.xl).apply(null,arguments)},Gn=b._emscripten_bind_btDefaultMotionState_get_m_graphicsWorldTrans_0= +function(){return(Gn=b._emscripten_bind_btDefaultMotionState_get_m_graphicsWorldTrans_0=b.asm.yl).apply(null,arguments)},Hn=b._emscripten_bind_btDefaultMotionState_set_m_graphicsWorldTrans_1=function(){return(Hn=b._emscripten_bind_btDefaultMotionState_set_m_graphicsWorldTrans_1=b.asm.zl).apply(null,arguments)},In=b._emscripten_bind_btDefaultMotionState___destroy___0=function(){return(In=b._emscripten_bind_btDefaultMotionState___destroy___0=b.asm.Al).apply(null,arguments)},Jn=b._emscripten_bind_btWheelInfo_btWheelInfo_1= +function(){return(Jn=b._emscripten_bind_btWheelInfo_btWheelInfo_1=b.asm.Bl).apply(null,arguments)},Kn=b._emscripten_bind_btWheelInfo_getSuspensionRestLength_0=function(){return(Kn=b._emscripten_bind_btWheelInfo_getSuspensionRestLength_0=b.asm.Cl).apply(null,arguments)},Ln=b._emscripten_bind_btWheelInfo_updateWheel_2=function(){return(Ln=b._emscripten_bind_btWheelInfo_updateWheel_2=b.asm.Dl).apply(null,arguments)},Mn=b._emscripten_bind_btWheelInfo_get_m_suspensionStiffness_0=function(){return(Mn=b._emscripten_bind_btWheelInfo_get_m_suspensionStiffness_0= +b.asm.El).apply(null,arguments)},Nn=b._emscripten_bind_btWheelInfo_set_m_suspensionStiffness_1=function(){return(Nn=b._emscripten_bind_btWheelInfo_set_m_suspensionStiffness_1=b.asm.Fl).apply(null,arguments)},On=b._emscripten_bind_btWheelInfo_get_m_frictionSlip_0=function(){return(On=b._emscripten_bind_btWheelInfo_get_m_frictionSlip_0=b.asm.Gl).apply(null,arguments)},Pn=b._emscripten_bind_btWheelInfo_set_m_frictionSlip_1=function(){return(Pn=b._emscripten_bind_btWheelInfo_set_m_frictionSlip_1=b.asm.Hl).apply(null, +arguments)},Qn=b._emscripten_bind_btWheelInfo_get_m_engineForce_0=function(){return(Qn=b._emscripten_bind_btWheelInfo_get_m_engineForce_0=b.asm.Il).apply(null,arguments)},Rn=b._emscripten_bind_btWheelInfo_set_m_engineForce_1=function(){return(Rn=b._emscripten_bind_btWheelInfo_set_m_engineForce_1=b.asm.Jl).apply(null,arguments)},Sn=b._emscripten_bind_btWheelInfo_get_m_rollInfluence_0=function(){return(Sn=b._emscripten_bind_btWheelInfo_get_m_rollInfluence_0=b.asm.Kl).apply(null,arguments)},Tn=b._emscripten_bind_btWheelInfo_set_m_rollInfluence_1= +function(){return(Tn=b._emscripten_bind_btWheelInfo_set_m_rollInfluence_1=b.asm.Ll).apply(null,arguments)},Un=b._emscripten_bind_btWheelInfo_get_m_suspensionRestLength1_0=function(){return(Un=b._emscripten_bind_btWheelInfo_get_m_suspensionRestLength1_0=b.asm.Ml).apply(null,arguments)},Vn=b._emscripten_bind_btWheelInfo_set_m_suspensionRestLength1_1=function(){return(Vn=b._emscripten_bind_btWheelInfo_set_m_suspensionRestLength1_1=b.asm.Nl).apply(null,arguments)},Wn=b._emscripten_bind_btWheelInfo_get_m_wheelsRadius_0= +function(){return(Wn=b._emscripten_bind_btWheelInfo_get_m_wheelsRadius_0=b.asm.Ol).apply(null,arguments)},Xn=b._emscripten_bind_btWheelInfo_set_m_wheelsRadius_1=function(){return(Xn=b._emscripten_bind_btWheelInfo_set_m_wheelsRadius_1=b.asm.Pl).apply(null,arguments)},Yn=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingCompression_0=function(){return(Yn=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingCompression_0=b.asm.Ql).apply(null,arguments)},Zn=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingCompression_1= +function(){return(Zn=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingCompression_1=b.asm.Rl).apply(null,arguments)},$n=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingRelaxation_0=function(){return($n=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingRelaxation_0=b.asm.Sl).apply(null,arguments)},ao=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingRelaxation_1=function(){return(ao=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingRelaxation_1=b.asm.Tl).apply(null,arguments)},bo=b._emscripten_bind_btWheelInfo_get_m_steering_0= +function(){return(bo=b._emscripten_bind_btWheelInfo_get_m_steering_0=b.asm.Ul).apply(null,arguments)},co=b._emscripten_bind_btWheelInfo_set_m_steering_1=function(){return(co=b._emscripten_bind_btWheelInfo_set_m_steering_1=b.asm.Vl).apply(null,arguments)},eo=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionForce_0=function(){return(eo=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionForce_0=b.asm.Wl).apply(null,arguments)},fo=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionForce_1=function(){return(fo= +b._emscripten_bind_btWheelInfo_set_m_maxSuspensionForce_1=b.asm.Xl).apply(null,arguments)},go=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionTravelCm_0=function(){return(go=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionTravelCm_0=b.asm.Yl).apply(null,arguments)},ho=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionTravelCm_1=function(){return(ho=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionTravelCm_1=b.asm.Zl).apply(null,arguments)},io=b._emscripten_bind_btWheelInfo_get_m_wheelsSuspensionForce_0= +function(){return(io=b._emscripten_bind_btWheelInfo_get_m_wheelsSuspensionForce_0=b.asm._l).apply(null,arguments)},jo=b._emscripten_bind_btWheelInfo_set_m_wheelsSuspensionForce_1=function(){return(jo=b._emscripten_bind_btWheelInfo_set_m_wheelsSuspensionForce_1=b.asm.$l).apply(null,arguments)},ko=b._emscripten_bind_btWheelInfo_get_m_bIsFrontWheel_0=function(){return(ko=b._emscripten_bind_btWheelInfo_get_m_bIsFrontWheel_0=b.asm.am).apply(null,arguments)},lo=b._emscripten_bind_btWheelInfo_set_m_bIsFrontWheel_1= +function(){return(lo=b._emscripten_bind_btWheelInfo_set_m_bIsFrontWheel_1=b.asm.bm).apply(null,arguments)},mo=b._emscripten_bind_btWheelInfo_get_m_raycastInfo_0=function(){return(mo=b._emscripten_bind_btWheelInfo_get_m_raycastInfo_0=b.asm.cm).apply(null,arguments)},no=b._emscripten_bind_btWheelInfo_set_m_raycastInfo_1=function(){return(no=b._emscripten_bind_btWheelInfo_set_m_raycastInfo_1=b.asm.dm).apply(null,arguments)},oo=b._emscripten_bind_btWheelInfo_get_m_chassisConnectionPointCS_0=function(){return(oo= +b._emscripten_bind_btWheelInfo_get_m_chassisConnectionPointCS_0=b.asm.em).apply(null,arguments)},po=b._emscripten_bind_btWheelInfo_set_m_chassisConnectionPointCS_1=function(){return(po=b._emscripten_bind_btWheelInfo_set_m_chassisConnectionPointCS_1=b.asm.fm).apply(null,arguments)},qo=b._emscripten_bind_btWheelInfo_get_m_worldTransform_0=function(){return(qo=b._emscripten_bind_btWheelInfo_get_m_worldTransform_0=b.asm.gm).apply(null,arguments)},ro=b._emscripten_bind_btWheelInfo_set_m_worldTransform_1= +function(){return(ro=b._emscripten_bind_btWheelInfo_set_m_worldTransform_1=b.asm.hm).apply(null,arguments)},so=b._emscripten_bind_btWheelInfo_get_m_wheelDirectionCS_0=function(){return(so=b._emscripten_bind_btWheelInfo_get_m_wheelDirectionCS_0=b.asm.im).apply(null,arguments)},to=b._emscripten_bind_btWheelInfo_set_m_wheelDirectionCS_1=function(){return(to=b._emscripten_bind_btWheelInfo_set_m_wheelDirectionCS_1=b.asm.jm).apply(null,arguments)},uo=b._emscripten_bind_btWheelInfo_get_m_wheelAxleCS_0=function(){return(uo= +b._emscripten_bind_btWheelInfo_get_m_wheelAxleCS_0=b.asm.km).apply(null,arguments)},vo=b._emscripten_bind_btWheelInfo_set_m_wheelAxleCS_1=function(){return(vo=b._emscripten_bind_btWheelInfo_set_m_wheelAxleCS_1=b.asm.lm).apply(null,arguments)},wo=b._emscripten_bind_btWheelInfo_get_m_rotation_0=function(){return(wo=b._emscripten_bind_btWheelInfo_get_m_rotation_0=b.asm.mm).apply(null,arguments)},xo=b._emscripten_bind_btWheelInfo_set_m_rotation_1=function(){return(xo=b._emscripten_bind_btWheelInfo_set_m_rotation_1= +b.asm.nm).apply(null,arguments)},yo=b._emscripten_bind_btWheelInfo_get_m_deltaRotation_0=function(){return(yo=b._emscripten_bind_btWheelInfo_get_m_deltaRotation_0=b.asm.om).apply(null,arguments)},zo=b._emscripten_bind_btWheelInfo_set_m_deltaRotation_1=function(){return(zo=b._emscripten_bind_btWheelInfo_set_m_deltaRotation_1=b.asm.pm).apply(null,arguments)},Ao=b._emscripten_bind_btWheelInfo_get_m_brake_0=function(){return(Ao=b._emscripten_bind_btWheelInfo_get_m_brake_0=b.asm.qm).apply(null,arguments)}, +Bo=b._emscripten_bind_btWheelInfo_set_m_brake_1=function(){return(Bo=b._emscripten_bind_btWheelInfo_set_m_brake_1=b.asm.rm).apply(null,arguments)},Co=b._emscripten_bind_btWheelInfo_get_m_clippedInvContactDotSuspension_0=function(){return(Co=b._emscripten_bind_btWheelInfo_get_m_clippedInvContactDotSuspension_0=b.asm.sm).apply(null,arguments)},Do=b._emscripten_bind_btWheelInfo_set_m_clippedInvContactDotSuspension_1=function(){return(Do=b._emscripten_bind_btWheelInfo_set_m_clippedInvContactDotSuspension_1= +b.asm.tm).apply(null,arguments)},Eo=b._emscripten_bind_btWheelInfo_get_m_suspensionRelativeVelocity_0=function(){return(Eo=b._emscripten_bind_btWheelInfo_get_m_suspensionRelativeVelocity_0=b.asm.um).apply(null,arguments)},Fo=b._emscripten_bind_btWheelInfo_set_m_suspensionRelativeVelocity_1=function(){return(Fo=b._emscripten_bind_btWheelInfo_set_m_suspensionRelativeVelocity_1=b.asm.vm).apply(null,arguments)},Go=b._emscripten_bind_btWheelInfo_get_m_skidInfo_0=function(){return(Go=b._emscripten_bind_btWheelInfo_get_m_skidInfo_0= +b.asm.wm).apply(null,arguments)},Ho=b._emscripten_bind_btWheelInfo_set_m_skidInfo_1=function(){return(Ho=b._emscripten_bind_btWheelInfo_set_m_skidInfo_1=b.asm.xm).apply(null,arguments)},Io=b._emscripten_bind_btWheelInfo___destroy___0=function(){return(Io=b._emscripten_bind_btWheelInfo___destroy___0=b.asm.ym).apply(null,arguments)},Jo=b._emscripten_bind_btVector4_btVector4_0=function(){return(Jo=b._emscripten_bind_btVector4_btVector4_0=b.asm.zm).apply(null,arguments)},Ko=b._emscripten_bind_btVector4_btVector4_4= +function(){return(Ko=b._emscripten_bind_btVector4_btVector4_4=b.asm.Am).apply(null,arguments)},Lo=b._emscripten_bind_btVector4_w_0=function(){return(Lo=b._emscripten_bind_btVector4_w_0=b.asm.Bm).apply(null,arguments)},Mo=b._emscripten_bind_btVector4_setValue_4=function(){return(Mo=b._emscripten_bind_btVector4_setValue_4=b.asm.Cm).apply(null,arguments)},No=b._emscripten_bind_btVector4_length_0=function(){return(No=b._emscripten_bind_btVector4_length_0=b.asm.Dm).apply(null,arguments)},Oo=b._emscripten_bind_btVector4_x_0= +function(){return(Oo=b._emscripten_bind_btVector4_x_0=b.asm.Em).apply(null,arguments)},Po=b._emscripten_bind_btVector4_y_0=function(){return(Po=b._emscripten_bind_btVector4_y_0=b.asm.Fm).apply(null,arguments)},Qo=b._emscripten_bind_btVector4_z_0=function(){return(Qo=b._emscripten_bind_btVector4_z_0=b.asm.Gm).apply(null,arguments)},Ro=b._emscripten_bind_btVector4_setX_1=function(){return(Ro=b._emscripten_bind_btVector4_setX_1=b.asm.Hm).apply(null,arguments)},So=b._emscripten_bind_btVector4_setY_1= +function(){return(So=b._emscripten_bind_btVector4_setY_1=b.asm.Im).apply(null,arguments)},To=b._emscripten_bind_btVector4_setZ_1=function(){return(To=b._emscripten_bind_btVector4_setZ_1=b.asm.Jm).apply(null,arguments)},Uo=b._emscripten_bind_btVector4_normalize_0=function(){return(Uo=b._emscripten_bind_btVector4_normalize_0=b.asm.Km).apply(null,arguments)},Vo=b._emscripten_bind_btVector4_rotate_2=function(){return(Vo=b._emscripten_bind_btVector4_rotate_2=b.asm.Lm).apply(null,arguments)},Wo=b._emscripten_bind_btVector4_dot_1= +function(){return(Wo=b._emscripten_bind_btVector4_dot_1=b.asm.Mm).apply(null,arguments)},Xo=b._emscripten_bind_btVector4_op_mul_1=function(){return(Xo=b._emscripten_bind_btVector4_op_mul_1=b.asm.Nm).apply(null,arguments)},Yo=b._emscripten_bind_btVector4_op_add_1=function(){return(Yo=b._emscripten_bind_btVector4_op_add_1=b.asm.Om).apply(null,arguments)},Zo=b._emscripten_bind_btVector4_op_sub_1=function(){return(Zo=b._emscripten_bind_btVector4_op_sub_1=b.asm.Pm).apply(null,arguments)},$o=b._emscripten_bind_btVector4___destroy___0= +function(){return($o=b._emscripten_bind_btVector4___destroy___0=b.asm.Qm).apply(null,arguments)},ap=b._emscripten_bind_btDefaultCollisionConstructionInfo_btDefaultCollisionConstructionInfo_0=function(){return(ap=b._emscripten_bind_btDefaultCollisionConstructionInfo_btDefaultCollisionConstructionInfo_0=b.asm.Rm).apply(null,arguments)},bp=b._emscripten_bind_btDefaultCollisionConstructionInfo___destroy___0=function(){return(bp=b._emscripten_bind_btDefaultCollisionConstructionInfo___destroy___0=b.asm.Sm).apply(null, +arguments)},cp=b._emscripten_bind_Anchor_get_m_node_0=function(){return(cp=b._emscripten_bind_Anchor_get_m_node_0=b.asm.Tm).apply(null,arguments)},dp=b._emscripten_bind_Anchor_set_m_node_1=function(){return(dp=b._emscripten_bind_Anchor_set_m_node_1=b.asm.Um).apply(null,arguments)},ep=b._emscripten_bind_Anchor_get_m_local_0=function(){return(ep=b._emscripten_bind_Anchor_get_m_local_0=b.asm.Vm).apply(null,arguments)},fp=b._emscripten_bind_Anchor_set_m_local_1=function(){return(fp=b._emscripten_bind_Anchor_set_m_local_1= +b.asm.Wm).apply(null,arguments)},gp=b._emscripten_bind_Anchor_get_m_body_0=function(){return(gp=b._emscripten_bind_Anchor_get_m_body_0=b.asm.Xm).apply(null,arguments)},hp=b._emscripten_bind_Anchor_set_m_body_1=function(){return(hp=b._emscripten_bind_Anchor_set_m_body_1=b.asm.Ym).apply(null,arguments)},ip=b._emscripten_bind_Anchor_get_m_influence_0=function(){return(ip=b._emscripten_bind_Anchor_get_m_influence_0=b.asm.Zm).apply(null,arguments)},jp=b._emscripten_bind_Anchor_set_m_influence_1=function(){return(jp= +b._emscripten_bind_Anchor_set_m_influence_1=b.asm._m).apply(null,arguments)},kp=b._emscripten_bind_Anchor_get_m_c0_0=function(){return(kp=b._emscripten_bind_Anchor_get_m_c0_0=b.asm.$m).apply(null,arguments)},lp=b._emscripten_bind_Anchor_set_m_c0_1=function(){return(lp=b._emscripten_bind_Anchor_set_m_c0_1=b.asm.an).apply(null,arguments)},mp=b._emscripten_bind_Anchor_get_m_c1_0=function(){return(mp=b._emscripten_bind_Anchor_get_m_c1_0=b.asm.bn).apply(null,arguments)},np=b._emscripten_bind_Anchor_set_m_c1_1= +function(){return(np=b._emscripten_bind_Anchor_set_m_c1_1=b.asm.cn).apply(null,arguments)},op=b._emscripten_bind_Anchor_get_m_c2_0=function(){return(op=b._emscripten_bind_Anchor_get_m_c2_0=b.asm.dn).apply(null,arguments)},pp=b._emscripten_bind_Anchor_set_m_c2_1=function(){return(pp=b._emscripten_bind_Anchor_set_m_c2_1=b.asm.en).apply(null,arguments)},qp=b._emscripten_bind_Anchor___destroy___0=function(){return(qp=b._emscripten_bind_Anchor___destroy___0=b.asm.fn).apply(null,arguments)},rp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitPointInWorld_0= +function(){return(rp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitPointInWorld_0=b.asm.gn).apply(null,arguments)},sp=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitPointInWorld_1=function(){return(sp=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitPointInWorld_1=b.asm.hn).apply(null,arguments)},tp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitNormalInWorld_0=function(){return(tp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitNormalInWorld_0=b.asm.jn).apply(null,arguments)}, +up=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitNormalInWorld_1=function(){return(up=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitNormalInWorld_1=b.asm.kn).apply(null,arguments)},vp=b._emscripten_bind_btVehicleRaycasterResult_get_m_distFraction_0=function(){return(vp=b._emscripten_bind_btVehicleRaycasterResult_get_m_distFraction_0=b.asm.ln).apply(null,arguments)},wp=b._emscripten_bind_btVehicleRaycasterResult_set_m_distFraction_1=function(){return(wp=b._emscripten_bind_btVehicleRaycasterResult_set_m_distFraction_1= +b.asm.mn).apply(null,arguments)},xp=b._emscripten_bind_btVehicleRaycasterResult___destroy___0=function(){return(xp=b._emscripten_bind_btVehicleRaycasterResult___destroy___0=b.asm.nn).apply(null,arguments)},yp=b._emscripten_bind_btVector3Array_size_0=function(){return(yp=b._emscripten_bind_btVector3Array_size_0=b.asm.on).apply(null,arguments)},zp=b._emscripten_bind_btVector3Array_at_1=function(){return(zp=b._emscripten_bind_btVector3Array_at_1=b.asm.pn).apply(null,arguments)},Ap=b._emscripten_bind_btVector3Array___destroy___0= +function(){return(Ap=b._emscripten_bind_btVector3Array___destroy___0=b.asm.qn).apply(null,arguments)},Bp=b._emscripten_bind_btConstraintSolver___destroy___0=function(){return(Bp=b._emscripten_bind_btConstraintSolver___destroy___0=b.asm.rn).apply(null,arguments)},Cp=b._emscripten_bind_btRaycastVehicle_btRaycastVehicle_3=function(){return(Cp=b._emscripten_bind_btRaycastVehicle_btRaycastVehicle_3=b.asm.sn).apply(null,arguments)},Dp=b._emscripten_bind_btRaycastVehicle_applyEngineForce_2=function(){return(Dp= +b._emscripten_bind_btRaycastVehicle_applyEngineForce_2=b.asm.tn).apply(null,arguments)},Ep=b._emscripten_bind_btRaycastVehicle_setSteeringValue_2=function(){return(Ep=b._emscripten_bind_btRaycastVehicle_setSteeringValue_2=b.asm.un).apply(null,arguments)},Fp=b._emscripten_bind_btRaycastVehicle_getWheelTransformWS_1=function(){return(Fp=b._emscripten_bind_btRaycastVehicle_getWheelTransformWS_1=b.asm.vn).apply(null,arguments)},Gp=b._emscripten_bind_btRaycastVehicle_updateWheelTransform_2=function(){return(Gp= +b._emscripten_bind_btRaycastVehicle_updateWheelTransform_2=b.asm.wn).apply(null,arguments)},Hp=b._emscripten_bind_btRaycastVehicle_addWheel_7=function(){return(Hp=b._emscripten_bind_btRaycastVehicle_addWheel_7=b.asm.xn).apply(null,arguments)},Ip=b._emscripten_bind_btRaycastVehicle_getNumWheels_0=function(){return(Ip=b._emscripten_bind_btRaycastVehicle_getNumWheels_0=b.asm.yn).apply(null,arguments)},Jp=b._emscripten_bind_btRaycastVehicle_getRigidBody_0=function(){return(Jp=b._emscripten_bind_btRaycastVehicle_getRigidBody_0= +b.asm.zn).apply(null,arguments)},Kp=b._emscripten_bind_btRaycastVehicle_getWheelInfo_1=function(){return(Kp=b._emscripten_bind_btRaycastVehicle_getWheelInfo_1=b.asm.An).apply(null,arguments)},Lp=b._emscripten_bind_btRaycastVehicle_setBrake_2=function(){return(Lp=b._emscripten_bind_btRaycastVehicle_setBrake_2=b.asm.Bn).apply(null,arguments)},Mp=b._emscripten_bind_btRaycastVehicle_setCoordinateSystem_3=function(){return(Mp=b._emscripten_bind_btRaycastVehicle_setCoordinateSystem_3=b.asm.Cn).apply(null, +arguments)},Np=b._emscripten_bind_btRaycastVehicle_getCurrentSpeedKmHour_0=function(){return(Np=b._emscripten_bind_btRaycastVehicle_getCurrentSpeedKmHour_0=b.asm.Dn).apply(null,arguments)},Op=b._emscripten_bind_btRaycastVehicle_getChassisWorldTransform_0=function(){return(Op=b._emscripten_bind_btRaycastVehicle_getChassisWorldTransform_0=b.asm.En).apply(null,arguments)},Pp=b._emscripten_bind_btRaycastVehicle_rayCast_1=function(){return(Pp=b._emscripten_bind_btRaycastVehicle_rayCast_1=b.asm.Fn).apply(null, +arguments)},Qp=b._emscripten_bind_btRaycastVehicle_updateVehicle_1=function(){return(Qp=b._emscripten_bind_btRaycastVehicle_updateVehicle_1=b.asm.Gn).apply(null,arguments)},Rp=b._emscripten_bind_btRaycastVehicle_resetSuspension_0=function(){return(Rp=b._emscripten_bind_btRaycastVehicle_resetSuspension_0=b.asm.Hn).apply(null,arguments)},Sp=b._emscripten_bind_btRaycastVehicle_getSteeringValue_1=function(){return(Sp=b._emscripten_bind_btRaycastVehicle_getSteeringValue_1=b.asm.In).apply(null,arguments)}, +Tp=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_1=function(){return(Tp=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_1=b.asm.Jn).apply(null,arguments)},Up=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_2=function(){return(Up=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_2=b.asm.Kn).apply(null,arguments)},Vp=b._emscripten_bind_btRaycastVehicle_setPitchControl_1=function(){return(Vp=b._emscripten_bind_btRaycastVehicle_setPitchControl_1=b.asm.Ln).apply(null, +arguments)},Wp=b._emscripten_bind_btRaycastVehicle_updateSuspension_1=function(){return(Wp=b._emscripten_bind_btRaycastVehicle_updateSuspension_1=b.asm.Mn).apply(null,arguments)},Xp=b._emscripten_bind_btRaycastVehicle_updateFriction_1=function(){return(Xp=b._emscripten_bind_btRaycastVehicle_updateFriction_1=b.asm.Nn).apply(null,arguments)},Yp=b._emscripten_bind_btRaycastVehicle_getRightAxis_0=function(){return(Yp=b._emscripten_bind_btRaycastVehicle_getRightAxis_0=b.asm.On).apply(null,arguments)}, +Zp=b._emscripten_bind_btRaycastVehicle_getUpAxis_0=function(){return(Zp=b._emscripten_bind_btRaycastVehicle_getUpAxis_0=b.asm.Pn).apply(null,arguments)},$p=b._emscripten_bind_btRaycastVehicle_getForwardAxis_0=function(){return($p=b._emscripten_bind_btRaycastVehicle_getForwardAxis_0=b.asm.Qn).apply(null,arguments)},aq=b._emscripten_bind_btRaycastVehicle_getForwardVector_0=function(){return(aq=b._emscripten_bind_btRaycastVehicle_getForwardVector_0=b.asm.Rn).apply(null,arguments)},bq=b._emscripten_bind_btRaycastVehicle_getUserConstraintType_0= +function(){return(bq=b._emscripten_bind_btRaycastVehicle_getUserConstraintType_0=b.asm.Sn).apply(null,arguments)},cq=b._emscripten_bind_btRaycastVehicle_setUserConstraintType_1=function(){return(cq=b._emscripten_bind_btRaycastVehicle_setUserConstraintType_1=b.asm.Tn).apply(null,arguments)},dq=b._emscripten_bind_btRaycastVehicle_setUserConstraintId_1=function(){return(dq=b._emscripten_bind_btRaycastVehicle_setUserConstraintId_1=b.asm.Un).apply(null,arguments)},eq=b._emscripten_bind_btRaycastVehicle_getUserConstraintId_0= +function(){return(eq=b._emscripten_bind_btRaycastVehicle_getUserConstraintId_0=b.asm.Vn).apply(null,arguments)},fq=b._emscripten_bind_btRaycastVehicle_updateAction_2=function(){return(fq=b._emscripten_bind_btRaycastVehicle_updateAction_2=b.asm.Wn).apply(null,arguments)},gq=b._emscripten_bind_btRaycastVehicle___destroy___0=function(){return(gq=b._emscripten_bind_btRaycastVehicle___destroy___0=b.asm.Xn).apply(null,arguments)},hq=b._emscripten_bind_btCylinderShapeX_btCylinderShapeX_1=function(){return(hq= +b._emscripten_bind_btCylinderShapeX_btCylinderShapeX_1=b.asm.Yn).apply(null,arguments)},iq=b._emscripten_bind_btCylinderShapeX_setMargin_1=function(){return(iq=b._emscripten_bind_btCylinderShapeX_setMargin_1=b.asm.Zn).apply(null,arguments)},jq=b._emscripten_bind_btCylinderShapeX_getMargin_0=function(){return(jq=b._emscripten_bind_btCylinderShapeX_getMargin_0=b.asm._n).apply(null,arguments)},kq=b._emscripten_bind_btCylinderShapeX_setLocalScaling_1=function(){return(kq=b._emscripten_bind_btCylinderShapeX_setLocalScaling_1= +b.asm.$n).apply(null,arguments)},lq=b._emscripten_bind_btCylinderShapeX_getLocalScaling_0=function(){return(lq=b._emscripten_bind_btCylinderShapeX_getLocalScaling_0=b.asm.ao).apply(null,arguments)},mq=b._emscripten_bind_btCylinderShapeX_calculateLocalInertia_2=function(){return(mq=b._emscripten_bind_btCylinderShapeX_calculateLocalInertia_2=b.asm.bo).apply(null,arguments)},nq=b._emscripten_bind_btCylinderShapeX___destroy___0=function(){return(nq=b._emscripten_bind_btCylinderShapeX___destroy___0=b.asm.co).apply(null, +arguments)},oq=b._emscripten_bind_btCylinderShapeZ_btCylinderShapeZ_1=function(){return(oq=b._emscripten_bind_btCylinderShapeZ_btCylinderShapeZ_1=b.asm.eo).apply(null,arguments)},pq=b._emscripten_bind_btCylinderShapeZ_setMargin_1=function(){return(pq=b._emscripten_bind_btCylinderShapeZ_setMargin_1=b.asm.fo).apply(null,arguments)},qq=b._emscripten_bind_btCylinderShapeZ_getMargin_0=function(){return(qq=b._emscripten_bind_btCylinderShapeZ_getMargin_0=b.asm.go).apply(null,arguments)},rq=b._emscripten_bind_btCylinderShapeZ_setLocalScaling_1= +function(){return(rq=b._emscripten_bind_btCylinderShapeZ_setLocalScaling_1=b.asm.ho).apply(null,arguments)},sq=b._emscripten_bind_btCylinderShapeZ_getLocalScaling_0=function(){return(sq=b._emscripten_bind_btCylinderShapeZ_getLocalScaling_0=b.asm.io).apply(null,arguments)},tq=b._emscripten_bind_btCylinderShapeZ_calculateLocalInertia_2=function(){return(tq=b._emscripten_bind_btCylinderShapeZ_calculateLocalInertia_2=b.asm.jo).apply(null,arguments)},uq=b._emscripten_bind_btCylinderShapeZ___destroy___0= +function(){return(uq=b._emscripten_bind_btCylinderShapeZ___destroy___0=b.asm.ko).apply(null,arguments)},vq=b._emscripten_bind_btConvexPolyhedron_get_m_vertices_0=function(){return(vq=b._emscripten_bind_btConvexPolyhedron_get_m_vertices_0=b.asm.lo).apply(null,arguments)},wq=b._emscripten_bind_btConvexPolyhedron_set_m_vertices_1=function(){return(wq=b._emscripten_bind_btConvexPolyhedron_set_m_vertices_1=b.asm.mo).apply(null,arguments)},xq=b._emscripten_bind_btConvexPolyhedron_get_m_faces_0=function(){return(xq= +b._emscripten_bind_btConvexPolyhedron_get_m_faces_0=b.asm.no).apply(null,arguments)},yq=b._emscripten_bind_btConvexPolyhedron_set_m_faces_1=function(){return(yq=b._emscripten_bind_btConvexPolyhedron_set_m_faces_1=b.asm.oo).apply(null,arguments)},zq=b._emscripten_bind_btConvexPolyhedron___destroy___0=function(){return(zq=b._emscripten_bind_btConvexPolyhedron___destroy___0=b.asm.po).apply(null,arguments)},Aq=b._emscripten_bind_btSequentialImpulseConstraintSolver_btSequentialImpulseConstraintSolver_0= +function(){return(Aq=b._emscripten_bind_btSequentialImpulseConstraintSolver_btSequentialImpulseConstraintSolver_0=b.asm.qo).apply(null,arguments)},Bq=b._emscripten_bind_btSequentialImpulseConstraintSolver___destroy___0=function(){return(Bq=b._emscripten_bind_btSequentialImpulseConstraintSolver___destroy___0=b.asm.ro).apply(null,arguments)},Cq=b._emscripten_bind_tAnchorArray_size_0=function(){return(Cq=b._emscripten_bind_tAnchorArray_size_0=b.asm.so).apply(null,arguments)},Dq=b._emscripten_bind_tAnchorArray_at_1= +function(){return(Dq=b._emscripten_bind_tAnchorArray_at_1=b.asm.to).apply(null,arguments)},Eq=b._emscripten_bind_tAnchorArray_clear_0=function(){return(Eq=b._emscripten_bind_tAnchorArray_clear_0=b.asm.uo).apply(null,arguments)},Fq=b._emscripten_bind_tAnchorArray_push_back_1=function(){return(Fq=b._emscripten_bind_tAnchorArray_push_back_1=b.asm.vo).apply(null,arguments)},Gq=b._emscripten_bind_tAnchorArray_pop_back_0=function(){return(Gq=b._emscripten_bind_tAnchorArray_pop_back_0=b.asm.wo).apply(null, +arguments)},Hq=b._emscripten_bind_tAnchorArray___destroy___0=function(){return(Hq=b._emscripten_bind_tAnchorArray___destroy___0=b.asm.xo).apply(null,arguments)},Iq=b._emscripten_bind_RaycastInfo_get_m_contactNormalWS_0=function(){return(Iq=b._emscripten_bind_RaycastInfo_get_m_contactNormalWS_0=b.asm.yo).apply(null,arguments)},Jq=b._emscripten_bind_RaycastInfo_set_m_contactNormalWS_1=function(){return(Jq=b._emscripten_bind_RaycastInfo_set_m_contactNormalWS_1=b.asm.zo).apply(null,arguments)},Kq=b._emscripten_bind_RaycastInfo_get_m_contactPointWS_0= +function(){return(Kq=b._emscripten_bind_RaycastInfo_get_m_contactPointWS_0=b.asm.Ao).apply(null,arguments)},Lq=b._emscripten_bind_RaycastInfo_set_m_contactPointWS_1=function(){return(Lq=b._emscripten_bind_RaycastInfo_set_m_contactPointWS_1=b.asm.Bo).apply(null,arguments)},Mq=b._emscripten_bind_RaycastInfo_get_m_suspensionLength_0=function(){return(Mq=b._emscripten_bind_RaycastInfo_get_m_suspensionLength_0=b.asm.Co).apply(null,arguments)},Nq=b._emscripten_bind_RaycastInfo_set_m_suspensionLength_1= +function(){return(Nq=b._emscripten_bind_RaycastInfo_set_m_suspensionLength_1=b.asm.Do).apply(null,arguments)},Oq=b._emscripten_bind_RaycastInfo_get_m_hardPointWS_0=function(){return(Oq=b._emscripten_bind_RaycastInfo_get_m_hardPointWS_0=b.asm.Eo).apply(null,arguments)},Pq=b._emscripten_bind_RaycastInfo_set_m_hardPointWS_1=function(){return(Pq=b._emscripten_bind_RaycastInfo_set_m_hardPointWS_1=b.asm.Fo).apply(null,arguments)},Qq=b._emscripten_bind_RaycastInfo_get_m_wheelDirectionWS_0=function(){return(Qq= +b._emscripten_bind_RaycastInfo_get_m_wheelDirectionWS_0=b.asm.Go).apply(null,arguments)},Rq=b._emscripten_bind_RaycastInfo_set_m_wheelDirectionWS_1=function(){return(Rq=b._emscripten_bind_RaycastInfo_set_m_wheelDirectionWS_1=b.asm.Ho).apply(null,arguments)},Sq=b._emscripten_bind_RaycastInfo_get_m_wheelAxleWS_0=function(){return(Sq=b._emscripten_bind_RaycastInfo_get_m_wheelAxleWS_0=b.asm.Io).apply(null,arguments)},Tq=b._emscripten_bind_RaycastInfo_set_m_wheelAxleWS_1=function(){return(Tq=b._emscripten_bind_RaycastInfo_set_m_wheelAxleWS_1= +b.asm.Jo).apply(null,arguments)},Uq=b._emscripten_bind_RaycastInfo_get_m_isInContact_0=function(){return(Uq=b._emscripten_bind_RaycastInfo_get_m_isInContact_0=b.asm.Ko).apply(null,arguments)},Vq=b._emscripten_bind_RaycastInfo_set_m_isInContact_1=function(){return(Vq=b._emscripten_bind_RaycastInfo_set_m_isInContact_1=b.asm.Lo).apply(null,arguments)},Wq=b._emscripten_bind_RaycastInfo_get_m_groundObject_0=function(){return(Wq=b._emscripten_bind_RaycastInfo_get_m_groundObject_0=b.asm.Mo).apply(null,arguments)}, +Xq=b._emscripten_bind_RaycastInfo_set_m_groundObject_1=function(){return(Xq=b._emscripten_bind_RaycastInfo_set_m_groundObject_1=b.asm.No).apply(null,arguments)},Yq=b._emscripten_bind_RaycastInfo___destroy___0=function(){return(Yq=b._emscripten_bind_RaycastInfo___destroy___0=b.asm.Oo).apply(null,arguments)},Zq=b._emscripten_bind_btMultiSphereShape_btMultiSphereShape_3=function(){return(Zq=b._emscripten_bind_btMultiSphereShape_btMultiSphereShape_3=b.asm.Po).apply(null,arguments)},$q=b._emscripten_bind_btMultiSphereShape_setLocalScaling_1= +function(){return($q=b._emscripten_bind_btMultiSphereShape_setLocalScaling_1=b.asm.Qo).apply(null,arguments)},ar=b._emscripten_bind_btMultiSphereShape_getLocalScaling_0=function(){return(ar=b._emscripten_bind_btMultiSphereShape_getLocalScaling_0=b.asm.Ro).apply(null,arguments)},br=b._emscripten_bind_btMultiSphereShape_calculateLocalInertia_2=function(){return(br=b._emscripten_bind_btMultiSphereShape_calculateLocalInertia_2=b.asm.So).apply(null,arguments)},cr=b._emscripten_bind_btMultiSphereShape___destroy___0= +function(){return(cr=b._emscripten_bind_btMultiSphereShape___destroy___0=b.asm.To).apply(null,arguments)},dr=b._emscripten_bind_btSoftBody_btSoftBody_4=function(){return(dr=b._emscripten_bind_btSoftBody_btSoftBody_4=b.asm.Uo).apply(null,arguments)},er=b._emscripten_bind_btSoftBody_checkLink_2=function(){return(er=b._emscripten_bind_btSoftBody_checkLink_2=b.asm.Vo).apply(null,arguments)},fr=b._emscripten_bind_btSoftBody_checkFace_3=function(){return(fr=b._emscripten_bind_btSoftBody_checkFace_3=b.asm.Wo).apply(null, +arguments)},gr=b._emscripten_bind_btSoftBody_appendMaterial_0=function(){return(gr=b._emscripten_bind_btSoftBody_appendMaterial_0=b.asm.Xo).apply(null,arguments)},hr=b._emscripten_bind_btSoftBody_appendNode_2=function(){return(hr=b._emscripten_bind_btSoftBody_appendNode_2=b.asm.Yo).apply(null,arguments)},ir=b._emscripten_bind_btSoftBody_appendLink_4=function(){return(ir=b._emscripten_bind_btSoftBody_appendLink_4=b.asm.Zo).apply(null,arguments)},jr=b._emscripten_bind_btSoftBody_appendFace_4=function(){return(jr= +b._emscripten_bind_btSoftBody_appendFace_4=b.asm._o).apply(null,arguments)},kr=b._emscripten_bind_btSoftBody_appendTetra_5=function(){return(kr=b._emscripten_bind_btSoftBody_appendTetra_5=b.asm.$o).apply(null,arguments)},lr=b._emscripten_bind_btSoftBody_appendAnchor_4=function(){return(lr=b._emscripten_bind_btSoftBody_appendAnchor_4=b.asm.ap).apply(null,arguments)},mr=b._emscripten_bind_btSoftBody_addForce_1=function(){return(mr=b._emscripten_bind_btSoftBody_addForce_1=b.asm.bp).apply(null,arguments)}, +nr=b._emscripten_bind_btSoftBody_addForce_2=function(){return(nr=b._emscripten_bind_btSoftBody_addForce_2=b.asm.cp).apply(null,arguments)},or=b._emscripten_bind_btSoftBody_addAeroForceToNode_2=function(){return(or=b._emscripten_bind_btSoftBody_addAeroForceToNode_2=b.asm.dp).apply(null,arguments)},pr=b._emscripten_bind_btSoftBody_getTotalMass_0=function(){return(pr=b._emscripten_bind_btSoftBody_getTotalMass_0=b.asm.ep).apply(null,arguments)},qr=b._emscripten_bind_btSoftBody_setTotalMass_2=function(){return(qr= +b._emscripten_bind_btSoftBody_setTotalMass_2=b.asm.fp).apply(null,arguments)},rr=b._emscripten_bind_btSoftBody_setMass_2=function(){return(rr=b._emscripten_bind_btSoftBody_setMass_2=b.asm.gp).apply(null,arguments)},sr=b._emscripten_bind_btSoftBody_transform_1=function(){return(sr=b._emscripten_bind_btSoftBody_transform_1=b.asm.hp).apply(null,arguments)},tr=b._emscripten_bind_btSoftBody_translate_1=function(){return(tr=b._emscripten_bind_btSoftBody_translate_1=b.asm.ip).apply(null,arguments)},ur=b._emscripten_bind_btSoftBody_rotate_1= +function(){return(ur=b._emscripten_bind_btSoftBody_rotate_1=b.asm.jp).apply(null,arguments)},vr=b._emscripten_bind_btSoftBody_scale_1=function(){return(vr=b._emscripten_bind_btSoftBody_scale_1=b.asm.kp).apply(null,arguments)},wr=b._emscripten_bind_btSoftBody_generateClusters_1=function(){return(wr=b._emscripten_bind_btSoftBody_generateClusters_1=b.asm.lp).apply(null,arguments)},xr=b._emscripten_bind_btSoftBody_generateClusters_2=function(){return(xr=b._emscripten_bind_btSoftBody_generateClusters_2= +b.asm.mp).apply(null,arguments)},yr=b._emscripten_bind_btSoftBody_generateBendingConstraints_2=function(){return(yr=b._emscripten_bind_btSoftBody_generateBendingConstraints_2=b.asm.np).apply(null,arguments)},zr=b._emscripten_bind_btSoftBody_upcast_1=function(){return(zr=b._emscripten_bind_btSoftBody_upcast_1=b.asm.op).apply(null,arguments)},Ar=b._emscripten_bind_btSoftBody_setAnisotropicFriction_2=function(){return(Ar=b._emscripten_bind_btSoftBody_setAnisotropicFriction_2=b.asm.pp).apply(null,arguments)}, +Br=b._emscripten_bind_btSoftBody_getCollisionShape_0=function(){return(Br=b._emscripten_bind_btSoftBody_getCollisionShape_0=b.asm.qp).apply(null,arguments)},Cr=b._emscripten_bind_btSoftBody_setContactProcessingThreshold_1=function(){return(Cr=b._emscripten_bind_btSoftBody_setContactProcessingThreshold_1=b.asm.rp).apply(null,arguments)},Dr=b._emscripten_bind_btSoftBody_setActivationState_1=function(){return(Dr=b._emscripten_bind_btSoftBody_setActivationState_1=b.asm.sp).apply(null,arguments)},Er=b._emscripten_bind_btSoftBody_forceActivationState_1= +function(){return(Er=b._emscripten_bind_btSoftBody_forceActivationState_1=b.asm.tp).apply(null,arguments)},Fr=b._emscripten_bind_btSoftBody_activate_0=function(){return(Fr=b._emscripten_bind_btSoftBody_activate_0=b.asm.up).apply(null,arguments)},Gr=b._emscripten_bind_btSoftBody_activate_1=function(){return(Gr=b._emscripten_bind_btSoftBody_activate_1=b.asm.vp).apply(null,arguments)},Hr=b._emscripten_bind_btSoftBody_isActive_0=function(){return(Hr=b._emscripten_bind_btSoftBody_isActive_0=b.asm.wp).apply(null, +arguments)},Ir=b._emscripten_bind_btSoftBody_isKinematicObject_0=function(){return(Ir=b._emscripten_bind_btSoftBody_isKinematicObject_0=b.asm.xp).apply(null,arguments)},Jr=b._emscripten_bind_btSoftBody_isStaticObject_0=function(){return(Jr=b._emscripten_bind_btSoftBody_isStaticObject_0=b.asm.yp).apply(null,arguments)},Kr=b._emscripten_bind_btSoftBody_isStaticOrKinematicObject_0=function(){return(Kr=b._emscripten_bind_btSoftBody_isStaticOrKinematicObject_0=b.asm.zp).apply(null,arguments)},Lr=b._emscripten_bind_btSoftBody_getRestitution_0= +function(){return(Lr=b._emscripten_bind_btSoftBody_getRestitution_0=b.asm.Ap).apply(null,arguments)},Mr=b._emscripten_bind_btSoftBody_getFriction_0=function(){return(Mr=b._emscripten_bind_btSoftBody_getFriction_0=b.asm.Bp).apply(null,arguments)},Nr=b._emscripten_bind_btSoftBody_getRollingFriction_0=function(){return(Nr=b._emscripten_bind_btSoftBody_getRollingFriction_0=b.asm.Cp).apply(null,arguments)},Or=b._emscripten_bind_btSoftBody_setRestitution_1=function(){return(Or=b._emscripten_bind_btSoftBody_setRestitution_1= +b.asm.Dp).apply(null,arguments)},Pr=b._emscripten_bind_btSoftBody_setFriction_1=function(){return(Pr=b._emscripten_bind_btSoftBody_setFriction_1=b.asm.Ep).apply(null,arguments)},Qr=b._emscripten_bind_btSoftBody_setRollingFriction_1=function(){return(Qr=b._emscripten_bind_btSoftBody_setRollingFriction_1=b.asm.Fp).apply(null,arguments)},Rr=b._emscripten_bind_btSoftBody_getWorldTransform_0=function(){return(Rr=b._emscripten_bind_btSoftBody_getWorldTransform_0=b.asm.Gp).apply(null,arguments)},Sr=b._emscripten_bind_btSoftBody_getCollisionFlags_0= +function(){return(Sr=b._emscripten_bind_btSoftBody_getCollisionFlags_0=b.asm.Hp).apply(null,arguments)},Tr=b._emscripten_bind_btSoftBody_setCollisionFlags_1=function(){return(Tr=b._emscripten_bind_btSoftBody_setCollisionFlags_1=b.asm.Ip).apply(null,arguments)},Ur=b._emscripten_bind_btSoftBody_setWorldTransform_1=function(){return(Ur=b._emscripten_bind_btSoftBody_setWorldTransform_1=b.asm.Jp).apply(null,arguments)},Vr=b._emscripten_bind_btSoftBody_setCollisionShape_1=function(){return(Vr=b._emscripten_bind_btSoftBody_setCollisionShape_1= +b.asm.Kp).apply(null,arguments)},Wr=b._emscripten_bind_btSoftBody_setCcdMotionThreshold_1=function(){return(Wr=b._emscripten_bind_btSoftBody_setCcdMotionThreshold_1=b.asm.Lp).apply(null,arguments)},Xr=b._emscripten_bind_btSoftBody_setCcdSweptSphereRadius_1=function(){return(Xr=b._emscripten_bind_btSoftBody_setCcdSweptSphereRadius_1=b.asm.Mp).apply(null,arguments)},Yr=b._emscripten_bind_btSoftBody_getUserIndex_0=function(){return(Yr=b._emscripten_bind_btSoftBody_getUserIndex_0=b.asm.Np).apply(null, +arguments)},Zr=b._emscripten_bind_btSoftBody_setUserIndex_1=function(){return(Zr=b._emscripten_bind_btSoftBody_setUserIndex_1=b.asm.Op).apply(null,arguments)},$r=b._emscripten_bind_btSoftBody_getUserPointer_0=function(){return($r=b._emscripten_bind_btSoftBody_getUserPointer_0=b.asm.Pp).apply(null,arguments)},as=b._emscripten_bind_btSoftBody_setUserPointer_1=function(){return(as=b._emscripten_bind_btSoftBody_setUserPointer_1=b.asm.Qp).apply(null,arguments)},bs=b._emscripten_bind_btSoftBody_getBroadphaseHandle_0= +function(){return(bs=b._emscripten_bind_btSoftBody_getBroadphaseHandle_0=b.asm.Rp).apply(null,arguments)},cs=b._emscripten_bind_btSoftBody_get_m_cfg_0=function(){return(cs=b._emscripten_bind_btSoftBody_get_m_cfg_0=b.asm.Sp).apply(null,arguments)},ds=b._emscripten_bind_btSoftBody_set_m_cfg_1=function(){return(ds=b._emscripten_bind_btSoftBody_set_m_cfg_1=b.asm.Tp).apply(null,arguments)},es=b._emscripten_bind_btSoftBody_get_m_nodes_0=function(){return(es=b._emscripten_bind_btSoftBody_get_m_nodes_0=b.asm.Up).apply(null, +arguments)},gs=b._emscripten_bind_btSoftBody_set_m_nodes_1=function(){return(gs=b._emscripten_bind_btSoftBody_set_m_nodes_1=b.asm.Vp).apply(null,arguments)},hs=b._emscripten_bind_btSoftBody_get_m_faces_0=function(){return(hs=b._emscripten_bind_btSoftBody_get_m_faces_0=b.asm.Wp).apply(null,arguments)},is=b._emscripten_bind_btSoftBody_set_m_faces_1=function(){return(is=b._emscripten_bind_btSoftBody_set_m_faces_1=b.asm.Xp).apply(null,arguments)},js=b._emscripten_bind_btSoftBody_get_m_materials_0=function(){return(js= +b._emscripten_bind_btSoftBody_get_m_materials_0=b.asm.Yp).apply(null,arguments)},ks=b._emscripten_bind_btSoftBody_set_m_materials_1=function(){return(ks=b._emscripten_bind_btSoftBody_set_m_materials_1=b.asm.Zp).apply(null,arguments)},ls=b._emscripten_bind_btSoftBody_get_m_anchors_0=function(){return(ls=b._emscripten_bind_btSoftBody_get_m_anchors_0=b.asm._p).apply(null,arguments)},ms=b._emscripten_bind_btSoftBody_set_m_anchors_1=function(){return(ms=b._emscripten_bind_btSoftBody_set_m_anchors_1=b.asm.$p).apply(null, +arguments)},ns=b._emscripten_bind_btSoftBody___destroy___0=function(){return(ns=b._emscripten_bind_btSoftBody___destroy___0=b.asm.aq).apply(null,arguments)},ps=b._emscripten_bind_btIntArray_size_0=function(){return(ps=b._emscripten_bind_btIntArray_size_0=b.asm.bq).apply(null,arguments)},qs=b._emscripten_bind_btIntArray_at_1=function(){return(qs=b._emscripten_bind_btIntArray_at_1=b.asm.cq).apply(null,arguments)},rs=b._emscripten_bind_btIntArray___destroy___0=function(){return(rs=b._emscripten_bind_btIntArray___destroy___0= +b.asm.dq).apply(null,arguments)},ss=b._emscripten_bind_Config_get_kVCF_0=function(){return(ss=b._emscripten_bind_Config_get_kVCF_0=b.asm.eq).apply(null,arguments)},ts=b._emscripten_bind_Config_set_kVCF_1=function(){return(ts=b._emscripten_bind_Config_set_kVCF_1=b.asm.fq).apply(null,arguments)},us=b._emscripten_bind_Config_get_kDP_0=function(){return(us=b._emscripten_bind_Config_get_kDP_0=b.asm.gq).apply(null,arguments)},vs=b._emscripten_bind_Config_set_kDP_1=function(){return(vs=b._emscripten_bind_Config_set_kDP_1= +b.asm.hq).apply(null,arguments)},xs=b._emscripten_bind_Config_get_kDG_0=function(){return(xs=b._emscripten_bind_Config_get_kDG_0=b.asm.iq).apply(null,arguments)},ys=b._emscripten_bind_Config_set_kDG_1=function(){return(ys=b._emscripten_bind_Config_set_kDG_1=b.asm.jq).apply(null,arguments)},zs=b._emscripten_bind_Config_get_kLF_0=function(){return(zs=b._emscripten_bind_Config_get_kLF_0=b.asm.kq).apply(null,arguments)},As=b._emscripten_bind_Config_set_kLF_1=function(){return(As=b._emscripten_bind_Config_set_kLF_1= +b.asm.lq).apply(null,arguments)},Bs=b._emscripten_bind_Config_get_kPR_0=function(){return(Bs=b._emscripten_bind_Config_get_kPR_0=b.asm.mq).apply(null,arguments)},Cs=b._emscripten_bind_Config_set_kPR_1=function(){return(Cs=b._emscripten_bind_Config_set_kPR_1=b.asm.nq).apply(null,arguments)},Ds=b._emscripten_bind_Config_get_kVC_0=function(){return(Ds=b._emscripten_bind_Config_get_kVC_0=b.asm.oq).apply(null,arguments)},Es=b._emscripten_bind_Config_set_kVC_1=function(){return(Es=b._emscripten_bind_Config_set_kVC_1= +b.asm.pq).apply(null,arguments)},Fs=b._emscripten_bind_Config_get_kDF_0=function(){return(Fs=b._emscripten_bind_Config_get_kDF_0=b.asm.qq).apply(null,arguments)},Gs=b._emscripten_bind_Config_set_kDF_1=function(){return(Gs=b._emscripten_bind_Config_set_kDF_1=b.asm.rq).apply(null,arguments)},Hs=b._emscripten_bind_Config_get_kMT_0=function(){return(Hs=b._emscripten_bind_Config_get_kMT_0=b.asm.sq).apply(null,arguments)},Is=b._emscripten_bind_Config_set_kMT_1=function(){return(Is=b._emscripten_bind_Config_set_kMT_1= +b.asm.tq).apply(null,arguments)},Js=b._emscripten_bind_Config_get_kCHR_0=function(){return(Js=b._emscripten_bind_Config_get_kCHR_0=b.asm.uq).apply(null,arguments)},Ks=b._emscripten_bind_Config_set_kCHR_1=function(){return(Ks=b._emscripten_bind_Config_set_kCHR_1=b.asm.vq).apply(null,arguments)},Ls=b._emscripten_bind_Config_get_kKHR_0=function(){return(Ls=b._emscripten_bind_Config_get_kKHR_0=b.asm.wq).apply(null,arguments)},Ms=b._emscripten_bind_Config_set_kKHR_1=function(){return(Ms=b._emscripten_bind_Config_set_kKHR_1= +b.asm.xq).apply(null,arguments)},Ns=b._emscripten_bind_Config_get_kSHR_0=function(){return(Ns=b._emscripten_bind_Config_get_kSHR_0=b.asm.yq).apply(null,arguments)},Os=b._emscripten_bind_Config_set_kSHR_1=function(){return(Os=b._emscripten_bind_Config_set_kSHR_1=b.asm.zq).apply(null,arguments)},Ps=b._emscripten_bind_Config_get_kAHR_0=function(){return(Ps=b._emscripten_bind_Config_get_kAHR_0=b.asm.Aq).apply(null,arguments)},Qs=b._emscripten_bind_Config_set_kAHR_1=function(){return(Qs=b._emscripten_bind_Config_set_kAHR_1= +b.asm.Bq).apply(null,arguments)},Rs=b._emscripten_bind_Config_get_kSRHR_CL_0=function(){return(Rs=b._emscripten_bind_Config_get_kSRHR_CL_0=b.asm.Cq).apply(null,arguments)},Ss=b._emscripten_bind_Config_set_kSRHR_CL_1=function(){return(Ss=b._emscripten_bind_Config_set_kSRHR_CL_1=b.asm.Dq).apply(null,arguments)},Ts=b._emscripten_bind_Config_get_kSKHR_CL_0=function(){return(Ts=b._emscripten_bind_Config_get_kSKHR_CL_0=b.asm.Eq).apply(null,arguments)},Us=b._emscripten_bind_Config_set_kSKHR_CL_1=function(){return(Us= +b._emscripten_bind_Config_set_kSKHR_CL_1=b.asm.Fq).apply(null,arguments)},Vs=b._emscripten_bind_Config_get_kSSHR_CL_0=function(){return(Vs=b._emscripten_bind_Config_get_kSSHR_CL_0=b.asm.Gq).apply(null,arguments)},Ws=b._emscripten_bind_Config_set_kSSHR_CL_1=function(){return(Ws=b._emscripten_bind_Config_set_kSSHR_CL_1=b.asm.Hq).apply(null,arguments)},Xs=b._emscripten_bind_Config_get_kSR_SPLT_CL_0=function(){return(Xs=b._emscripten_bind_Config_get_kSR_SPLT_CL_0=b.asm.Iq).apply(null,arguments)},Ys=b._emscripten_bind_Config_set_kSR_SPLT_CL_1= +function(){return(Ys=b._emscripten_bind_Config_set_kSR_SPLT_CL_1=b.asm.Jq).apply(null,arguments)},Zs=b._emscripten_bind_Config_get_kSK_SPLT_CL_0=function(){return(Zs=b._emscripten_bind_Config_get_kSK_SPLT_CL_0=b.asm.Kq).apply(null,arguments)},$s=b._emscripten_bind_Config_set_kSK_SPLT_CL_1=function(){return($s=b._emscripten_bind_Config_set_kSK_SPLT_CL_1=b.asm.Lq).apply(null,arguments)},at=b._emscripten_bind_Config_get_kSS_SPLT_CL_0=function(){return(at=b._emscripten_bind_Config_get_kSS_SPLT_CL_0=b.asm.Mq).apply(null, +arguments)},bt=b._emscripten_bind_Config_set_kSS_SPLT_CL_1=function(){return(bt=b._emscripten_bind_Config_set_kSS_SPLT_CL_1=b.asm.Nq).apply(null,arguments)},ct=b._emscripten_bind_Config_get_maxvolume_0=function(){return(ct=b._emscripten_bind_Config_get_maxvolume_0=b.asm.Oq).apply(null,arguments)},dt=b._emscripten_bind_Config_set_maxvolume_1=function(){return(dt=b._emscripten_bind_Config_set_maxvolume_1=b.asm.Pq).apply(null,arguments)},et=b._emscripten_bind_Config_get_timescale_0=function(){return(et= +b._emscripten_bind_Config_get_timescale_0=b.asm.Qq).apply(null,arguments)},ft=b._emscripten_bind_Config_set_timescale_1=function(){return(ft=b._emscripten_bind_Config_set_timescale_1=b.asm.Rq).apply(null,arguments)},gt=b._emscripten_bind_Config_get_viterations_0=function(){return(gt=b._emscripten_bind_Config_get_viterations_0=b.asm.Sq).apply(null,arguments)},ht=b._emscripten_bind_Config_set_viterations_1=function(){return(ht=b._emscripten_bind_Config_set_viterations_1=b.asm.Tq).apply(null,arguments)}, +it=b._emscripten_bind_Config_get_piterations_0=function(){return(it=b._emscripten_bind_Config_get_piterations_0=b.asm.Uq).apply(null,arguments)},jt=b._emscripten_bind_Config_set_piterations_1=function(){return(jt=b._emscripten_bind_Config_set_piterations_1=b.asm.Vq).apply(null,arguments)},kt=b._emscripten_bind_Config_get_diterations_0=function(){return(kt=b._emscripten_bind_Config_get_diterations_0=b.asm.Wq).apply(null,arguments)},lt=b._emscripten_bind_Config_set_diterations_1=function(){return(lt= +b._emscripten_bind_Config_set_diterations_1=b.asm.Xq).apply(null,arguments)},mt=b._emscripten_bind_Config_get_citerations_0=function(){return(mt=b._emscripten_bind_Config_get_citerations_0=b.asm.Yq).apply(null,arguments)},nt=b._emscripten_bind_Config_set_citerations_1=function(){return(nt=b._emscripten_bind_Config_set_citerations_1=b.asm.Zq).apply(null,arguments)},ot=b._emscripten_bind_Config_get_collisions_0=function(){return(ot=b._emscripten_bind_Config_get_collisions_0=b.asm._q).apply(null,arguments)}, +pt=b._emscripten_bind_Config_set_collisions_1=function(){return(pt=b._emscripten_bind_Config_set_collisions_1=b.asm.$q).apply(null,arguments)},qt=b._emscripten_bind_Config___destroy___0=function(){return(qt=b._emscripten_bind_Config___destroy___0=b.asm.ar).apply(null,arguments)},rt=b._emscripten_bind_Node_get_m_x_0=function(){return(rt=b._emscripten_bind_Node_get_m_x_0=b.asm.br).apply(null,arguments)},st=b._emscripten_bind_Node_set_m_x_1=function(){return(st=b._emscripten_bind_Node_set_m_x_1=b.asm.cr).apply(null, +arguments)},tt=b._emscripten_bind_Node_get_m_q_0=function(){return(tt=b._emscripten_bind_Node_get_m_q_0=b.asm.dr).apply(null,arguments)},ut=b._emscripten_bind_Node_set_m_q_1=function(){return(ut=b._emscripten_bind_Node_set_m_q_1=b.asm.er).apply(null,arguments)},vt=b._emscripten_bind_Node_get_m_v_0=function(){return(vt=b._emscripten_bind_Node_get_m_v_0=b.asm.fr).apply(null,arguments)},wt=b._emscripten_bind_Node_set_m_v_1=function(){return(wt=b._emscripten_bind_Node_set_m_v_1=b.asm.gr).apply(null,arguments)}, +xt=b._emscripten_bind_Node_get_m_f_0=function(){return(xt=b._emscripten_bind_Node_get_m_f_0=b.asm.hr).apply(null,arguments)},yt=b._emscripten_bind_Node_set_m_f_1=function(){return(yt=b._emscripten_bind_Node_set_m_f_1=b.asm.ir).apply(null,arguments)},zt=b._emscripten_bind_Node_get_m_n_0=function(){return(zt=b._emscripten_bind_Node_get_m_n_0=b.asm.jr).apply(null,arguments)},At=b._emscripten_bind_Node_set_m_n_1=function(){return(At=b._emscripten_bind_Node_set_m_n_1=b.asm.kr).apply(null,arguments)},Bt= +b._emscripten_bind_Node_get_m_im_0=function(){return(Bt=b._emscripten_bind_Node_get_m_im_0=b.asm.lr).apply(null,arguments)},Ct=b._emscripten_bind_Node_set_m_im_1=function(){return(Ct=b._emscripten_bind_Node_set_m_im_1=b.asm.mr).apply(null,arguments)},Dt=b._emscripten_bind_Node_get_m_area_0=function(){return(Dt=b._emscripten_bind_Node_get_m_area_0=b.asm.nr).apply(null,arguments)},Et=b._emscripten_bind_Node_set_m_area_1=function(){return(Et=b._emscripten_bind_Node_set_m_area_1=b.asm.or).apply(null, +arguments)},Ft=b._emscripten_bind_Node___destroy___0=function(){return(Ft=b._emscripten_bind_Node___destroy___0=b.asm.pr).apply(null,arguments)},Gt=b._emscripten_bind_btGhostPairCallback_btGhostPairCallback_0=function(){return(Gt=b._emscripten_bind_btGhostPairCallback_btGhostPairCallback_0=b.asm.qr).apply(null,arguments)},Ht=b._emscripten_bind_btGhostPairCallback___destroy___0=function(){return(Ht=b._emscripten_bind_btGhostPairCallback___destroy___0=b.asm.rr).apply(null,arguments)},It=b._emscripten_bind_btOverlappingPairCallback___destroy___0= +function(){return(It=b._emscripten_bind_btOverlappingPairCallback___destroy___0=b.asm.sr).apply(null,arguments)},Jt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_3=function(){return(Jt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_3=b.asm.tr).apply(null,arguments)},Kt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_4=function(){return(Kt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_4= +b.asm.ur).apply(null,arguments)},Lt=b._emscripten_bind_btKinematicCharacterController_setUpAxis_1=function(){return(Lt=b._emscripten_bind_btKinematicCharacterController_setUpAxis_1=b.asm.vr).apply(null,arguments)},Mt=b._emscripten_bind_btKinematicCharacterController_setWalkDirection_1=function(){return(Mt=b._emscripten_bind_btKinematicCharacterController_setWalkDirection_1=b.asm.wr).apply(null,arguments)},Nt=b._emscripten_bind_btKinematicCharacterController_setVelocityForTimeInterval_2=function(){return(Nt= +b._emscripten_bind_btKinematicCharacterController_setVelocityForTimeInterval_2=b.asm.xr).apply(null,arguments)},Ot=b._emscripten_bind_btKinematicCharacterController_warp_1=function(){return(Ot=b._emscripten_bind_btKinematicCharacterController_warp_1=b.asm.yr).apply(null,arguments)},Pt=b._emscripten_bind_btKinematicCharacterController_preStep_1=function(){return(Pt=b._emscripten_bind_btKinematicCharacterController_preStep_1=b.asm.zr).apply(null,arguments)},Qt=b._emscripten_bind_btKinematicCharacterController_playerStep_2= +function(){return(Qt=b._emscripten_bind_btKinematicCharacterController_playerStep_2=b.asm.Ar).apply(null,arguments)},Rt=b._emscripten_bind_btKinematicCharacterController_setFallSpeed_1=function(){return(Rt=b._emscripten_bind_btKinematicCharacterController_setFallSpeed_1=b.asm.Br).apply(null,arguments)},St=b._emscripten_bind_btKinematicCharacterController_setJumpSpeed_1=function(){return(St=b._emscripten_bind_btKinematicCharacterController_setJumpSpeed_1=b.asm.Cr).apply(null,arguments)},Tt=b._emscripten_bind_btKinematicCharacterController_setMaxJumpHeight_1= +function(){return(Tt=b._emscripten_bind_btKinematicCharacterController_setMaxJumpHeight_1=b.asm.Dr).apply(null,arguments)},Ut=b._emscripten_bind_btKinematicCharacterController_canJump_0=function(){return(Ut=b._emscripten_bind_btKinematicCharacterController_canJump_0=b.asm.Er).apply(null,arguments)},Vt=b._emscripten_bind_btKinematicCharacterController_jump_0=function(){return(Vt=b._emscripten_bind_btKinematicCharacterController_jump_0=b.asm.Fr).apply(null,arguments)},Wt=b._emscripten_bind_btKinematicCharacterController_setGravity_1= +function(){return(Wt=b._emscripten_bind_btKinematicCharacterController_setGravity_1=b.asm.Gr).apply(null,arguments)},Xt=b._emscripten_bind_btKinematicCharacterController_getGravity_0=function(){return(Xt=b._emscripten_bind_btKinematicCharacterController_getGravity_0=b.asm.Hr).apply(null,arguments)},Yt=b._emscripten_bind_btKinematicCharacterController_setMaxSlope_1=function(){return(Yt=b._emscripten_bind_btKinematicCharacterController_setMaxSlope_1=b.asm.Ir).apply(null,arguments)},Zt=b._emscripten_bind_btKinematicCharacterController_getMaxSlope_0= +function(){return(Zt=b._emscripten_bind_btKinematicCharacterController_getMaxSlope_0=b.asm.Jr).apply(null,arguments)},$t=b._emscripten_bind_btKinematicCharacterController_getGhostObject_0=function(){return($t=b._emscripten_bind_btKinematicCharacterController_getGhostObject_0=b.asm.Kr).apply(null,arguments)},au=b._emscripten_bind_btKinematicCharacterController_setUseGhostSweepTest_1=function(){return(au=b._emscripten_bind_btKinematicCharacterController_setUseGhostSweepTest_1=b.asm.Lr).apply(null,arguments)}, +bu=b._emscripten_bind_btKinematicCharacterController_onGround_0=function(){return(bu=b._emscripten_bind_btKinematicCharacterController_onGround_0=b.asm.Mr).apply(null,arguments)},cu=b._emscripten_bind_btKinematicCharacterController_setUpInterpolate_1=function(){return(cu=b._emscripten_bind_btKinematicCharacterController_setUpInterpolate_1=b.asm.Nr).apply(null,arguments)},du=b._emscripten_bind_btKinematicCharacterController_updateAction_2=function(){return(du=b._emscripten_bind_btKinematicCharacterController_updateAction_2= +b.asm.Or).apply(null,arguments)},eu=b._emscripten_bind_btKinematicCharacterController___destroy___0=function(){return(eu=b._emscripten_bind_btKinematicCharacterController___destroy___0=b.asm.Pr).apply(null,arguments)},fu=b._emscripten_bind_btSoftBodyArray_size_0=function(){return(fu=b._emscripten_bind_btSoftBodyArray_size_0=b.asm.Qr).apply(null,arguments)},gu=b._emscripten_bind_btSoftBodyArray_at_1=function(){return(gu=b._emscripten_bind_btSoftBodyArray_at_1=b.asm.Rr).apply(null,arguments)},hu=b._emscripten_bind_btSoftBodyArray___destroy___0= +function(){return(hu=b._emscripten_bind_btSoftBodyArray___destroy___0=b.asm.Sr).apply(null,arguments)},iu=b._emscripten_bind_btFaceArray_size_0=function(){return(iu=b._emscripten_bind_btFaceArray_size_0=b.asm.Tr).apply(null,arguments)},ju=b._emscripten_bind_btFaceArray_at_1=function(){return(ju=b._emscripten_bind_btFaceArray_at_1=b.asm.Ur).apply(null,arguments)},ku=b._emscripten_bind_btFaceArray___destroy___0=function(){return(ku=b._emscripten_bind_btFaceArray___destroy___0=b.asm.Vr).apply(null,arguments)}, +lu=b._emscripten_bind_btStaticPlaneShape_btStaticPlaneShape_2=function(){return(lu=b._emscripten_bind_btStaticPlaneShape_btStaticPlaneShape_2=b.asm.Wr).apply(null,arguments)},mu=b._emscripten_bind_btStaticPlaneShape_setLocalScaling_1=function(){return(mu=b._emscripten_bind_btStaticPlaneShape_setLocalScaling_1=b.asm.Xr).apply(null,arguments)},nu=b._emscripten_bind_btStaticPlaneShape_getLocalScaling_0=function(){return(nu=b._emscripten_bind_btStaticPlaneShape_getLocalScaling_0=b.asm.Yr).apply(null, +arguments)},ou=b._emscripten_bind_btStaticPlaneShape_calculateLocalInertia_2=function(){return(ou=b._emscripten_bind_btStaticPlaneShape_calculateLocalInertia_2=b.asm.Zr).apply(null,arguments)},pu=b._emscripten_bind_btStaticPlaneShape___destroy___0=function(){return(pu=b._emscripten_bind_btStaticPlaneShape___destroy___0=b.asm._r).apply(null,arguments)},qu=b._emscripten_bind_btOverlappingPairCache_setInternalGhostPairCallback_1=function(){return(qu=b._emscripten_bind_btOverlappingPairCache_setInternalGhostPairCallback_1= +b.asm.$r).apply(null,arguments)},ru=b._emscripten_bind_btOverlappingPairCache_getNumOverlappingPairs_0=function(){return(ru=b._emscripten_bind_btOverlappingPairCache_getNumOverlappingPairs_0=b.asm.as).apply(null,arguments)},su=b._emscripten_bind_btOverlappingPairCache___destroy___0=function(){return(su=b._emscripten_bind_btOverlappingPairCache___destroy___0=b.asm.bs).apply(null,arguments)},tu=b._emscripten_bind_btIndexedMesh_get_m_numTriangles_0=function(){return(tu=b._emscripten_bind_btIndexedMesh_get_m_numTriangles_0= +b.asm.cs).apply(null,arguments)},uu=b._emscripten_bind_btIndexedMesh_set_m_numTriangles_1=function(){return(uu=b._emscripten_bind_btIndexedMesh_set_m_numTriangles_1=b.asm.ds).apply(null,arguments)},vu=b._emscripten_bind_btIndexedMesh___destroy___0=function(){return(vu=b._emscripten_bind_btIndexedMesh___destroy___0=b.asm.es).apply(null,arguments)},wu=b._emscripten_bind_btSoftRigidDynamicsWorld_btSoftRigidDynamicsWorld_5=function(){return(wu=b._emscripten_bind_btSoftRigidDynamicsWorld_btSoftRigidDynamicsWorld_5= +b.asm.fs).apply(null,arguments)},xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addSoftBody_3=function(){return(xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addSoftBody_3=b.asm.gs).apply(null,arguments)},yu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeSoftBody_1=function(){return(yu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeSoftBody_1=b.asm.hs).apply(null,arguments)},zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeCollisionObject_1=function(){return(zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeCollisionObject_1= +b.asm.is).apply(null,arguments)},Au=b._emscripten_bind_btSoftRigidDynamicsWorld_getWorldInfo_0=function(){return(Au=b._emscripten_bind_btSoftRigidDynamicsWorld_getWorldInfo_0=b.asm.js).apply(null,arguments)},Bu=b._emscripten_bind_btSoftRigidDynamicsWorld_getSoftBodyArray_0=function(){return(Bu=b._emscripten_bind_btSoftRigidDynamicsWorld_getSoftBodyArray_0=b.asm.ks).apply(null,arguments)},Cu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatcher_0=function(){return(Cu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatcher_0= +b.asm.ls).apply(null,arguments)},Du=b._emscripten_bind_btSoftRigidDynamicsWorld_rayTest_3=function(){return(Du=b._emscripten_bind_btSoftRigidDynamicsWorld_rayTest_3=b.asm.ms).apply(null,arguments)},Eu=b._emscripten_bind_btSoftRigidDynamicsWorld_getPairCache_0=function(){return(Eu=b._emscripten_bind_btSoftRigidDynamicsWorld_getPairCache_0=b.asm.ns).apply(null,arguments)},Fu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatchInfo_0=function(){return(Fu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatchInfo_0= +b.asm.os).apply(null,arguments)},Gu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_1=function(){return(Gu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_1=b.asm.ps).apply(null,arguments)},Hu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_2=function(){return(Hu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_2=b.asm.qs).apply(null,arguments)},Iu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_3=function(){return(Iu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_3= +b.asm.rs).apply(null,arguments)},Ju=b._emscripten_bind_btSoftRigidDynamicsWorld_getBroadphase_0=function(){return(Ju=b._emscripten_bind_btSoftRigidDynamicsWorld_getBroadphase_0=b.asm.ss).apply(null,arguments)},Ku=b._emscripten_bind_btSoftRigidDynamicsWorld_convexSweepTest_5=function(){return(Ku=b._emscripten_bind_btSoftRigidDynamicsWorld_convexSweepTest_5=b.asm.ts).apply(null,arguments)},Lu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactPairTest_3=function(){return(Lu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactPairTest_3= +b.asm.us).apply(null,arguments)},Mu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactTest_2=function(){return(Mu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactTest_2=b.asm.vs).apply(null,arguments)},Nu=b._emscripten_bind_btSoftRigidDynamicsWorld_updateSingleAabb_1=function(){return(Nu=b._emscripten_bind_btSoftRigidDynamicsWorld_updateSingleAabb_1=b.asm.ws).apply(null,arguments)},Ou=b._emscripten_bind_btSoftRigidDynamicsWorld_setDebugDrawer_1=function(){return(Ou=b._emscripten_bind_btSoftRigidDynamicsWorld_setDebugDrawer_1= +b.asm.xs).apply(null,arguments)},Pu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDebugDrawer_0=function(){return(Pu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDebugDrawer_0=b.asm.ys).apply(null,arguments)},Qu=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawWorld_0=function(){return(Qu=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawWorld_0=b.asm.zs).apply(null,arguments)},Ru=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawObject_3=function(){return(Ru=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawObject_3= +b.asm.As).apply(null,arguments)},Su=b._emscripten_bind_btSoftRigidDynamicsWorld_setGravity_1=function(){return(Su=b._emscripten_bind_btSoftRigidDynamicsWorld_setGravity_1=b.asm.Bs).apply(null,arguments)},Tu=b._emscripten_bind_btSoftRigidDynamicsWorld_getGravity_0=function(){return(Tu=b._emscripten_bind_btSoftRigidDynamicsWorld_getGravity_0=b.asm.Cs).apply(null,arguments)},Uu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_1=function(){return(Uu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_1= +b.asm.Ds).apply(null,arguments)},Vu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_3=function(){return(Vu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_3=b.asm.Es).apply(null,arguments)},Wu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeRigidBody_1=function(){return(Wu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeRigidBody_1=b.asm.Fs).apply(null,arguments)},Xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_1=function(){return(Xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_1= +b.asm.Gs).apply(null,arguments)},Yu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_2=function(){return(Yu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_2=b.asm.Hs).apply(null,arguments)},Zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeConstraint_1=function(){return(Zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeConstraint_1=b.asm.Is).apply(null,arguments)},$u=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_1=function(){return($u=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_1= +b.asm.Js).apply(null,arguments)},av=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_2=function(){return(av=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_2=b.asm.Ks).apply(null,arguments)},bv=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_3=function(){return(bv=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_3=b.asm.Ls).apply(null,arguments)},cv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactAddedCallback_1=function(){return(cv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactAddedCallback_1= +b.asm.Ms).apply(null,arguments)},dv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactProcessedCallback_1=function(){return(dv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactProcessedCallback_1=b.asm.Ns).apply(null,arguments)},ev=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactDestroyedCallback_1=function(){return(ev=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactDestroyedCallback_1=b.asm.Os).apply(null,arguments)},fv=b._emscripten_bind_btSoftRigidDynamicsWorld_addAction_1= +function(){return(fv=b._emscripten_bind_btSoftRigidDynamicsWorld_addAction_1=b.asm.Ps).apply(null,arguments)},gv=b._emscripten_bind_btSoftRigidDynamicsWorld_removeAction_1=function(){return(gv=b._emscripten_bind_btSoftRigidDynamicsWorld_removeAction_1=b.asm.Qs).apply(null,arguments)},hv=b._emscripten_bind_btSoftRigidDynamicsWorld_getSolverInfo_0=function(){return(hv=b._emscripten_bind_btSoftRigidDynamicsWorld_getSolverInfo_0=b.asm.Rs).apply(null,arguments)},iv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_1= +function(){return(iv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_1=b.asm.Ss).apply(null,arguments)},jv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_2=function(){return(jv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_2=b.asm.Ts).apply(null,arguments)},kv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_3=function(){return(kv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_3=b.asm.Us).apply(null, +arguments)},lv=b._emscripten_bind_btSoftRigidDynamicsWorld___destroy___0=function(){return(lv=b._emscripten_bind_btSoftRigidDynamicsWorld___destroy___0=b.asm.Vs).apply(null,arguments)},mv=b._emscripten_bind_btFixedConstraint_btFixedConstraint_4=function(){return(mv=b._emscripten_bind_btFixedConstraint_btFixedConstraint_4=b.asm.Ws).apply(null,arguments)},nv=b._emscripten_bind_btFixedConstraint_enableFeedback_1=function(){return(nv=b._emscripten_bind_btFixedConstraint_enableFeedback_1=b.asm.Xs).apply(null, +arguments)},ov=b._emscripten_bind_btFixedConstraint_getBreakingImpulseThreshold_0=function(){return(ov=b._emscripten_bind_btFixedConstraint_getBreakingImpulseThreshold_0=b.asm.Ys).apply(null,arguments)},pv=b._emscripten_bind_btFixedConstraint_setBreakingImpulseThreshold_1=function(){return(pv=b._emscripten_bind_btFixedConstraint_setBreakingImpulseThreshold_1=b.asm.Zs).apply(null,arguments)},qv=b._emscripten_bind_btFixedConstraint_getParam_2=function(){return(qv=b._emscripten_bind_btFixedConstraint_getParam_2= +b.asm._s).apply(null,arguments)},rv=b._emscripten_bind_btFixedConstraint_setParam_3=function(){return(rv=b._emscripten_bind_btFixedConstraint_setParam_3=b.asm.$s).apply(null,arguments)},sv=b._emscripten_bind_btFixedConstraint___destroy___0=function(){return(sv=b._emscripten_bind_btFixedConstraint___destroy___0=b.asm.at).apply(null,arguments)},tv=b._emscripten_bind_btTransform_btTransform_0=function(){return(tv=b._emscripten_bind_btTransform_btTransform_0=b.asm.bt).apply(null,arguments)},uv=b._emscripten_bind_btTransform_btTransform_2= +function(){return(uv=b._emscripten_bind_btTransform_btTransform_2=b.asm.ct).apply(null,arguments)},vv=b._emscripten_bind_btTransform_setIdentity_0=function(){return(vv=b._emscripten_bind_btTransform_setIdentity_0=b.asm.dt).apply(null,arguments)},wv=b._emscripten_bind_btTransform_setOrigin_1=function(){return(wv=b._emscripten_bind_btTransform_setOrigin_1=b.asm.et).apply(null,arguments)},xv=b._emscripten_bind_btTransform_setRotation_1=function(){return(xv=b._emscripten_bind_btTransform_setRotation_1= +b.asm.ft).apply(null,arguments)},yv=b._emscripten_bind_btTransform_getOrigin_0=function(){return(yv=b._emscripten_bind_btTransform_getOrigin_0=b.asm.gt).apply(null,arguments)},zv=b._emscripten_bind_btTransform_getRotation_0=function(){return(zv=b._emscripten_bind_btTransform_getRotation_0=b.asm.ht).apply(null,arguments)},Av=b._emscripten_bind_btTransform_getBasis_0=function(){return(Av=b._emscripten_bind_btTransform_getBasis_0=b.asm.it).apply(null,arguments)},Bv=b._emscripten_bind_btTransform_setFromOpenGLMatrix_1= +function(){return(Bv=b._emscripten_bind_btTransform_setFromOpenGLMatrix_1=b.asm.jt).apply(null,arguments)},Cv=b._emscripten_bind_btTransform_inverse_0=function(){return(Cv=b._emscripten_bind_btTransform_inverse_0=b.asm.kt).apply(null,arguments)},Dv=b._emscripten_bind_btTransform_op_mul_1=function(){return(Dv=b._emscripten_bind_btTransform_op_mul_1=b.asm.lt).apply(null,arguments)},Ev=b._emscripten_bind_btTransform___destroy___0=function(){return(Ev=b._emscripten_bind_btTransform___destroy___0=b.asm.mt).apply(null, +arguments)},Fv=b._emscripten_bind_ClosestRayResultCallback_ClosestRayResultCallback_2=function(){return(Fv=b._emscripten_bind_ClosestRayResultCallback_ClosestRayResultCallback_2=b.asm.nt).apply(null,arguments)},Gv=b._emscripten_bind_ClosestRayResultCallback_hasHit_0=function(){return(Gv=b._emscripten_bind_ClosestRayResultCallback_hasHit_0=b.asm.ot).apply(null,arguments)},Hv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayFromWorld_0=function(){return(Hv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayFromWorld_0= +b.asm.pt).apply(null,arguments)},Iv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayFromWorld_1=function(){return(Iv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayFromWorld_1=b.asm.qt).apply(null,arguments)},Jv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayToWorld_0=function(){return(Jv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayToWorld_0=b.asm.rt).apply(null,arguments)},Kv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayToWorld_1=function(){return(Kv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayToWorld_1= +b.asm.st).apply(null,arguments)},Lv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitNormalWorld_0=function(){return(Lv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitNormalWorld_0=b.asm.tt).apply(null,arguments)},Mv=b._emscripten_bind_ClosestRayResultCallback_set_m_hitNormalWorld_1=function(){return(Mv=b._emscripten_bind_ClosestRayResultCallback_set_m_hitNormalWorld_1=b.asm.ut).apply(null,arguments)},Nv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitPointWorld_0=function(){return(Nv= +b._emscripten_bind_ClosestRayResultCallback_get_m_hitPointWorld_0=b.asm.vt).apply(null,arguments)},Ov=b._emscripten_bind_ClosestRayResultCallback_set_m_hitPointWorld_1=function(){return(Ov=b._emscripten_bind_ClosestRayResultCallback_set_m_hitPointWorld_1=b.asm.wt).apply(null,arguments)},Pv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterGroup_0=function(){return(Pv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterGroup_0=b.asm.xt).apply(null,arguments)},Qv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterGroup_1= +function(){return(Qv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterGroup_1=b.asm.yt).apply(null,arguments)},Rv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterMask_0=function(){return(Rv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterMask_0=b.asm.zt).apply(null,arguments)},Sv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterMask_1=function(){return(Sv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterMask_1=b.asm.At).apply(null, +arguments)},Tv=b._emscripten_bind_ClosestRayResultCallback_get_m_closestHitFraction_0=function(){return(Tv=b._emscripten_bind_ClosestRayResultCallback_get_m_closestHitFraction_0=b.asm.Bt).apply(null,arguments)},Uv=b._emscripten_bind_ClosestRayResultCallback_set_m_closestHitFraction_1=function(){return(Uv=b._emscripten_bind_ClosestRayResultCallback_set_m_closestHitFraction_1=b.asm.Ct).apply(null,arguments)},Vv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionObject_0=function(){return(Vv= +b._emscripten_bind_ClosestRayResultCallback_get_m_collisionObject_0=b.asm.Dt).apply(null,arguments)},Wv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionObject_1=function(){return(Wv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionObject_1=b.asm.Et).apply(null,arguments)},Xv=b._emscripten_bind_ClosestRayResultCallback___destroy___0=function(){return(Xv=b._emscripten_bind_ClosestRayResultCallback___destroy___0=b.asm.Ft).apply(null,arguments)},Yv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_0= +function(){return(Yv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_0=b.asm.Gt).apply(null,arguments)},Zv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_1=function(){return(Zv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_1=b.asm.Ht).apply(null,arguments)},$v=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration___destroy___0= +function(){return($v=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration___destroy___0=b.asm.It).apply(null,arguments)},aw=b._emscripten_bind_ConcreteContactResultCallback_ConcreteContactResultCallback_0=function(){return(aw=b._emscripten_bind_ConcreteContactResultCallback_ConcreteContactResultCallback_0=b.asm.Jt).apply(null,arguments)},bw=b._emscripten_bind_ConcreteContactResultCallback_addSingleResult_7=function(){return(bw=b._emscripten_bind_ConcreteContactResultCallback_addSingleResult_7= +b.asm.Kt).apply(null,arguments)},cw=b._emscripten_bind_ConcreteContactResultCallback___destroy___0=function(){return(cw=b._emscripten_bind_ConcreteContactResultCallback___destroy___0=b.asm.Lt).apply(null,arguments)},dw=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_2=function(){return(dw=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_2=b.asm.Mt).apply(null,arguments)},ew=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_3=function(){return(ew=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_3= +b.asm.Nt).apply(null,arguments)},fw=b._emscripten_bind_btBvhTriangleMeshShape_setLocalScaling_1=function(){return(fw=b._emscripten_bind_btBvhTriangleMeshShape_setLocalScaling_1=b.asm.Ot).apply(null,arguments)},gw=b._emscripten_bind_btBvhTriangleMeshShape_getLocalScaling_0=function(){return(gw=b._emscripten_bind_btBvhTriangleMeshShape_getLocalScaling_0=b.asm.Pt).apply(null,arguments)},hw=b._emscripten_bind_btBvhTriangleMeshShape_calculateLocalInertia_2=function(){return(hw=b._emscripten_bind_btBvhTriangleMeshShape_calculateLocalInertia_2= +b.asm.Qt).apply(null,arguments)},iw=b._emscripten_bind_btBvhTriangleMeshShape___destroy___0=function(){return(iw=b._emscripten_bind_btBvhTriangleMeshShape___destroy___0=b.asm.Rt).apply(null,arguments)},jw=b._emscripten_bind_btConstCollisionObjectArray_size_0=function(){return(jw=b._emscripten_bind_btConstCollisionObjectArray_size_0=b.asm.St).apply(null,arguments)},kw=b._emscripten_bind_btConstCollisionObjectArray_at_1=function(){return(kw=b._emscripten_bind_btConstCollisionObjectArray_at_1=b.asm.Tt).apply(null, +arguments)},lw=b._emscripten_bind_btConstCollisionObjectArray___destroy___0=function(){return(lw=b._emscripten_bind_btConstCollisionObjectArray___destroy___0=b.asm.Ut).apply(null,arguments)},mw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_3=function(){return(mw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_3=b.asm.Vt).apply(null,arguments)},nw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_5=function(){return(nw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_5= +b.asm.Wt).apply(null,arguments)},ow=b._emscripten_bind_btSliderConstraint_setLowerLinLimit_1=function(){return(ow=b._emscripten_bind_btSliderConstraint_setLowerLinLimit_1=b.asm.Xt).apply(null,arguments)},pw=b._emscripten_bind_btSliderConstraint_setUpperLinLimit_1=function(){return(pw=b._emscripten_bind_btSliderConstraint_setUpperLinLimit_1=b.asm.Yt).apply(null,arguments)},qw=b._emscripten_bind_btSliderConstraint_setLowerAngLimit_1=function(){return(qw=b._emscripten_bind_btSliderConstraint_setLowerAngLimit_1= +b.asm.Zt).apply(null,arguments)},rw=b._emscripten_bind_btSliderConstraint_setUpperAngLimit_1=function(){return(rw=b._emscripten_bind_btSliderConstraint_setUpperAngLimit_1=b.asm._t).apply(null,arguments)},sw=b._emscripten_bind_btSliderConstraint_enableFeedback_1=function(){return(sw=b._emscripten_bind_btSliderConstraint_enableFeedback_1=b.asm.$t).apply(null,arguments)},tw=b._emscripten_bind_btSliderConstraint_getBreakingImpulseThreshold_0=function(){return(tw=b._emscripten_bind_btSliderConstraint_getBreakingImpulseThreshold_0= +b.asm.au).apply(null,arguments)},uw=b._emscripten_bind_btSliderConstraint_setBreakingImpulseThreshold_1=function(){return(uw=b._emscripten_bind_btSliderConstraint_setBreakingImpulseThreshold_1=b.asm.bu).apply(null,arguments)},vw=b._emscripten_bind_btSliderConstraint_getParam_2=function(){return(vw=b._emscripten_bind_btSliderConstraint_getParam_2=b.asm.cu).apply(null,arguments)},ww=b._emscripten_bind_btSliderConstraint_setParam_3=function(){return(ww=b._emscripten_bind_btSliderConstraint_setParam_3= +b.asm.du).apply(null,arguments)},xw=b._emscripten_bind_btSliderConstraint___destroy___0=function(){return(xw=b._emscripten_bind_btSliderConstraint___destroy___0=b.asm.eu).apply(null,arguments)},yw=b._emscripten_bind_btPairCachingGhostObject_btPairCachingGhostObject_0=function(){return(yw=b._emscripten_bind_btPairCachingGhostObject_btPairCachingGhostObject_0=b.asm.fu).apply(null,arguments)},zw=b._emscripten_bind_btPairCachingGhostObject_setAnisotropicFriction_2=function(){return(zw=b._emscripten_bind_btPairCachingGhostObject_setAnisotropicFriction_2= +b.asm.gu).apply(null,arguments)},Aw=b._emscripten_bind_btPairCachingGhostObject_getCollisionShape_0=function(){return(Aw=b._emscripten_bind_btPairCachingGhostObject_getCollisionShape_0=b.asm.hu).apply(null,arguments)},Bw=b._emscripten_bind_btPairCachingGhostObject_setContactProcessingThreshold_1=function(){return(Bw=b._emscripten_bind_btPairCachingGhostObject_setContactProcessingThreshold_1=b.asm.iu).apply(null,arguments)},Cw=b._emscripten_bind_btPairCachingGhostObject_setActivationState_1=function(){return(Cw= +b._emscripten_bind_btPairCachingGhostObject_setActivationState_1=b.asm.ju).apply(null,arguments)},Dw=b._emscripten_bind_btPairCachingGhostObject_forceActivationState_1=function(){return(Dw=b._emscripten_bind_btPairCachingGhostObject_forceActivationState_1=b.asm.ku).apply(null,arguments)},Ew=b._emscripten_bind_btPairCachingGhostObject_activate_0=function(){return(Ew=b._emscripten_bind_btPairCachingGhostObject_activate_0=b.asm.lu).apply(null,arguments)},Fw=b._emscripten_bind_btPairCachingGhostObject_activate_1= +function(){return(Fw=b._emscripten_bind_btPairCachingGhostObject_activate_1=b.asm.mu).apply(null,arguments)},Gw=b._emscripten_bind_btPairCachingGhostObject_isActive_0=function(){return(Gw=b._emscripten_bind_btPairCachingGhostObject_isActive_0=b.asm.nu).apply(null,arguments)},Hw=b._emscripten_bind_btPairCachingGhostObject_isKinematicObject_0=function(){return(Hw=b._emscripten_bind_btPairCachingGhostObject_isKinematicObject_0=b.asm.ou).apply(null,arguments)},Iw=b._emscripten_bind_btPairCachingGhostObject_isStaticObject_0= +function(){return(Iw=b._emscripten_bind_btPairCachingGhostObject_isStaticObject_0=b.asm.pu).apply(null,arguments)},Jw=b._emscripten_bind_btPairCachingGhostObject_isStaticOrKinematicObject_0=function(){return(Jw=b._emscripten_bind_btPairCachingGhostObject_isStaticOrKinematicObject_0=b.asm.qu).apply(null,arguments)},Kw=b._emscripten_bind_btPairCachingGhostObject_getRestitution_0=function(){return(Kw=b._emscripten_bind_btPairCachingGhostObject_getRestitution_0=b.asm.ru).apply(null,arguments)},Lw=b._emscripten_bind_btPairCachingGhostObject_getFriction_0= +function(){return(Lw=b._emscripten_bind_btPairCachingGhostObject_getFriction_0=b.asm.su).apply(null,arguments)},Mw=b._emscripten_bind_btPairCachingGhostObject_getRollingFriction_0=function(){return(Mw=b._emscripten_bind_btPairCachingGhostObject_getRollingFriction_0=b.asm.tu).apply(null,arguments)},Nw=b._emscripten_bind_btPairCachingGhostObject_setRestitution_1=function(){return(Nw=b._emscripten_bind_btPairCachingGhostObject_setRestitution_1=b.asm.uu).apply(null,arguments)},Ow=b._emscripten_bind_btPairCachingGhostObject_setFriction_1= +function(){return(Ow=b._emscripten_bind_btPairCachingGhostObject_setFriction_1=b.asm.vu).apply(null,arguments)},Pw=b._emscripten_bind_btPairCachingGhostObject_setRollingFriction_1=function(){return(Pw=b._emscripten_bind_btPairCachingGhostObject_setRollingFriction_1=b.asm.wu).apply(null,arguments)},Qw=b._emscripten_bind_btPairCachingGhostObject_getWorldTransform_0=function(){return(Qw=b._emscripten_bind_btPairCachingGhostObject_getWorldTransform_0=b.asm.xu).apply(null,arguments)},Rw=b._emscripten_bind_btPairCachingGhostObject_getCollisionFlags_0= +function(){return(Rw=b._emscripten_bind_btPairCachingGhostObject_getCollisionFlags_0=b.asm.yu).apply(null,arguments)},Sw=b._emscripten_bind_btPairCachingGhostObject_setCollisionFlags_1=function(){return(Sw=b._emscripten_bind_btPairCachingGhostObject_setCollisionFlags_1=b.asm.zu).apply(null,arguments)},Tw=b._emscripten_bind_btPairCachingGhostObject_setWorldTransform_1=function(){return(Tw=b._emscripten_bind_btPairCachingGhostObject_setWorldTransform_1=b.asm.Au).apply(null,arguments)},Uw=b._emscripten_bind_btPairCachingGhostObject_setCollisionShape_1= +function(){return(Uw=b._emscripten_bind_btPairCachingGhostObject_setCollisionShape_1=b.asm.Bu).apply(null,arguments)},Vw=b._emscripten_bind_btPairCachingGhostObject_setCcdMotionThreshold_1=function(){return(Vw=b._emscripten_bind_btPairCachingGhostObject_setCcdMotionThreshold_1=b.asm.Cu).apply(null,arguments)},Ww=b._emscripten_bind_btPairCachingGhostObject_setCcdSweptSphereRadius_1=function(){return(Ww=b._emscripten_bind_btPairCachingGhostObject_setCcdSweptSphereRadius_1=b.asm.Du).apply(null,arguments)}, +Xw=b._emscripten_bind_btPairCachingGhostObject_getUserIndex_0=function(){return(Xw=b._emscripten_bind_btPairCachingGhostObject_getUserIndex_0=b.asm.Eu).apply(null,arguments)},Yw=b._emscripten_bind_btPairCachingGhostObject_setUserIndex_1=function(){return(Yw=b._emscripten_bind_btPairCachingGhostObject_setUserIndex_1=b.asm.Fu).apply(null,arguments)},Zw=b._emscripten_bind_btPairCachingGhostObject_getUserPointer_0=function(){return(Zw=b._emscripten_bind_btPairCachingGhostObject_getUserPointer_0=b.asm.Gu).apply(null, +arguments)},$w=b._emscripten_bind_btPairCachingGhostObject_setUserPointer_1=function(){return($w=b._emscripten_bind_btPairCachingGhostObject_setUserPointer_1=b.asm.Hu).apply(null,arguments)},ax=b._emscripten_bind_btPairCachingGhostObject_getBroadphaseHandle_0=function(){return(ax=b._emscripten_bind_btPairCachingGhostObject_getBroadphaseHandle_0=b.asm.Iu).apply(null,arguments)},bx=b._emscripten_bind_btPairCachingGhostObject_getNumOverlappingObjects_0=function(){return(bx=b._emscripten_bind_btPairCachingGhostObject_getNumOverlappingObjects_0= +b.asm.Ju).apply(null,arguments)},cx=b._emscripten_bind_btPairCachingGhostObject_getOverlappingObject_1=function(){return(cx=b._emscripten_bind_btPairCachingGhostObject_getOverlappingObject_1=b.asm.Ku).apply(null,arguments)},dx=b._emscripten_bind_btPairCachingGhostObject___destroy___0=function(){return(dx=b._emscripten_bind_btPairCachingGhostObject___destroy___0=b.asm.Lu).apply(null,arguments)},ex=b._emscripten_bind_btManifoldPoint_getPositionWorldOnA_0=function(){return(ex=b._emscripten_bind_btManifoldPoint_getPositionWorldOnA_0= +b.asm.Mu).apply(null,arguments)},fx=b._emscripten_bind_btManifoldPoint_getPositionWorldOnB_0=function(){return(fx=b._emscripten_bind_btManifoldPoint_getPositionWorldOnB_0=b.asm.Nu).apply(null,arguments)},gx=b._emscripten_bind_btManifoldPoint_getAppliedImpulse_0=function(){return(gx=b._emscripten_bind_btManifoldPoint_getAppliedImpulse_0=b.asm.Ou).apply(null,arguments)},hx=b._emscripten_bind_btManifoldPoint_getDistance_0=function(){return(hx=b._emscripten_bind_btManifoldPoint_getDistance_0=b.asm.Pu).apply(null, +arguments)},ix=b._emscripten_bind_btManifoldPoint_get_m_localPointA_0=function(){return(ix=b._emscripten_bind_btManifoldPoint_get_m_localPointA_0=b.asm.Qu).apply(null,arguments)},jx=b._emscripten_bind_btManifoldPoint_set_m_localPointA_1=function(){return(jx=b._emscripten_bind_btManifoldPoint_set_m_localPointA_1=b.asm.Ru).apply(null,arguments)},kx=b._emscripten_bind_btManifoldPoint_get_m_localPointB_0=function(){return(kx=b._emscripten_bind_btManifoldPoint_get_m_localPointB_0=b.asm.Su).apply(null, +arguments)},lx=b._emscripten_bind_btManifoldPoint_set_m_localPointB_1=function(){return(lx=b._emscripten_bind_btManifoldPoint_set_m_localPointB_1=b.asm.Tu).apply(null,arguments)},mx=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnB_0=function(){return(mx=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnB_0=b.asm.Uu).apply(null,arguments)},nx=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnB_1=function(){return(nx=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnB_1=b.asm.Vu).apply(null, +arguments)},ox=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnA_0=function(){return(ox=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnA_0=b.asm.Wu).apply(null,arguments)},px=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnA_1=function(){return(px=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnA_1=b.asm.Xu).apply(null,arguments)},qx=b._emscripten_bind_btManifoldPoint_get_m_normalWorldOnB_0=function(){return(qx=b._emscripten_bind_btManifoldPoint_get_m_normalWorldOnB_0= +b.asm.Yu).apply(null,arguments)},rx=b._emscripten_bind_btManifoldPoint_set_m_normalWorldOnB_1=function(){return(rx=b._emscripten_bind_btManifoldPoint_set_m_normalWorldOnB_1=b.asm.Zu).apply(null,arguments)},sx=b._emscripten_bind_btManifoldPoint_get_m_userPersistentData_0=function(){return(sx=b._emscripten_bind_btManifoldPoint_get_m_userPersistentData_0=b.asm._u).apply(null,arguments)},tx=b._emscripten_bind_btManifoldPoint_set_m_userPersistentData_1=function(){return(tx=b._emscripten_bind_btManifoldPoint_set_m_userPersistentData_1= +b.asm.$u).apply(null,arguments)},ux=b._emscripten_bind_btManifoldPoint___destroy___0=function(){return(ux=b._emscripten_bind_btManifoldPoint___destroy___0=b.asm.av).apply(null,arguments)},vx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_2=function(){return(vx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_2=b.asm.bv).apply(null,arguments)},wx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_4=function(){return(wx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_4= +b.asm.cv).apply(null,arguments)},xx=b._emscripten_bind_btPoint2PointConstraint_setPivotA_1=function(){return(xx=b._emscripten_bind_btPoint2PointConstraint_setPivotA_1=b.asm.dv).apply(null,arguments)},yx=b._emscripten_bind_btPoint2PointConstraint_setPivotB_1=function(){return(yx=b._emscripten_bind_btPoint2PointConstraint_setPivotB_1=b.asm.ev).apply(null,arguments)},zx=b._emscripten_bind_btPoint2PointConstraint_getPivotInA_0=function(){return(zx=b._emscripten_bind_btPoint2PointConstraint_getPivotInA_0= +b.asm.fv).apply(null,arguments)},Ax=b._emscripten_bind_btPoint2PointConstraint_getPivotInB_0=function(){return(Ax=b._emscripten_bind_btPoint2PointConstraint_getPivotInB_0=b.asm.gv).apply(null,arguments)},Bx=b._emscripten_bind_btPoint2PointConstraint_enableFeedback_1=function(){return(Bx=b._emscripten_bind_btPoint2PointConstraint_enableFeedback_1=b.asm.hv).apply(null,arguments)},Cx=b._emscripten_bind_btPoint2PointConstraint_getBreakingImpulseThreshold_0=function(){return(Cx=b._emscripten_bind_btPoint2PointConstraint_getBreakingImpulseThreshold_0= +b.asm.iv).apply(null,arguments)},Dx=b._emscripten_bind_btPoint2PointConstraint_setBreakingImpulseThreshold_1=function(){return(Dx=b._emscripten_bind_btPoint2PointConstraint_setBreakingImpulseThreshold_1=b.asm.jv).apply(null,arguments)},Ex=b._emscripten_bind_btPoint2PointConstraint_getParam_2=function(){return(Ex=b._emscripten_bind_btPoint2PointConstraint_getParam_2=b.asm.kv).apply(null,arguments)},Fx=b._emscripten_bind_btPoint2PointConstraint_setParam_3=function(){return(Fx=b._emscripten_bind_btPoint2PointConstraint_setParam_3= +b.asm.lv).apply(null,arguments)},Gx=b._emscripten_bind_btPoint2PointConstraint_get_m_setting_0=function(){return(Gx=b._emscripten_bind_btPoint2PointConstraint_get_m_setting_0=b.asm.mv).apply(null,arguments)},Hx=b._emscripten_bind_btPoint2PointConstraint_set_m_setting_1=function(){return(Hx=b._emscripten_bind_btPoint2PointConstraint_set_m_setting_1=b.asm.nv).apply(null,arguments)},Ix=b._emscripten_bind_btPoint2PointConstraint___destroy___0=function(){return(Ix=b._emscripten_bind_btPoint2PointConstraint___destroy___0= +b.asm.ov).apply(null,arguments)},Jx=b._emscripten_bind_btSoftBodyHelpers_btSoftBodyHelpers_0=function(){return(Jx=b._emscripten_bind_btSoftBodyHelpers_btSoftBodyHelpers_0=b.asm.pv).apply(null,arguments)},Kx=b._emscripten_bind_btSoftBodyHelpers_CreateRope_5=function(){return(Kx=b._emscripten_bind_btSoftBodyHelpers_CreateRope_5=b.asm.qv).apply(null,arguments)},Lx=b._emscripten_bind_btSoftBodyHelpers_CreatePatch_9=function(){return(Lx=b._emscripten_bind_btSoftBodyHelpers_CreatePatch_9=b.asm.rv).apply(null, +arguments)},Mx=b._emscripten_bind_btSoftBodyHelpers_CreatePatchUV_10=function(){return(Mx=b._emscripten_bind_btSoftBodyHelpers_CreatePatchUV_10=b.asm.sv).apply(null,arguments)},Nx=b._emscripten_bind_btSoftBodyHelpers_CreateEllipsoid_4=function(){return(Nx=b._emscripten_bind_btSoftBodyHelpers_CreateEllipsoid_4=b.asm.tv).apply(null,arguments)},Ox=b._emscripten_bind_btSoftBodyHelpers_CreateFromTriMesh_5=function(){return(Ox=b._emscripten_bind_btSoftBodyHelpers_CreateFromTriMesh_5=b.asm.uv).apply(null, +arguments)},Px=b._emscripten_bind_btSoftBodyHelpers_CreateFromConvexHull_4=function(){return(Px=b._emscripten_bind_btSoftBodyHelpers_CreateFromConvexHull_4=b.asm.vv).apply(null,arguments)},Qx=b._emscripten_bind_btSoftBodyHelpers___destroy___0=function(){return(Qx=b._emscripten_bind_btSoftBodyHelpers___destroy___0=b.asm.wv).apply(null,arguments)},Rx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterGroup_0=function(){return(Rx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterGroup_0= +b.asm.xv).apply(null,arguments)},Sx=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterGroup_1=function(){return(Sx=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterGroup_1=b.asm.yv).apply(null,arguments)},Tx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterMask_0=function(){return(Tx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterMask_0=b.asm.zv).apply(null,arguments)},Ux=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterMask_1=function(){return(Ux=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterMask_1= +b.asm.Av).apply(null,arguments)},Vx=b._emscripten_bind_btBroadphaseProxy___destroy___0=function(){return(Vx=b._emscripten_bind_btBroadphaseProxy___destroy___0=b.asm.Bv).apply(null,arguments)},Wx=b._emscripten_bind_tNodeArray_size_0=function(){return(Wx=b._emscripten_bind_tNodeArray_size_0=b.asm.Cv).apply(null,arguments)},Xx=b._emscripten_bind_tNodeArray_at_1=function(){return(Xx=b._emscripten_bind_tNodeArray_at_1=b.asm.Dv).apply(null,arguments)},Yx=b._emscripten_bind_tNodeArray___destroy___0=function(){return(Yx= +b._emscripten_bind_tNodeArray___destroy___0=b.asm.Ev).apply(null,arguments)},Zx=b._emscripten_bind_btBoxShape_btBoxShape_1=function(){return(Zx=b._emscripten_bind_btBoxShape_btBoxShape_1=b.asm.Fv).apply(null,arguments)},$x=b._emscripten_bind_btBoxShape_setMargin_1=function(){return($x=b._emscripten_bind_btBoxShape_setMargin_1=b.asm.Gv).apply(null,arguments)},ay=b._emscripten_bind_btBoxShape_getMargin_0=function(){return(ay=b._emscripten_bind_btBoxShape_getMargin_0=b.asm.Hv).apply(null,arguments)}, +by=b._emscripten_bind_btBoxShape_setLocalScaling_1=function(){return(by=b._emscripten_bind_btBoxShape_setLocalScaling_1=b.asm.Iv).apply(null,arguments)},cy=b._emscripten_bind_btBoxShape_getLocalScaling_0=function(){return(cy=b._emscripten_bind_btBoxShape_getLocalScaling_0=b.asm.Jv).apply(null,arguments)},dy=b._emscripten_bind_btBoxShape_calculateLocalInertia_2=function(){return(dy=b._emscripten_bind_btBoxShape_calculateLocalInertia_2=b.asm.Kv).apply(null,arguments)},ey=b._emscripten_bind_btBoxShape___destroy___0= +function(){return(ey=b._emscripten_bind_btBoxShape___destroy___0=b.asm.Lv).apply(null,arguments)},fy=b._emscripten_bind_btFace_get_m_indices_0=function(){return(fy=b._emscripten_bind_btFace_get_m_indices_0=b.asm.Mv).apply(null,arguments)},gy=b._emscripten_bind_btFace_set_m_indices_1=function(){return(gy=b._emscripten_bind_btFace_set_m_indices_1=b.asm.Nv).apply(null,arguments)},hy=b._emscripten_bind_btFace_get_m_plane_1=function(){return(hy=b._emscripten_bind_btFace_get_m_plane_1=b.asm.Ov).apply(null, +arguments)},iy=b._emscripten_bind_btFace_set_m_plane_2=function(){return(iy=b._emscripten_bind_btFace_set_m_plane_2=b.asm.Pv).apply(null,arguments)},jy=b._emscripten_bind_btFace___destroy___0=function(){return(jy=b._emscripten_bind_btFace___destroy___0=b.asm.Qv).apply(null,arguments)},ky=b._emscripten_bind_DebugDrawer_DebugDrawer_0=function(){return(ky=b._emscripten_bind_DebugDrawer_DebugDrawer_0=b.asm.Rv).apply(null,arguments)},ly=b._emscripten_bind_DebugDrawer_drawLine_3=function(){return(ly=b._emscripten_bind_DebugDrawer_drawLine_3= +b.asm.Sv).apply(null,arguments)},my=b._emscripten_bind_DebugDrawer_drawContactPoint_5=function(){return(my=b._emscripten_bind_DebugDrawer_drawContactPoint_5=b.asm.Tv).apply(null,arguments)},ny=b._emscripten_bind_DebugDrawer_reportErrorWarning_1=function(){return(ny=b._emscripten_bind_DebugDrawer_reportErrorWarning_1=b.asm.Uv).apply(null,arguments)},oy=b._emscripten_bind_DebugDrawer_draw3dText_2=function(){return(oy=b._emscripten_bind_DebugDrawer_draw3dText_2=b.asm.Vv).apply(null,arguments)},py=b._emscripten_bind_DebugDrawer_setDebugMode_1= +function(){return(py=b._emscripten_bind_DebugDrawer_setDebugMode_1=b.asm.Wv).apply(null,arguments)},qy=b._emscripten_bind_DebugDrawer_getDebugMode_0=function(){return(qy=b._emscripten_bind_DebugDrawer_getDebugMode_0=b.asm.Xv).apply(null,arguments)},ry=b._emscripten_bind_DebugDrawer___destroy___0=function(){return(ry=b._emscripten_bind_DebugDrawer___destroy___0=b.asm.Yv).apply(null,arguments)},sy=b._emscripten_bind_btCapsuleShapeX_btCapsuleShapeX_2=function(){return(sy=b._emscripten_bind_btCapsuleShapeX_btCapsuleShapeX_2= +b.asm.Zv).apply(null,arguments)},ty=b._emscripten_bind_btCapsuleShapeX_setMargin_1=function(){return(ty=b._emscripten_bind_btCapsuleShapeX_setMargin_1=b.asm._v).apply(null,arguments)},uy=b._emscripten_bind_btCapsuleShapeX_getMargin_0=function(){return(uy=b._emscripten_bind_btCapsuleShapeX_getMargin_0=b.asm.$v).apply(null,arguments)},vy=b._emscripten_bind_btCapsuleShapeX_getUpAxis_0=function(){return(vy=b._emscripten_bind_btCapsuleShapeX_getUpAxis_0=b.asm.aw).apply(null,arguments)},wy=b._emscripten_bind_btCapsuleShapeX_getRadius_0= +function(){return(wy=b._emscripten_bind_btCapsuleShapeX_getRadius_0=b.asm.bw).apply(null,arguments)},xy=b._emscripten_bind_btCapsuleShapeX_getHalfHeight_0=function(){return(xy=b._emscripten_bind_btCapsuleShapeX_getHalfHeight_0=b.asm.cw).apply(null,arguments)},yy=b._emscripten_bind_btCapsuleShapeX_setLocalScaling_1=function(){return(yy=b._emscripten_bind_btCapsuleShapeX_setLocalScaling_1=b.asm.dw).apply(null,arguments)},zy=b._emscripten_bind_btCapsuleShapeX_getLocalScaling_0=function(){return(zy=b._emscripten_bind_btCapsuleShapeX_getLocalScaling_0= +b.asm.ew).apply(null,arguments)},Ay=b._emscripten_bind_btCapsuleShapeX_calculateLocalInertia_2=function(){return(Ay=b._emscripten_bind_btCapsuleShapeX_calculateLocalInertia_2=b.asm.fw).apply(null,arguments)},By=b._emscripten_bind_btCapsuleShapeX___destroy___0=function(){return(By=b._emscripten_bind_btCapsuleShapeX___destroy___0=b.asm.gw).apply(null,arguments)},Cy=b._emscripten_bind_btQuaternion_btQuaternion_4=function(){return(Cy=b._emscripten_bind_btQuaternion_btQuaternion_4=b.asm.hw).apply(null, +arguments)},Dy=b._emscripten_bind_btQuaternion_setValue_4=function(){return(Dy=b._emscripten_bind_btQuaternion_setValue_4=b.asm.iw).apply(null,arguments)},Ey=b._emscripten_bind_btQuaternion_setEulerZYX_3=function(){return(Ey=b._emscripten_bind_btQuaternion_setEulerZYX_3=b.asm.jw).apply(null,arguments)},Fy=b._emscripten_bind_btQuaternion_setRotation_2=function(){return(Fy=b._emscripten_bind_btQuaternion_setRotation_2=b.asm.kw).apply(null,arguments)},Gy=b._emscripten_bind_btQuaternion_normalize_0=function(){return(Gy= +b._emscripten_bind_btQuaternion_normalize_0=b.asm.lw).apply(null,arguments)},Hy=b._emscripten_bind_btQuaternion_length2_0=function(){return(Hy=b._emscripten_bind_btQuaternion_length2_0=b.asm.mw).apply(null,arguments)},Iy=b._emscripten_bind_btQuaternion_length_0=function(){return(Iy=b._emscripten_bind_btQuaternion_length_0=b.asm.nw).apply(null,arguments)},Jy=b._emscripten_bind_btQuaternion_dot_1=function(){return(Jy=b._emscripten_bind_btQuaternion_dot_1=b.asm.ow).apply(null,arguments)},Ky=b._emscripten_bind_btQuaternion_normalized_0= +function(){return(Ky=b._emscripten_bind_btQuaternion_normalized_0=b.asm.pw).apply(null,arguments)},Ly=b._emscripten_bind_btQuaternion_getAxis_0=function(){return(Ly=b._emscripten_bind_btQuaternion_getAxis_0=b.asm.qw).apply(null,arguments)},My=b._emscripten_bind_btQuaternion_inverse_0=function(){return(My=b._emscripten_bind_btQuaternion_inverse_0=b.asm.rw).apply(null,arguments)},Ny=b._emscripten_bind_btQuaternion_getAngle_0=function(){return(Ny=b._emscripten_bind_btQuaternion_getAngle_0=b.asm.sw).apply(null, +arguments)},Oy=b._emscripten_bind_btQuaternion_getAngleShortestPath_0=function(){return(Oy=b._emscripten_bind_btQuaternion_getAngleShortestPath_0=b.asm.tw).apply(null,arguments)},Py=b._emscripten_bind_btQuaternion_angle_1=function(){return(Py=b._emscripten_bind_btQuaternion_angle_1=b.asm.uw).apply(null,arguments)},Qy=b._emscripten_bind_btQuaternion_angleShortestPath_1=function(){return(Qy=b._emscripten_bind_btQuaternion_angleShortestPath_1=b.asm.vw).apply(null,arguments)},Ry=b._emscripten_bind_btQuaternion_op_add_1= +function(){return(Ry=b._emscripten_bind_btQuaternion_op_add_1=b.asm.ww).apply(null,arguments)},Sy=b._emscripten_bind_btQuaternion_op_sub_1=function(){return(Sy=b._emscripten_bind_btQuaternion_op_sub_1=b.asm.xw).apply(null,arguments)},Ty=b._emscripten_bind_btQuaternion_op_mul_1=function(){return(Ty=b._emscripten_bind_btQuaternion_op_mul_1=b.asm.yw).apply(null,arguments)},Uy=b._emscripten_bind_btQuaternion_op_mulq_1=function(){return(Uy=b._emscripten_bind_btQuaternion_op_mulq_1=b.asm.zw).apply(null, +arguments)},Vy=b._emscripten_bind_btQuaternion_op_div_1=function(){return(Vy=b._emscripten_bind_btQuaternion_op_div_1=b.asm.Aw).apply(null,arguments)},Wy=b._emscripten_bind_btQuaternion_x_0=function(){return(Wy=b._emscripten_bind_btQuaternion_x_0=b.asm.Bw).apply(null,arguments)},Xy=b._emscripten_bind_btQuaternion_y_0=function(){return(Xy=b._emscripten_bind_btQuaternion_y_0=b.asm.Cw).apply(null,arguments)},Yy=b._emscripten_bind_btQuaternion_z_0=function(){return(Yy=b._emscripten_bind_btQuaternion_z_0= +b.asm.Dw).apply(null,arguments)},Zy=b._emscripten_bind_btQuaternion_w_0=function(){return(Zy=b._emscripten_bind_btQuaternion_w_0=b.asm.Ew).apply(null,arguments)},$y=b._emscripten_bind_btQuaternion_setX_1=function(){return($y=b._emscripten_bind_btQuaternion_setX_1=b.asm.Fw).apply(null,arguments)},az=b._emscripten_bind_btQuaternion_setY_1=function(){return(az=b._emscripten_bind_btQuaternion_setY_1=b.asm.Gw).apply(null,arguments)},bz=b._emscripten_bind_btQuaternion_setZ_1=function(){return(bz=b._emscripten_bind_btQuaternion_setZ_1= +b.asm.Hw).apply(null,arguments)},cz=b._emscripten_bind_btQuaternion_setW_1=function(){return(cz=b._emscripten_bind_btQuaternion_setW_1=b.asm.Iw).apply(null,arguments)},dz=b._emscripten_bind_btQuaternion___destroy___0=function(){return(dz=b._emscripten_bind_btQuaternion___destroy___0=b.asm.Jw).apply(null,arguments)},ez=b._emscripten_bind_btCapsuleShapeZ_btCapsuleShapeZ_2=function(){return(ez=b._emscripten_bind_btCapsuleShapeZ_btCapsuleShapeZ_2=b.asm.Kw).apply(null,arguments)},fz=b._emscripten_bind_btCapsuleShapeZ_setMargin_1= +function(){return(fz=b._emscripten_bind_btCapsuleShapeZ_setMargin_1=b.asm.Lw).apply(null,arguments)},gz=b._emscripten_bind_btCapsuleShapeZ_getMargin_0=function(){return(gz=b._emscripten_bind_btCapsuleShapeZ_getMargin_0=b.asm.Mw).apply(null,arguments)},hz=b._emscripten_bind_btCapsuleShapeZ_getUpAxis_0=function(){return(hz=b._emscripten_bind_btCapsuleShapeZ_getUpAxis_0=b.asm.Nw).apply(null,arguments)},iz=b._emscripten_bind_btCapsuleShapeZ_getRadius_0=function(){return(iz=b._emscripten_bind_btCapsuleShapeZ_getRadius_0= +b.asm.Ow).apply(null,arguments)},jz=b._emscripten_bind_btCapsuleShapeZ_getHalfHeight_0=function(){return(jz=b._emscripten_bind_btCapsuleShapeZ_getHalfHeight_0=b.asm.Pw).apply(null,arguments)},kz=b._emscripten_bind_btCapsuleShapeZ_setLocalScaling_1=function(){return(kz=b._emscripten_bind_btCapsuleShapeZ_setLocalScaling_1=b.asm.Qw).apply(null,arguments)},lz=b._emscripten_bind_btCapsuleShapeZ_getLocalScaling_0=function(){return(lz=b._emscripten_bind_btCapsuleShapeZ_getLocalScaling_0=b.asm.Rw).apply(null, +arguments)},mz=b._emscripten_bind_btCapsuleShapeZ_calculateLocalInertia_2=function(){return(mz=b._emscripten_bind_btCapsuleShapeZ_calculateLocalInertia_2=b.asm.Sw).apply(null,arguments)},nz=b._emscripten_bind_btCapsuleShapeZ___destroy___0=function(){return(nz=b._emscripten_bind_btCapsuleShapeZ___destroy___0=b.asm.Tw).apply(null,arguments)},oz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulse_0=function(){return(oz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulse_0=b.asm.Uw).apply(null, +arguments)},pz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulse_1=function(){return(pz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulse_1=b.asm.Vw).apply(null,arguments)},qz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulsePenetrationThreshold_0=function(){return(qz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulsePenetrationThreshold_0=b.asm.Ww).apply(null,arguments)},rz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulsePenetrationThreshold_1=function(){return(rz= +b._emscripten_bind_btContactSolverInfo_set_m_splitImpulsePenetrationThreshold_1=b.asm.Xw).apply(null,arguments)},sz=b._emscripten_bind_btContactSolverInfo_get_m_numIterations_0=function(){return(sz=b._emscripten_bind_btContactSolverInfo_get_m_numIterations_0=b.asm.Yw).apply(null,arguments)},tz=b._emscripten_bind_btContactSolverInfo_set_m_numIterations_1=function(){return(tz=b._emscripten_bind_btContactSolverInfo_set_m_numIterations_1=b.asm.Zw).apply(null,arguments)},uz=b._emscripten_bind_btContactSolverInfo___destroy___0= +function(){return(uz=b._emscripten_bind_btContactSolverInfo___destroy___0=b.asm._w).apply(null,arguments)},vz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_3=function(){return(vz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_3=b.asm.$w).apply(null,arguments)},wz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_5=function(){return(wz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_5= +b.asm.ax).apply(null,arguments)},xz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableSpring_2=function(){return(xz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableSpring_2=b.asm.bx).apply(null,arguments)},yz=b._emscripten_bind_btGeneric6DofSpringConstraint_setStiffness_2=function(){return(yz=b._emscripten_bind_btGeneric6DofSpringConstraint_setStiffness_2=b.asm.cx).apply(null,arguments)},zz=b._emscripten_bind_btGeneric6DofSpringConstraint_setDamping_2=function(){return(zz=b._emscripten_bind_btGeneric6DofSpringConstraint_setDamping_2= +b.asm.dx).apply(null,arguments)},Az=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_0=function(){return(Az=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_0=b.asm.ex).apply(null,arguments)},Bz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_1=function(){return(Bz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_1=b.asm.fx).apply(null,arguments)},Cz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_2= +function(){return(Cz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_2=b.asm.gx).apply(null,arguments)},Dz=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearLowerLimit_1=function(){return(Dz=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearLowerLimit_1=b.asm.hx).apply(null,arguments)},Ez=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearUpperLimit_1=function(){return(Ez=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearUpperLimit_1=b.asm.ix).apply(null, +arguments)},Fz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularLowerLimit_1=function(){return(Fz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularLowerLimit_1=b.asm.jx).apply(null,arguments)},Gz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularUpperLimit_1=function(){return(Gz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularUpperLimit_1=b.asm.kx).apply(null,arguments)},Hz=b._emscripten_bind_btGeneric6DofSpringConstraint_getFrameOffsetA_0=function(){return(Hz= +b._emscripten_bind_btGeneric6DofSpringConstraint_getFrameOffsetA_0=b.asm.lx).apply(null,arguments)},Iz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableFeedback_1=function(){return(Iz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableFeedback_1=b.asm.mx).apply(null,arguments)},Jz=b._emscripten_bind_btGeneric6DofSpringConstraint_getBreakingImpulseThreshold_0=function(){return(Jz=b._emscripten_bind_btGeneric6DofSpringConstraint_getBreakingImpulseThreshold_0=b.asm.nx).apply(null,arguments)}, +Kz=b._emscripten_bind_btGeneric6DofSpringConstraint_setBreakingImpulseThreshold_1=function(){return(Kz=b._emscripten_bind_btGeneric6DofSpringConstraint_setBreakingImpulseThreshold_1=b.asm.ox).apply(null,arguments)},Lz=b._emscripten_bind_btGeneric6DofSpringConstraint_getParam_2=function(){return(Lz=b._emscripten_bind_btGeneric6DofSpringConstraint_getParam_2=b.asm.px).apply(null,arguments)},Mz=b._emscripten_bind_btGeneric6DofSpringConstraint_setParam_3=function(){return(Mz=b._emscripten_bind_btGeneric6DofSpringConstraint_setParam_3= +b.asm.qx).apply(null,arguments)},Nz=b._emscripten_bind_btGeneric6DofSpringConstraint___destroy___0=function(){return(Nz=b._emscripten_bind_btGeneric6DofSpringConstraint___destroy___0=b.asm.rx).apply(null,arguments)},Oz=b._emscripten_bind_btSphereShape_btSphereShape_1=function(){return(Oz=b._emscripten_bind_btSphereShape_btSphereShape_1=b.asm.sx).apply(null,arguments)},Pz=b._emscripten_bind_btSphereShape_setMargin_1=function(){return(Pz=b._emscripten_bind_btSphereShape_setMargin_1=b.asm.tx).apply(null, +arguments)},Qz=b._emscripten_bind_btSphereShape_getMargin_0=function(){return(Qz=b._emscripten_bind_btSphereShape_getMargin_0=b.asm.ux).apply(null,arguments)},Rz=b._emscripten_bind_btSphereShape_setLocalScaling_1=function(){return(Rz=b._emscripten_bind_btSphereShape_setLocalScaling_1=b.asm.vx).apply(null,arguments)},Sz=b._emscripten_bind_btSphereShape_getLocalScaling_0=function(){return(Sz=b._emscripten_bind_btSphereShape_getLocalScaling_0=b.asm.wx).apply(null,arguments)},Tz=b._emscripten_bind_btSphereShape_calculateLocalInertia_2= +function(){return(Tz=b._emscripten_bind_btSphereShape_calculateLocalInertia_2=b.asm.xx).apply(null,arguments)},Uz=b._emscripten_bind_btSphereShape___destroy___0=function(){return(Uz=b._emscripten_bind_btSphereShape___destroy___0=b.asm.yx).apply(null,arguments)},Vz=b._emscripten_bind_Face_get_m_n_1=function(){return(Vz=b._emscripten_bind_Face_get_m_n_1=b.asm.zx).apply(null,arguments)},Wz=b._emscripten_bind_Face_set_m_n_2=function(){return(Wz=b._emscripten_bind_Face_set_m_n_2=b.asm.Ax).apply(null,arguments)}, +Xz=b._emscripten_bind_Face_get_m_normal_0=function(){return(Xz=b._emscripten_bind_Face_get_m_normal_0=b.asm.Bx).apply(null,arguments)},Yz=b._emscripten_bind_Face_set_m_normal_1=function(){return(Yz=b._emscripten_bind_Face_set_m_normal_1=b.asm.Cx).apply(null,arguments)},Zz=b._emscripten_bind_Face_get_m_ra_0=function(){return(Zz=b._emscripten_bind_Face_get_m_ra_0=b.asm.Dx).apply(null,arguments)},$z=b._emscripten_bind_Face_set_m_ra_1=function(){return($z=b._emscripten_bind_Face_set_m_ra_1=b.asm.Ex).apply(null, +arguments)},aA=b._emscripten_bind_Face___destroy___0=function(){return(aA=b._emscripten_bind_Face___destroy___0=b.asm.Fx).apply(null,arguments)},bA=b._emscripten_bind_tFaceArray_size_0=function(){return(bA=b._emscripten_bind_tFaceArray_size_0=b.asm.Gx).apply(null,arguments)},cA=b._emscripten_bind_tFaceArray_at_1=function(){return(cA=b._emscripten_bind_tFaceArray_at_1=b.asm.Hx).apply(null,arguments)},dA=b._emscripten_bind_tFaceArray___destroy___0=function(){return(dA=b._emscripten_bind_tFaceArray___destroy___0= +b.asm.Ix).apply(null,arguments)},eA=b._emscripten_bind_LocalConvexResult_LocalConvexResult_5=function(){return(eA=b._emscripten_bind_LocalConvexResult_LocalConvexResult_5=b.asm.Jx).apply(null,arguments)},fA=b._emscripten_bind_LocalConvexResult_get_m_hitCollisionObject_0=function(){return(fA=b._emscripten_bind_LocalConvexResult_get_m_hitCollisionObject_0=b.asm.Kx).apply(null,arguments)},gA=b._emscripten_bind_LocalConvexResult_set_m_hitCollisionObject_1=function(){return(gA=b._emscripten_bind_LocalConvexResult_set_m_hitCollisionObject_1= +b.asm.Lx).apply(null,arguments)},hA=b._emscripten_bind_LocalConvexResult_get_m_localShapeInfo_0=function(){return(hA=b._emscripten_bind_LocalConvexResult_get_m_localShapeInfo_0=b.asm.Mx).apply(null,arguments)},iA=b._emscripten_bind_LocalConvexResult_set_m_localShapeInfo_1=function(){return(iA=b._emscripten_bind_LocalConvexResult_set_m_localShapeInfo_1=b.asm.Nx).apply(null,arguments)},jA=b._emscripten_bind_LocalConvexResult_get_m_hitNormalLocal_0=function(){return(jA=b._emscripten_bind_LocalConvexResult_get_m_hitNormalLocal_0= +b.asm.Ox).apply(null,arguments)},kA=b._emscripten_bind_LocalConvexResult_set_m_hitNormalLocal_1=function(){return(kA=b._emscripten_bind_LocalConvexResult_set_m_hitNormalLocal_1=b.asm.Px).apply(null,arguments)},lA=b._emscripten_bind_LocalConvexResult_get_m_hitPointLocal_0=function(){return(lA=b._emscripten_bind_LocalConvexResult_get_m_hitPointLocal_0=b.asm.Qx).apply(null,arguments)},mA=b._emscripten_bind_LocalConvexResult_set_m_hitPointLocal_1=function(){return(mA=b._emscripten_bind_LocalConvexResult_set_m_hitPointLocal_1= +b.asm.Rx).apply(null,arguments)},nA=b._emscripten_bind_LocalConvexResult_get_m_hitFraction_0=function(){return(nA=b._emscripten_bind_LocalConvexResult_get_m_hitFraction_0=b.asm.Sx).apply(null,arguments)},oA=b._emscripten_bind_LocalConvexResult_set_m_hitFraction_1=function(){return(oA=b._emscripten_bind_LocalConvexResult_set_m_hitFraction_1=b.asm.Tx).apply(null,arguments)},pA=b._emscripten_bind_LocalConvexResult___destroy___0=function(){return(pA=b._emscripten_bind_LocalConvexResult___destroy___0= +b.asm.Ux).apply(null,arguments)},qA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_ERP=function(){return(qA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_ERP=b.asm.Vx).apply(null,arguments)},rA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_ERP=function(){return(rA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_ERP=b.asm.Wx).apply(null,arguments)},sA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_CFM=function(){return(sA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_CFM= +b.asm.Xx).apply(null,arguments)},tA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_CFM=function(){return(tA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_CFM=b.asm.Yx).apply(null,arguments)},uA=b._emscripten_enum_PHY_ScalarType_PHY_FLOAT=function(){return(uA=b._emscripten_enum_PHY_ScalarType_PHY_FLOAT=b.asm.Zx).apply(null,arguments)},vA=b._emscripten_enum_PHY_ScalarType_PHY_DOUBLE=function(){return(vA=b._emscripten_enum_PHY_ScalarType_PHY_DOUBLE=b.asm._x).apply(null,arguments)}, +wA=b._emscripten_enum_PHY_ScalarType_PHY_INTEGER=function(){return(wA=b._emscripten_enum_PHY_ScalarType_PHY_INTEGER=b.asm.$x).apply(null,arguments)},xA=b._emscripten_enum_PHY_ScalarType_PHY_SHORT=function(){return(xA=b._emscripten_enum_PHY_ScalarType_PHY_SHORT=b.asm.ay).apply(null,arguments)},yA=b._emscripten_enum_PHY_ScalarType_PHY_FIXEDPOINT88=function(){return(yA=b._emscripten_enum_PHY_ScalarType_PHY_FIXEDPOINT88=b.asm.by).apply(null,arguments)},zA=b._emscripten_enum_PHY_ScalarType_PHY_UCHAR=function(){return(zA= +b._emscripten_enum_PHY_ScalarType_PHY_UCHAR=b.asm.cy).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.dy).apply(null,arguments)};b._free=function(){return(b._free=b.asm.ey).apply(null,arguments)};b.dynCall_vi=function(){return(b.dynCall_vi=b.asm.fy).apply(null,arguments)};b.dynCall_v=function(){return(b.dynCall_v=b.asm.gy).apply(null,arguments)}; +b.UTF8ToString=function(a,c){if(a){var d=a+c;for(c=a;za[c]&&!(c>=d);)++c;if(16e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}a=d}}else a="";return a};var AA; +Oa=function BA(){AA||CA();AA||(Oa=BA)}; +function CA(){function a(){if(!AA&&(AA=!0,b.calledRun=!0,!va)){Ka=!0;Fa(Ha);Fa(Ia);ba(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();Ja.unshift(c)}Fa(Ja)}}if(!(0=EA?(assert(0>>=0;switch(c.BYTES_PER_ELEMENT){case 2:d>>>=1;break;case 4:d>>>=2;break;case 8:d>>>=3}for(var e=0;e=e&&(e=65536+((e&1023)<<10)|a.charCodeAt(++d)&1023);127>=e?++c:c=2047>=e?c+2:65535>=e?c+3:c+4}c=Array(c+1);e=c.length;d=0;if(0=n){var F=a.charCodeAt(++g);n=65536+((n&1023)<<10)|F&1023}if(127>=n){if(d>=e)break;c[d++]=n}else{if(2047>=n){if(d+1>=e)break;c[d++]=192|n>>6}else{if(65535>=n){if(d+2>=e)break;c[d++]=224| +n>>12}else{if(d+3>=e)break;c[d++]=240|n>>18;c[d++]=128|n>>12&63}c[d++]=128|n>>6&63}c[d++]=128|n&63}}c[d]=0}a=JA(c,ya);KA(c,ya,a)}return a}function MA(a){if("object"===typeof a){var c=JA(a,Ba);KA(a,Ba,c);return c}return a}function NA(){throw"cannot construct a btCollisionWorld, no constructor in IDL";}NA.prototype=Object.create(f.prototype);NA.prototype.constructor=NA;NA.prototype.iy=NA;NA.jy={};b.btCollisionWorld=NA;NA.prototype.getDispatcher=function(){return k($a(this.hy),OA)}; +NA.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ab(e,a,c,d)};NA.prototype.getPairCache=function(){return k(bb(this.hy),PA)};NA.prototype.getDispatchInfo=function(){return k(cb(this.hy),l)}; +NA.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?db(e,a):void 0===d?eb(e,a,c):fb(e,a,c,d)};NA.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gb(c,a)};NA.prototype.getBroadphase=function(){return k(hb(this.hy),QA)}; +NA.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);ib(n,a,c,d,e,g)};NA.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);jb(e,a,c,d)}; +NA.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);kb(d,a,c)};NA.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lb(c,a)};NA.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mb(c,a)};NA.prototype.getDebugDrawer=function(){return k(nb(this.hy),RA)};NA.prototype.debugDrawWorld=function(){ob(this.hy)}; +NA.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);pb(e,a,c,d)};NA.prototype.__destroy__=function(){qb(this.hy)};function m(){throw"cannot construct a btCollisionShape, no constructor in IDL";}m.prototype=Object.create(f.prototype);m.prototype.constructor=m;m.prototype.iy=m;m.jy={};b.btCollisionShape=m; +m.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rb(c,a)};m.prototype.getLocalScaling=function(){return k(sb(this.hy),p)};m.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tb(d,a,c)};m.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ub(c,a)};m.prototype.getMargin=function(){return vb(this.hy)};m.prototype.__destroy__=function(){wb(this.hy)}; +function q(){throw"cannot construct a btCollisionObject, no constructor in IDL";}q.prototype=Object.create(f.prototype);q.prototype.constructor=q;q.prototype.iy=q;q.jy={};b.btCollisionObject=q;q.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);xb(d,a,c)};q.prototype.getCollisionShape=function(){return k(yb(this.hy),m)}; +q.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zb(c,a)};q.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ab(c,a)};q.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bb(c,a)};q.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Cb(c):Db(c,a)};q.prototype.isActive=function(){return!!Eb(this.hy)};q.prototype.isKinematicObject=function(){return!!Fb(this.hy)}; +q.prototype.isStaticObject=function(){return!!Gb(this.hy)};q.prototype.isStaticOrKinematicObject=function(){return!!Hb(this.hy)};q.prototype.getRestitution=function(){return Ib(this.hy)};q.prototype.getFriction=function(){return Jb(this.hy)};q.prototype.getRollingFriction=function(){return Kb(this.hy)};q.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lb(c,a)};q.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mb(c,a)}; +q.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nb(c,a)};q.prototype.getWorldTransform=function(){return k(Ob(this.hy),r)};q.prototype.getCollisionFlags=function(){return Pb(this.hy)};q.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qb(c,a)};q.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sb(c,a)}; +q.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tb(c,a)};q.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ub(c,a)};q.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vb(c,a)};q.prototype.getUserIndex=function(){return Wb(this.hy)};q.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xb(c,a)}; +q.prototype.getUserPointer=function(){return k(Yb(this.hy),SA)};q.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zb(c,a)};q.prototype.getBroadphaseHandle=function(){return k($b(this.hy),t)};q.prototype.__destroy__=function(){ac(this.hy)};function u(){throw"cannot construct a btDynamicsWorld, no constructor in IDL";}u.prototype=Object.create(NA.prototype);u.prototype.constructor=u;u.prototype.iy=u;u.jy={};b.btDynamicsWorld=u; +u.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bc(c,a)};u.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cc(c,a)};u.prototype.getSolverInfo=function(){return k(dc(this.hy),v)};u.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?ec(e,a):void 0===d?fc(e,a,c):hc(e,a,c,d)}; +u.prototype.getDispatcher=function(){return k(ic(this.hy),OA)};u.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);jc(e,a,c,d)};u.prototype.getPairCache=function(){return k(kc(this.hy),PA)};u.prototype.getDispatchInfo=function(){return k(lc(this.hy),l)}; +u.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?mc(e,a):void 0===d?nc(e,a,c):oc(e,a,c,d)};u.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pc(c,a)};u.prototype.getBroadphase=function(){return k(qc(this.hy),QA)}; +u.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);rc(n,a,c,d,e,g)};u.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);sc(e,a,c,d)}; +u.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tc(d,a,c)};u.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uc(c,a)};u.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vc(c,a)};u.prototype.getDebugDrawer=function(){return k(wc(this.hy),RA)};u.prototype.debugDrawWorld=function(){xc(this.hy)}; +u.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);yc(e,a,c,d)};u.prototype.__destroy__=function(){zc(this.hy)};function TA(){throw"cannot construct a btTypedConstraint, no constructor in IDL";}TA.prototype=Object.create(f.prototype);TA.prototype.constructor=TA;TA.prototype.iy=TA;TA.jy={};b.btTypedConstraint=TA; +TA.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ac(c,a)};TA.prototype.getBreakingImpulseThreshold=function(){return Bc(this.hy)};TA.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cc(c,a)};TA.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Dc(d,a,c)}; +TA.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ec(e,a,c,d)};TA.prototype.__destroy__=function(){Fc(this.hy)};function UA(){throw"cannot construct a btConcaveShape, no constructor in IDL";}UA.prototype=Object.create(m.prototype);UA.prototype.constructor=UA;UA.prototype.iy=UA;UA.jy={};b.btConcaveShape=UA; +UA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gc(c,a)};UA.prototype.getLocalScaling=function(){return k(Hc(this.hy),p)};UA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ic(d,a,c)};UA.prototype.__destroy__=function(){Jc(this.hy)};function VA(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Kc(a,c);h(VA)[this.hy]=this}VA.prototype=Object.create(m.prototype); +VA.prototype.constructor=VA;VA.prototype.iy=VA;VA.jy={};b.btCapsuleShape=VA;VA.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lc(c,a)};VA.prototype.getMargin=function(){return Mc(this.hy)};VA.prototype.getUpAxis=function(){return Nc(this.hy)};VA.prototype.getRadius=function(){return Oc(this.hy)};VA.prototype.getHalfHeight=function(){return Pc(this.hy)};VA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qc(c,a)}; +VA.prototype.getLocalScaling=function(){return k(Rc(this.hy),p)};VA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Sc(d,a,c)};VA.prototype.__destroy__=function(){Tc(this.hy)};function RA(){throw"cannot construct a btIDebugDraw, no constructor in IDL";}RA.prototype=Object.create(f.prototype);RA.prototype.constructor=RA;RA.prototype.iy=RA;RA.jy={};b.btIDebugDraw=RA; +RA.prototype.drawLine=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Uc(e,a,c,d)};RA.prototype.drawContactPoint=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);Vc(n,a,c,d,e,g)}; +RA.prototype.reportErrorWarning=function(a){var c=this.hy;IA();a=a&&"object"===typeof a?a.hy:LA(a);Wc(c,a)};RA.prototype.draw3dText=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c=c&&"object"===typeof c?c.hy:LA(c);Xc(d,a,c)};RA.prototype.setDebugMode=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yc(c,a)};RA.prototype.getDebugMode=function(){return Zc(this.hy)};RA.prototype.__destroy__=function(){$c(this.hy)}; +function WA(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?ad():bd(a);h(WA)[this.hy]=this}WA.prototype=Object.create(f.prototype);WA.prototype.constructor=WA;WA.prototype.iy=WA;WA.jy={};b.btDefaultCollisionConfiguration=WA;WA.prototype.__destroy__=function(){cd(this.hy)};function XA(){throw"cannot construct a btTriangleMeshShape, no constructor in IDL";}XA.prototype=Object.create(UA.prototype);XA.prototype.constructor=XA;XA.prototype.iy=XA;XA.jy={};b.btTriangleMeshShape=XA; +XA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dd(c,a)};XA.prototype.getLocalScaling=function(){return k(ed(this.hy),p)};XA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);fd(d,a,c)};XA.prototype.__destroy__=function(){gd(this.hy)};function w(){this.hy=hd();h(w)[this.hy]=this}w.prototype=Object.create(q.prototype);w.prototype.constructor=w;w.prototype.iy=w;w.jy={}; +b.btGhostObject=w;w.prototype.getNumOverlappingObjects=function(){return id(this.hy)};w.prototype.getOverlappingObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(jd(c,a),q)};w.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);kd(d,a,c)};w.prototype.getCollisionShape=function(){return k(ld(this.hy),m)}; +w.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);md(c,a)};w.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nd(c,a)};w.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);od(c,a)};w.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?pd(c):qd(c,a)};w.prototype.isActive=function(){return!!rd(this.hy)};w.prototype.isKinematicObject=function(){return!!sd(this.hy)}; +w.prototype.isStaticObject=function(){return!!td(this.hy)};w.prototype.isStaticOrKinematicObject=function(){return!!ud(this.hy)};w.prototype.getRestitution=function(){return vd(this.hy)};w.prototype.getFriction=function(){return wd(this.hy)};w.prototype.getRollingFriction=function(){return xd(this.hy)};w.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yd(c,a)};w.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zd(c,a)}; +w.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ad(c,a)};w.prototype.getWorldTransform=function(){return k(Bd(this.hy),r)};w.prototype.getCollisionFlags=function(){return Cd(this.hy)};w.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dd(c,a)};w.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ed(c,a)}; +w.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fd(c,a)};w.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gd(c,a)};w.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hd(c,a)};w.prototype.getUserIndex=function(){return Id(this.hy)};w.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jd(c,a)}; +w.prototype.getUserPointer=function(){return k(Kd(this.hy),SA)};w.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ld(c,a)};w.prototype.getBroadphaseHandle=function(){return k(Md(this.hy),t)};w.prototype.__destroy__=function(){Nd(this.hy)};function YA(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Od(a,c);h(YA)[this.hy]=this}YA.prototype=Object.create(m.prototype);YA.prototype.constructor=YA;YA.prototype.iy=YA;YA.jy={}; +b.btConeShape=YA;YA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pd(c,a)};YA.prototype.getLocalScaling=function(){return k(Qd(this.hy),p)};YA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Rd(d,a,c)};YA.prototype.__destroy__=function(){Sd(this.hy)};function ZA(){throw"cannot construct a btActionInterface, no constructor in IDL";}ZA.prototype=Object.create(f.prototype); +ZA.prototype.constructor=ZA;ZA.prototype.iy=ZA;ZA.jy={};b.btActionInterface=ZA;ZA.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Td(d,a,c)};ZA.prototype.__destroy__=function(){Ud(this.hy)}; +function p(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=void 0===a?Vd():void 0===c?_emscripten_bind_btVector3_btVector3_1(a):void 0===d?_emscripten_bind_btVector3_btVector3_2(a,c):Wd(a,c,d);h(p)[this.hy]=this}p.prototype=Object.create(f.prototype);p.prototype.constructor=p;p.prototype.iy=p;p.jy={};b.btVector3=p;p.prototype.length=p.prototype.length=function(){return Xd(this.hy)};p.prototype.x=p.prototype.x=function(){return Yd(this.hy)}; +p.prototype.y=p.prototype.y=function(){return Zd(this.hy)};p.prototype.z=p.prototype.z=function(){return $d(this.hy)};p.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ae(c,a)};p.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);be(c,a)};p.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ce(c,a)}; +p.prototype.setValue=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);de(e,a,c,d)};p.prototype.normalize=p.prototype.normalize=function(){ee(this.hy)};p.prototype.rotate=p.prototype.rotate=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return k(fe(d,a,c),p)};p.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return ge(c,a)}; +p.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(he(c,a),p)};p.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ie(c,a),p)};p.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(je(c,a),p)};p.prototype.__destroy__=function(){ke(this.hy)};function $A(){throw"cannot construct a btVehicleRaycaster, no constructor in IDL";}$A.prototype=Object.create(f.prototype);$A.prototype.constructor=$A; +$A.prototype.iy=$A;$A.jy={};b.btVehicleRaycaster=$A;$A.prototype.castRay=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);le(e,a,c,d)};$A.prototype.__destroy__=function(){me(this.hy)};function aB(){throw"cannot construct a btQuadWord, no constructor in IDL";}aB.prototype=Object.create(f.prototype);aB.prototype.constructor=aB;aB.prototype.iy=aB;aB.jy={};b.btQuadWord=aB;aB.prototype.x=aB.prototype.x=function(){return ne(this.hy)}; +aB.prototype.y=aB.prototype.y=function(){return oe(this.hy)};aB.prototype.z=aB.prototype.z=function(){return pe(this.hy)};aB.prototype.w=function(){return qe(this.hy)};aB.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);re(c,a)};aB.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);se(c,a)};aB.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);te(c,a)}; +aB.prototype.setW=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ue(c,a)};aB.prototype.__destroy__=function(){ve(this.hy)};function bB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=we(a);h(bB)[this.hy]=this}bB.prototype=Object.create(m.prototype);bB.prototype.constructor=bB;bB.prototype.iy=bB;bB.jy={};b.btCylinderShape=bB;bB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xe(c,a)};bB.prototype.getMargin=function(){return ye(this.hy)}; +bB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ze(c,a)};bB.prototype.getLocalScaling=function(){return k(Ae(this.hy),p)};bB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Be(d,a,c)};bB.prototype.__destroy__=function(){Ce(this.hy)}; +function x(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=De(a,c,d,e);h(x)[this.hy]=this}x.prototype=Object.create(u.prototype);x.prototype.constructor=x;x.prototype.iy=x;x.jy={};b.btDiscreteDynamicsWorld=x;x.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ee(c,a)};x.prototype.getGravity=function(){return k(Fe(this.hy),p)}; +x.prototype.addRigidBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Ge(e,a):void 0===d?_emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_2(e,a,c):He(e,a,c,d)};x.prototype.removeRigidBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ie(c,a)}; +x.prototype.addConstraint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Je(d,a):Ke(d,a,c)};x.prototype.removeConstraint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Le(c,a)};x.prototype.stepSimulation=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return void 0===c?Me(e,a):void 0===d?Ne(e,a,c):Oe(e,a,c,d)}; +x.prototype.setContactAddedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pe(c,a)};x.prototype.setContactProcessedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qe(c,a)};x.prototype.setContactDestroyedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Re(c,a)};x.prototype.getDispatcher=function(){return k(Se(this.hy),OA)}; +x.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Te(e,a,c,d)};x.prototype.getPairCache=function(){return k(Ue(this.hy),PA)};x.prototype.getDispatchInfo=function(){return k(Ve(this.hy),l)};x.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?We(e,a):void 0===d?Xe(e,a,c):Ye(e,a,c,d)}; +x.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ze(c,a)};x.prototype.getBroadphase=function(){return k($e(this.hy),QA)};x.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);af(n,a,c,d,e,g)}; +x.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);bf(e,a,c,d)};x.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);cf(d,a,c)};x.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);df(c,a)};x.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ef(c,a)}; +x.prototype.getDebugDrawer=function(){return k(ff(this.hy),RA)};x.prototype.debugDrawWorld=function(){gf(this.hy)};x.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);hf(e,a,c,d)};x.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jf(c,a)};x.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kf(c,a)}; +x.prototype.getSolverInfo=function(){return k(lf(this.hy),v)};x.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?mf(e,a):void 0===d?nf(e,a,c):of(e,a,c,d)};x.prototype.__destroy__=function(){pf(this.hy)};function cB(){throw"cannot construct a btConvexShape, no constructor in IDL";}cB.prototype=Object.create(m.prototype);cB.prototype.constructor=cB;cB.prototype.iy=cB;cB.jy={}; +b.btConvexShape=cB;cB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qf(c,a)};cB.prototype.getLocalScaling=function(){return k(rf(this.hy),p)};cB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);sf(d,a,c)};cB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tf(c,a)};cB.prototype.getMargin=function(){return uf(this.hy)};cB.prototype.__destroy__=function(){vf(this.hy)}; +function OA(){throw"cannot construct a btDispatcher, no constructor in IDL";}OA.prototype=Object.create(f.prototype);OA.prototype.constructor=OA;OA.prototype.iy=OA;OA.jy={};b.btDispatcher=OA;OA.prototype.getNumManifolds=function(){return wf(this.hy)};OA.prototype.getManifoldByIndexInternal=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(xf(c,a),dB)};OA.prototype.__destroy__=function(){yf(this.hy)}; +function eB(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?zf(a,c,d):void 0===g?_emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_4(a,c,d,e):Af(a,c,d,e,g);h(eB)[this.hy]=this}eB.prototype=Object.create(TA.prototype);eB.prototype.constructor=eB;eB.prototype.iy=eB;eB.jy={};b.btGeneric6DofConstraint=eB; +eB.prototype.setLinearLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bf(c,a)};eB.prototype.setLinearUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cf(c,a)};eB.prototype.setAngularLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Df(c,a)};eB.prototype.setAngularUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ef(c,a)};eB.prototype.getFrameOffsetA=function(){return k(Ff(this.hy),r)}; +eB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gf(c,a)};eB.prototype.getBreakingImpulseThreshold=function(){return Hf(this.hy)};eB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);If(c,a)};eB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Jf(d,a,c)}; +eB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Kf(e,a,c,d)};eB.prototype.__destroy__=function(){Lf(this.hy)};function fB(){throw"cannot construct a btStridingMeshInterface, no constructor in IDL";}fB.prototype=Object.create(f.prototype);fB.prototype.constructor=fB;fB.prototype.iy=fB;fB.jy={};b.btStridingMeshInterface=fB; +fB.prototype.setScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mf(c,a)};fB.prototype.__destroy__=function(){Nf(this.hy)};function gB(){throw"cannot construct a btMotionState, no constructor in IDL";}gB.prototype=Object.create(f.prototype);gB.prototype.constructor=gB;gB.prototype.iy=gB;gB.jy={};b.btMotionState=gB;gB.prototype.getWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Of(c,a)}; +gB.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pf(c,a)};gB.prototype.__destroy__=function(){Qf(this.hy)};function y(){throw"cannot construct a ConvexResultCallback, no constructor in IDL";}y.prototype=Object.create(f.prototype);y.prototype.constructor=y;y.prototype.iy=y;y.jy={};b.ConvexResultCallback=y;y.prototype.hasHit=function(){return!!Rf(this.hy)};y.prototype.get_m_collisionFilterGroup=y.prototype.ky=function(){return Sf(this.hy)}; +y.prototype.set_m_collisionFilterGroup=y.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tf(c,a)};Object.defineProperty(y.prototype,"m_collisionFilterGroup",{get:y.prototype.ky,set:y.prototype.my});y.prototype.get_m_collisionFilterMask=y.prototype.ly=function(){return Uf(this.hy)};y.prototype.set_m_collisionFilterMask=y.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vf(c,a)}; +Object.defineProperty(y.prototype,"m_collisionFilterMask",{get:y.prototype.ly,set:y.prototype.ny});y.prototype.get_m_closestHitFraction=y.prototype.oy=function(){return Wf(this.hy)};y.prototype.set_m_closestHitFraction=y.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xf(c,a)};Object.defineProperty(y.prototype,"m_closestHitFraction",{get:y.prototype.oy,set:y.prototype.py});y.prototype.__destroy__=function(){Yf(this.hy)}; +function hB(){throw"cannot construct a ContactResultCallback, no constructor in IDL";}hB.prototype=Object.create(f.prototype);hB.prototype.constructor=hB;hB.prototype.iy=hB;hB.jy={};b.ContactResultCallback=hB; +hB.prototype.addSingleResult=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return Zf(aa,a,c,d,e,g,n,F)};hB.prototype.__destroy__=function(){$f(this.hy)};function iB(){throw"cannot construct a btSoftBodySolver, no constructor in IDL";}iB.prototype=Object.create(f.prototype); +iB.prototype.constructor=iB;iB.prototype.iy=iB;iB.jy={};b.btSoftBodySolver=iB;iB.prototype.__destroy__=function(){ag(this.hy)};function z(){throw"cannot construct a RayResultCallback, no constructor in IDL";}z.prototype=Object.create(f.prototype);z.prototype.constructor=z;z.prototype.iy=z;z.jy={};b.RayResultCallback=z;z.prototype.hasHit=function(){return!!bg(this.hy)};z.prototype.get_m_collisionFilterGroup=z.prototype.ky=function(){return cg(this.hy)}; +z.prototype.set_m_collisionFilterGroup=z.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dg(c,a)};Object.defineProperty(z.prototype,"m_collisionFilterGroup",{get:z.prototype.ky,set:z.prototype.my});z.prototype.get_m_collisionFilterMask=z.prototype.ly=function(){return eg(this.hy)};z.prototype.set_m_collisionFilterMask=z.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fg(c,a)}; +Object.defineProperty(z.prototype,"m_collisionFilterMask",{get:z.prototype.ly,set:z.prototype.ny});z.prototype.get_m_closestHitFraction=z.prototype.oy=function(){return gg(this.hy)};z.prototype.set_m_closestHitFraction=z.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hg(c,a)};Object.defineProperty(z.prototype,"m_closestHitFraction",{get:z.prototype.oy,set:z.prototype.py});z.prototype.get_m_collisionObject=z.prototype.qy=function(){return k(ig(this.hy),q)}; +z.prototype.set_m_collisionObject=z.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jg(c,a)};Object.defineProperty(z.prototype,"m_collisionObject",{get:z.prototype.qy,set:z.prototype.xy});z.prototype.__destroy__=function(){kg(this.hy)};function jB(){throw"cannot construct a btMatrix3x3, no constructor in IDL";}jB.prototype=Object.create(f.prototype);jB.prototype.constructor=jB;jB.prototype.iy=jB;jB.jy={};b.btMatrix3x3=jB; +jB.prototype.setEulerZYX=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);lg(e,a,c,d)};jB.prototype.getRotation=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mg(c,a)};jB.prototype.getRow=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ng(c,a),p)};jB.prototype.__destroy__=function(){og(this.hy)};function kB(){throw"cannot construct a btScalarArray, no constructor in IDL";}kB.prototype=Object.create(f.prototype); +kB.prototype.constructor=kB;kB.prototype.iy=kB;kB.jy={};b.btScalarArray=kB;kB.prototype.size=kB.prototype.size=function(){return pg(this.hy)};kB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return qg(c,a)};kB.prototype.__destroy__=function(){rg(this.hy)};function A(){throw"cannot construct a Material, no constructor in IDL";}A.prototype=Object.create(f.prototype);A.prototype.constructor=A;A.prototype.iy=A;A.jy={};b.Material=A;A.prototype.get_m_kLST=A.prototype.vA=function(){return sg(this.hy)}; +A.prototype.set_m_kLST=A.prototype.bD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tg(c,a)};Object.defineProperty(A.prototype,"m_kLST",{get:A.prototype.vA,set:A.prototype.bD});A.prototype.get_m_kAST=A.prototype.uA=function(){return ug(this.hy)};A.prototype.set_m_kAST=A.prototype.aD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vg(c,a)};Object.defineProperty(A.prototype,"m_kAST",{get:A.prototype.uA,set:A.prototype.aD});A.prototype.get_m_kVST=A.prototype.wA=function(){return wg(this.hy)}; +A.prototype.set_m_kVST=A.prototype.cD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xg(c,a)};Object.defineProperty(A.prototype,"m_kVST",{get:A.prototype.wA,set:A.prototype.cD});A.prototype.get_m_flags=A.prototype.cA=function(){return yg(this.hy)};A.prototype.set_m_flags=A.prototype.JC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zg(c,a)};Object.defineProperty(A.prototype,"m_flags",{get:A.prototype.cA,set:A.prototype.JC});A.prototype.__destroy__=function(){Ag(this.hy)}; +function l(){throw"cannot construct a btDispatcherInfo, no constructor in IDL";}l.prototype=Object.create(f.prototype);l.prototype.constructor=l;l.prototype.iy=l;l.jy={};b.btDispatcherInfo=l;l.prototype.get_m_timeStep=l.prototype.jB=function(){return Bg(this.hy)};l.prototype.set_m_timeStep=l.prototype.QD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cg(c,a)};Object.defineProperty(l.prototype,"m_timeStep",{get:l.prototype.jB,set:l.prototype.QD}); +l.prototype.get_m_stepCount=l.prototype.aB=function(){return Dg(this.hy)};l.prototype.set_m_stepCount=l.prototype.HD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Eg(c,a)};Object.defineProperty(l.prototype,"m_stepCount",{get:l.prototype.aB,set:l.prototype.HD});l.prototype.get_m_dispatchFunc=l.prototype.Wz=function(){return Fg(this.hy)};l.prototype.set_m_dispatchFunc=l.prototype.CC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gg(c,a)}; +Object.defineProperty(l.prototype,"m_dispatchFunc",{get:l.prototype.Wz,set:l.prototype.CC});l.prototype.get_m_timeOfImpact=l.prototype.iB=function(){return Hg(this.hy)};l.prototype.set_m_timeOfImpact=l.prototype.PD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ig(c,a)};Object.defineProperty(l.prototype,"m_timeOfImpact",{get:l.prototype.iB,set:l.prototype.PD});l.prototype.get_m_useContinuous=l.prototype.lB=function(){return!!Jg(this.hy)}; +l.prototype.set_m_useContinuous=l.prototype.SD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kg(c,a)};Object.defineProperty(l.prototype,"m_useContinuous",{get:l.prototype.lB,set:l.prototype.SD});l.prototype.get_m_enableSatConvex=l.prototype.$z=function(){return!!Lg(this.hy)};l.prototype.set_m_enableSatConvex=l.prototype.GC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mg(c,a)};Object.defineProperty(l.prototype,"m_enableSatConvex",{get:l.prototype.$z,set:l.prototype.GC}); +l.prototype.get_m_enableSPU=l.prototype.Zz=function(){return!!Ng(this.hy)};l.prototype.set_m_enableSPU=l.prototype.FC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Og(c,a)};Object.defineProperty(l.prototype,"m_enableSPU",{get:l.prototype.Zz,set:l.prototype.FC});l.prototype.get_m_useEpa=l.prototype.nB=function(){return!!Pg(this.hy)};l.prototype.set_m_useEpa=l.prototype.UD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qg(c,a)}; +Object.defineProperty(l.prototype,"m_useEpa",{get:l.prototype.nB,set:l.prototype.UD});l.prototype.get_m_allowedCcdPenetration=l.prototype.zz=function(){return Rg(this.hy)};l.prototype.set_m_allowedCcdPenetration=l.prototype.fC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sg(c,a)};Object.defineProperty(l.prototype,"m_allowedCcdPenetration",{get:l.prototype.zz,set:l.prototype.fC});l.prototype.get_m_useConvexConservativeDistanceUtil=l.prototype.mB=function(){return!!Tg(this.hy)}; +l.prototype.set_m_useConvexConservativeDistanceUtil=l.prototype.TD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ug(c,a)};Object.defineProperty(l.prototype,"m_useConvexConservativeDistanceUtil",{get:l.prototype.mB,set:l.prototype.TD});l.prototype.get_m_convexConservativeDistanceThreshold=l.prototype.Rz=function(){return Vg(this.hy)};l.prototype.set_m_convexConservativeDistanceThreshold=l.prototype.xC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wg(c,a)}; +Object.defineProperty(l.prototype,"m_convexConservativeDistanceThreshold",{get:l.prototype.Rz,set:l.prototype.xC});l.prototype.__destroy__=function(){Xg(this.hy)};function B(){throw"cannot construct a btWheelInfoConstructionInfo, no constructor in IDL";}B.prototype=Object.create(f.prototype);B.prototype.constructor=B;B.prototype.iy=B;B.jy={};b.btWheelInfoConstructionInfo=B;B.prototype.get_m_chassisConnectionCS=B.prototype.Lz=function(){return k(Yg(this.hy),p)}; +B.prototype.set_m_chassisConnectionCS=B.prototype.rC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zg(c,a)};Object.defineProperty(B.prototype,"m_chassisConnectionCS",{get:B.prototype.Lz,set:B.prototype.rC});B.prototype.get_m_wheelDirectionCS=B.prototype.Ly=function(){return k($g(this.hy),p)};B.prototype.set_m_wheelDirectionCS=B.prototype.Uy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ah(c,a)};Object.defineProperty(B.prototype,"m_wheelDirectionCS",{get:B.prototype.Ly,set:B.prototype.Uy}); +B.prototype.get_m_wheelAxleCS=B.prototype.Ky=function(){return k(bh(this.hy),p)};B.prototype.set_m_wheelAxleCS=B.prototype.Ty=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ch(c,a)};Object.defineProperty(B.prototype,"m_wheelAxleCS",{get:B.prototype.Ky,set:B.prototype.Ty});B.prototype.get_m_suspensionRestLength=B.prototype.fB=function(){return dh(this.hy)};B.prototype.set_m_suspensionRestLength=B.prototype.MD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);eh(c,a)}; +Object.defineProperty(B.prototype,"m_suspensionRestLength",{get:B.prototype.fB,set:B.prototype.MD});B.prototype.get_m_maxSuspensionTravelCm=B.prototype.vy=function(){return fh(this.hy)};B.prototype.set_m_maxSuspensionTravelCm=B.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gh(c,a)};Object.defineProperty(B.prototype,"m_maxSuspensionTravelCm",{get:B.prototype.vy,set:B.prototype.Cy});B.prototype.get_m_wheelRadius=B.prototype.tB=function(){return hh(this.hy)}; +B.prototype.set_m_wheelRadius=B.prototype.$D=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ih(c,a)};Object.defineProperty(B.prototype,"m_wheelRadius",{get:B.prototype.tB,set:B.prototype.$D});B.prototype.get_m_suspensionStiffness=B.prototype.wy=function(){return jh(this.hy)};B.prototype.set_m_suspensionStiffness=B.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kh(c,a)};Object.defineProperty(B.prototype,"m_suspensionStiffness",{get:B.prototype.wy,set:B.prototype.Dy}); +B.prototype.get_m_wheelsDampingCompression=B.prototype.My=function(){return lh(this.hy)};B.prototype.set_m_wheelsDampingCompression=B.prototype.Vy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mh(c,a)};Object.defineProperty(B.prototype,"m_wheelsDampingCompression",{get:B.prototype.My,set:B.prototype.Vy});B.prototype.get_m_wheelsDampingRelaxation=B.prototype.Ny=function(){return nh(this.hy)}; +B.prototype.set_m_wheelsDampingRelaxation=B.prototype.Wy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);oh(c,a)};Object.defineProperty(B.prototype,"m_wheelsDampingRelaxation",{get:B.prototype.Ny,set:B.prototype.Wy});B.prototype.get_m_frictionSlip=B.prototype.ry=function(){return ph(this.hy)};B.prototype.set_m_frictionSlip=B.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qh(c,a)};Object.defineProperty(B.prototype,"m_frictionSlip",{get:B.prototype.ry,set:B.prototype.yy}); +B.prototype.get_m_maxSuspensionForce=B.prototype.uy=function(){return rh(this.hy)};B.prototype.set_m_maxSuspensionForce=B.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sh(c,a)};Object.defineProperty(B.prototype,"m_maxSuspensionForce",{get:B.prototype.uy,set:B.prototype.By});B.prototype.get_m_bIsFrontWheel=B.prototype.Fy=function(){return!!th(this.hy)};B.prototype.set_m_bIsFrontWheel=B.prototype.Oy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uh(c,a)}; +Object.defineProperty(B.prototype,"m_bIsFrontWheel",{get:B.prototype.Fy,set:B.prototype.Oy});B.prototype.__destroy__=function(){vh(this.hy)};function lB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===c?wh(a):xh(a,c);h(lB)[this.hy]=this}lB.prototype=Object.create(cB.prototype);lB.prototype.constructor=lB;lB.prototype.iy=lB;lB.jy={};b.btConvexTriangleMeshShape=lB;lB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yh(c,a)}; +lB.prototype.getLocalScaling=function(){return k(zh(this.hy),p)};lB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ah(d,a,c)};lB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bh(c,a)};lB.prototype.getMargin=function(){return Ch(this.hy)};lB.prototype.__destroy__=function(){Dh(this.hy)};function QA(){throw"cannot construct a btBroadphaseInterface, no constructor in IDL";}QA.prototype=Object.create(f.prototype); +QA.prototype.constructor=QA;QA.prototype.iy=QA;QA.jy={};b.btBroadphaseInterface=QA;QA.prototype.getOverlappingPairCache=function(){return k(Eh(this.hy),PA)};QA.prototype.__destroy__=function(){Fh(this.hy)};function C(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===e?Gh(a,c,d):Hh(a,c,d,e);h(C)[this.hy]=this}C.prototype=Object.create(f.prototype);C.prototype.constructor=C;C.prototype.iy=C; +C.jy={};b.btRigidBodyConstructionInfo=C;C.prototype.get_m_linearDamping=C.prototype.xA=function(){return Ih(this.hy)};C.prototype.set_m_linearDamping=C.prototype.dD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jh(c,a)};Object.defineProperty(C.prototype,"m_linearDamping",{get:C.prototype.xA,set:C.prototype.dD});C.prototype.get_m_angularDamping=C.prototype.Bz=function(){return Kh(this.hy)}; +C.prototype.set_m_angularDamping=C.prototype.hC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lh(c,a)};Object.defineProperty(C.prototype,"m_angularDamping",{get:C.prototype.Bz,set:C.prototype.hC});C.prototype.get_m_friction=C.prototype.dA=function(){return Mh(this.hy)};C.prototype.set_m_friction=C.prototype.KC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nh(c,a)};Object.defineProperty(C.prototype,"m_friction",{get:C.prototype.dA,set:C.prototype.KC}); +C.prototype.get_m_rollingFriction=C.prototype.TA=function(){return Oh(this.hy)};C.prototype.set_m_rollingFriction=C.prototype.zD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ph(c,a)};Object.defineProperty(C.prototype,"m_rollingFriction",{get:C.prototype.TA,set:C.prototype.zD});C.prototype.get_m_restitution=C.prototype.RA=function(){return Qh(this.hy)};C.prototype.set_m_restitution=C.prototype.xD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rh(c,a)}; +Object.defineProperty(C.prototype,"m_restitution",{get:C.prototype.RA,set:C.prototype.xD});C.prototype.get_m_linearSleepingThreshold=C.prototype.yA=function(){return Sh(this.hy)};C.prototype.set_m_linearSleepingThreshold=C.prototype.eD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Th(c,a)};Object.defineProperty(C.prototype,"m_linearSleepingThreshold",{get:C.prototype.yA,set:C.prototype.eD});C.prototype.get_m_angularSleepingThreshold=C.prototype.Cz=function(){return Uh(this.hy)}; +C.prototype.set_m_angularSleepingThreshold=C.prototype.iC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vh(c,a)};Object.defineProperty(C.prototype,"m_angularSleepingThreshold",{get:C.prototype.Cz,set:C.prototype.iC});C.prototype.get_m_additionalDamping=C.prototype.wz=function(){return!!Wh(this.hy)};C.prototype.set_m_additionalDamping=C.prototype.cC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xh(c,a)}; +Object.defineProperty(C.prototype,"m_additionalDamping",{get:C.prototype.wz,set:C.prototype.cC});C.prototype.get_m_additionalDampingFactor=C.prototype.xz=function(){return Yh(this.hy)};C.prototype.set_m_additionalDampingFactor=C.prototype.dC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zh(c,a)};Object.defineProperty(C.prototype,"m_additionalDampingFactor",{get:C.prototype.xz,set:C.prototype.dC});C.prototype.get_m_additionalLinearDampingThresholdSqr=C.prototype.yz=function(){return $h(this.hy)}; +C.prototype.set_m_additionalLinearDampingThresholdSqr=C.prototype.eC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ai(c,a)};Object.defineProperty(C.prototype,"m_additionalLinearDampingThresholdSqr",{get:C.prototype.yz,set:C.prototype.eC});C.prototype.get_m_additionalAngularDampingThresholdSqr=C.prototype.vz=function(){return bi(this.hy)};C.prototype.set_m_additionalAngularDampingThresholdSqr=C.prototype.bC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ci(c,a)}; +Object.defineProperty(C.prototype,"m_additionalAngularDampingThresholdSqr",{get:C.prototype.vz,set:C.prototype.bC});C.prototype.get_m_additionalAngularDampingFactor=C.prototype.uz=function(){return di(this.hy)};C.prototype.set_m_additionalAngularDampingFactor=C.prototype.aC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ei(c,a)};Object.defineProperty(C.prototype,"m_additionalAngularDampingFactor",{get:C.prototype.uz,set:C.prototype.aC});C.prototype.__destroy__=function(){fi(this.hy)}; +function mB(){throw"cannot construct a btCollisionConfiguration, no constructor in IDL";}mB.prototype=Object.create(f.prototype);mB.prototype.constructor=mB;mB.prototype.iy=mB;mB.jy={};b.btCollisionConfiguration=mB;mB.prototype.__destroy__=function(){gi(this.hy)};function dB(){this.hy=hi();h(dB)[this.hy]=this}dB.prototype=Object.create(f.prototype);dB.prototype.constructor=dB;dB.prototype.iy=dB;dB.jy={};b.btPersistentManifold=dB;dB.prototype.getBody0=function(){return k(ii(this.hy),q)}; +dB.prototype.getBody1=function(){return k(ji(this.hy),q)};dB.prototype.getNumContacts=function(){return ki(this.hy)};dB.prototype.getContactPoint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(li(c,a),D)};dB.prototype.__destroy__=function(){mi(this.hy)};function nB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?ni():oi(a);h(nB)[this.hy]=this}nB.prototype=Object.create(m.prototype);nB.prototype.constructor=nB;nB.prototype.iy=nB;nB.jy={};b.btCompoundShape=nB; +nB.prototype.addChildShape=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pi(d,a,c)};nB.prototype.removeChildShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qi(c,a)};nB.prototype.removeChildShapeByIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ri(c,a)};nB.prototype.getNumChildShapes=function(){return si(this.hy)};nB.prototype.getChildShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ti(c,a),m)}; +nB.prototype.updateChildTransform=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===d?ui(e,a,c):vi(e,a,c,d)};nB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wi(c,a)};nB.prototype.getMargin=function(){return xi(this.hy)};nB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yi(c,a)};nB.prototype.getLocalScaling=function(){return k(zi(this.hy),p)}; +nB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ai(d,a,c)};nB.prototype.__destroy__=function(){Bi(this.hy)};function E(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Ci(a,c);h(E)[this.hy]=this}E.prototype=Object.create(y.prototype);E.prototype.constructor=E;E.prototype.iy=E;E.jy={};b.ClosestConvexResultCallback=E;E.prototype.hasHit=function(){return!!Di(this.hy)}; +E.prototype.get_m_convexFromWorld=E.prototype.Sz=function(){return k(Ei(this.hy),p)};E.prototype.set_m_convexFromWorld=E.prototype.yC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fi(c,a)};Object.defineProperty(E.prototype,"m_convexFromWorld",{get:E.prototype.Sz,set:E.prototype.yC});E.prototype.get_m_convexToWorld=E.prototype.Tz=function(){return k(Gi(this.hy),p)};E.prototype.set_m_convexToWorld=E.prototype.zC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hi(c,a)}; +Object.defineProperty(E.prototype,"m_convexToWorld",{get:E.prototype.Tz,set:E.prototype.zC});E.prototype.get_m_hitNormalWorld=E.prototype.sy=function(){return k(Ii(this.hy),p)};E.prototype.set_m_hitNormalWorld=E.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ji(c,a)};Object.defineProperty(E.prototype,"m_hitNormalWorld",{get:E.prototype.sy,set:E.prototype.zy});E.prototype.get_m_hitPointWorld=E.prototype.ty=function(){return k(Ki(this.hy),p)}; +E.prototype.set_m_hitPointWorld=E.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Li(c,a)};Object.defineProperty(E.prototype,"m_hitPointWorld",{get:E.prototype.ty,set:E.prototype.Ay});E.prototype.get_m_collisionFilterGroup=E.prototype.ky=function(){return Mi(this.hy)};E.prototype.set_m_collisionFilterGroup=E.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ni(c,a)};Object.defineProperty(E.prototype,"m_collisionFilterGroup",{get:E.prototype.ky,set:E.prototype.my}); +E.prototype.get_m_collisionFilterMask=E.prototype.ly=function(){return Oi(this.hy)};E.prototype.set_m_collisionFilterMask=E.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pi(c,a)};Object.defineProperty(E.prototype,"m_collisionFilterMask",{get:E.prototype.ly,set:E.prototype.ny});E.prototype.get_m_closestHitFraction=E.prototype.oy=function(){return Qi(this.hy)}; +E.prototype.set_m_closestHitFraction=E.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ri(c,a)};Object.defineProperty(E.prototype,"m_closestHitFraction",{get:E.prototype.oy,set:E.prototype.py});E.prototype.__destroy__=function(){Si(this.hy)};function G(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Ti(a,c);h(G)[this.hy]=this}G.prototype=Object.create(z.prototype);G.prototype.constructor=G;G.prototype.iy=G;G.jy={};b.AllHitsRayResultCallback=G; +G.prototype.hasHit=function(){return!!Ui(this.hy)};G.prototype.get_m_collisionObjects=G.prototype.Oz=function(){return k(Vi(this.hy),oB)};G.prototype.set_m_collisionObjects=G.prototype.uC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wi(c,a)};Object.defineProperty(G.prototype,"m_collisionObjects",{get:G.prototype.Oz,set:G.prototype.uC});G.prototype.get_m_rayFromWorld=G.prototype.Iy=function(){return k(Xi(this.hy),p)}; +G.prototype.set_m_rayFromWorld=G.prototype.Ry=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yi(c,a)};Object.defineProperty(G.prototype,"m_rayFromWorld",{get:G.prototype.Iy,set:G.prototype.Ry});G.prototype.get_m_rayToWorld=G.prototype.Jy=function(){return k(Zi(this.hy),p)};G.prototype.set_m_rayToWorld=G.prototype.Sy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$i(c,a)};Object.defineProperty(G.prototype,"m_rayToWorld",{get:G.prototype.Jy,set:G.prototype.Sy}); +G.prototype.get_m_hitNormalWorld=G.prototype.sy=function(){return k(aj(this.hy),pB)};G.prototype.set_m_hitNormalWorld=G.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bj(c,a)};Object.defineProperty(G.prototype,"m_hitNormalWorld",{get:G.prototype.sy,set:G.prototype.zy});G.prototype.get_m_hitPointWorld=G.prototype.ty=function(){return k(cj(this.hy),pB)};G.prototype.set_m_hitPointWorld=G.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dj(c,a)}; +Object.defineProperty(G.prototype,"m_hitPointWorld",{get:G.prototype.ty,set:G.prototype.Ay});G.prototype.get_m_hitFractions=G.prototype.kA=function(){return k(ej(this.hy),kB)};G.prototype.set_m_hitFractions=G.prototype.RC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fj(c,a)};Object.defineProperty(G.prototype,"m_hitFractions",{get:G.prototype.kA,set:G.prototype.RC});G.prototype.get_m_collisionFilterGroup=G.prototype.ky=function(){return gj(this.hy)}; +G.prototype.set_m_collisionFilterGroup=G.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hj(c,a)};Object.defineProperty(G.prototype,"m_collisionFilterGroup",{get:G.prototype.ky,set:G.prototype.my});G.prototype.get_m_collisionFilterMask=G.prototype.ly=function(){return ij(this.hy)};G.prototype.set_m_collisionFilterMask=G.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jj(c,a)}; +Object.defineProperty(G.prototype,"m_collisionFilterMask",{get:G.prototype.ly,set:G.prototype.ny});G.prototype.get_m_closestHitFraction=G.prototype.oy=function(){return kj(this.hy)};G.prototype.set_m_closestHitFraction=G.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lj(c,a)};Object.defineProperty(G.prototype,"m_closestHitFraction",{get:G.prototype.oy,set:G.prototype.py});G.prototype.get_m_collisionObject=G.prototype.qy=function(){return k(mj(this.hy),q)}; +G.prototype.set_m_collisionObject=G.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nj(c,a)};Object.defineProperty(G.prototype,"m_collisionObject",{get:G.prototype.qy,set:G.prototype.xy});G.prototype.__destroy__=function(){oj(this.hy)};function qB(){throw"cannot construct a tMaterialArray, no constructor in IDL";}qB.prototype=Object.create(f.prototype);qB.prototype.constructor=qB;qB.prototype.iy=qB;qB.jy={};b.tMaterialArray=qB;qB.prototype.size=qB.prototype.size=function(){return pj(this.hy)}; +qB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(qj(c,a),A)};qB.prototype.__destroy__=function(){rj(this.hy)};function rB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=sj(a);h(rB)[this.hy]=this}rB.prototype=Object.create($A.prototype);rB.prototype.constructor=rB;rB.prototype.iy=rB;rB.jy={};b.btDefaultVehicleRaycaster=rB; +rB.prototype.castRay=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);tj(e,a,c,d)};rB.prototype.__destroy__=function(){uj(this.hy)};function sB(){this.hy=vj();h(sB)[this.hy]=this}sB.prototype=Object.create(UA.prototype);sB.prototype.constructor=sB;sB.prototype.iy=sB;sB.jy={};b.btEmptyShape=sB;sB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wj(c,a)}; +sB.prototype.getLocalScaling=function(){return k(xj(this.hy),p)};sB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);yj(d,a,c)};sB.prototype.__destroy__=function(){zj(this.hy)};function H(){this.hy=Aj();h(H)[this.hy]=this}H.prototype=Object.create(f.prototype);H.prototype.constructor=H;H.prototype.iy=H;H.jy={};b.btConstraintSetting=H;H.prototype.get_m_tau=H.prototype.hB=function(){return Bj(this.hy)}; +H.prototype.set_m_tau=H.prototype.OD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cj(c,a)};Object.defineProperty(H.prototype,"m_tau",{get:H.prototype.hB,set:H.prototype.OD});H.prototype.get_m_damping=H.prototype.Uz=function(){return Dj(this.hy)};H.prototype.set_m_damping=H.prototype.AC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ej(c,a)};Object.defineProperty(H.prototype,"m_damping",{get:H.prototype.Uz,set:H.prototype.AC}); +H.prototype.get_m_impulseClamp=H.prototype.qA=function(){return Fj(this.hy)};H.prototype.set_m_impulseClamp=H.prototype.XC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gj(c,a)};Object.defineProperty(H.prototype,"m_impulseClamp",{get:H.prototype.qA,set:H.prototype.XC});H.prototype.__destroy__=function(){Hj(this.hy)};function tB(){throw"cannot construct a LocalShapeInfo, no constructor in IDL";}tB.prototype=Object.create(f.prototype);tB.prototype.constructor=tB;tB.prototype.iy=tB; +tB.jy={};b.LocalShapeInfo=tB;tB.prototype.get_m_shapePart=tB.prototype.WA=function(){return Ij(this.hy)};tB.prototype.set_m_shapePart=tB.prototype.CD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jj(c,a)};Object.defineProperty(tB.prototype,"m_shapePart",{get:tB.prototype.WA,set:tB.prototype.CD});tB.prototype.get_m_triangleIndex=tB.prototype.kB=function(){return Kj(this.hy)}; +tB.prototype.set_m_triangleIndex=tB.prototype.RD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lj(c,a)};Object.defineProperty(tB.prototype,"m_triangleIndex",{get:tB.prototype.kB,set:tB.prototype.RD});tB.prototype.__destroy__=function(){Mj(this.hy)};function I(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Nj(a);h(I)[this.hy]=this}I.prototype=Object.create(q.prototype);I.prototype.constructor=I;I.prototype.iy=I;I.jy={};b.btRigidBody=I; +I.prototype.getCenterOfMassTransform=function(){return k(Oj(this.hy),r)};I.prototype.setCenterOfMassTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pj(c,a)};I.prototype.setSleepingThresholds=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Qj(d,a,c)};I.prototype.getLinearDamping=function(){return Rj(this.hy)};I.prototype.getAngularDamping=function(){return Sj(this.hy)}; +I.prototype.setDamping=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Tj(d,a,c)};I.prototype.setMassProps=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Uj(d,a,c)};I.prototype.getLinearFactor=function(){return k(Vj(this.hy),p)};I.prototype.setLinearFactor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wj(c,a)}; +I.prototype.applyTorque=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xj(c,a)};I.prototype.applyLocalTorque=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yj(c,a)};I.prototype.applyForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Zj(d,a,c)};I.prototype.applyCentralForce=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ak(c,a)}; +I.prototype.applyCentralLocalForce=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bk(c,a)};I.prototype.applyTorqueImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ck(c,a)};I.prototype.applyImpulse=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dk(d,a,c)};I.prototype.applyCentralImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ek(c,a)};I.prototype.updateInertiaTensor=function(){fk(this.hy)}; +I.prototype.getLinearVelocity=function(){return k(gk(this.hy),p)};I.prototype.getAngularVelocity=function(){return k(hk(this.hy),p)};I.prototype.setLinearVelocity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ik(c,a)};I.prototype.setAngularVelocity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jk(c,a)};I.prototype.getMotionState=function(){return k(kk(this.hy),gB)};I.prototype.setMotionState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lk(c,a)}; +I.prototype.getAngularFactor=function(){return k(mk(this.hy),p)};I.prototype.setAngularFactor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nk(c,a)};I.prototype.upcast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ok(c,a),I)};I.prototype.getAabb=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pk(d,a,c)};I.prototype.applyGravity=function(){qk(this.hy)};I.prototype.getGravity=function(){return k(rk(this.hy),p)}; +I.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sk(c,a)};I.prototype.getBroadphaseProxy=function(){return k(tk(this.hy),t)};I.prototype.clearForces=function(){uk(this.hy)};I.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);vk(d,a,c)};I.prototype.getCollisionShape=function(){return k(wk(this.hy),m)}; +I.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xk(c,a)};I.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yk(c,a)};I.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zk(c,a)};I.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Ak(c):Bk(c,a)};I.prototype.isActive=function(){return!!Ck(this.hy)};I.prototype.isKinematicObject=function(){return!!Dk(this.hy)}; +I.prototype.isStaticObject=function(){return!!Ek(this.hy)};I.prototype.isStaticOrKinematicObject=function(){return!!Fk(this.hy)};I.prototype.getRestitution=function(){return Gk(this.hy)};I.prototype.getFriction=function(){return Hk(this.hy)};I.prototype.getRollingFriction=function(){return Ik(this.hy)};I.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jk(c,a)};I.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kk(c,a)}; +I.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lk(c,a)};I.prototype.getWorldTransform=function(){return k(Mk(this.hy),r)};I.prototype.getCollisionFlags=function(){return Nk(this.hy)};I.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ok(c,a)};I.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pk(c,a)}; +I.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qk(c,a)};I.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rk(c,a)};I.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sk(c,a)};I.prototype.getUserIndex=function(){return Tk(this.hy)};I.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uk(c,a)}; +I.prototype.getUserPointer=function(){return k(Vk(this.hy),SA)};I.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wk(c,a)};I.prototype.getBroadphaseHandle=function(){return k(Xk(this.hy),t)};I.prototype.__destroy__=function(){Yk(this.hy)};function uB(){throw"cannot construct a btIndexedMeshArray, no constructor in IDL";}uB.prototype=Object.create(f.prototype);uB.prototype.constructor=uB;uB.prototype.iy=uB;uB.jy={};b.btIndexedMeshArray=uB; +uB.prototype.size=uB.prototype.size=function(){return Zk(this.hy)};uB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k($k(c,a),vB)};uB.prototype.__destroy__=function(){al(this.hy)};function wB(){this.hy=bl();h(wB)[this.hy]=this}wB.prototype=Object.create(f.prototype);wB.prototype.constructor=wB;wB.prototype.iy=wB;wB.jy={};b.btDbvtBroadphase=wB;wB.prototype.__destroy__=function(){cl(this.hy)}; +function xB(a,c,d,e,g,n,F,aa,ta){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);this.hy=dl(a,c,d,e,g,n,F,aa,ta);h(xB)[this.hy]=this}xB.prototype=Object.create(UA.prototype);xB.prototype.constructor=xB;xB.prototype.iy=xB;xB.jy={}; +b.btHeightfieldTerrainShape=xB;xB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);el(c,a)};xB.prototype.getMargin=function(){return fl(this.hy)};xB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gl(c,a)};xB.prototype.getLocalScaling=function(){return k(hl(this.hy),p)};xB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);il(d,a,c)}; +xB.prototype.__destroy__=function(){jl(this.hy)};function yB(){this.hy=kl();h(yB)[this.hy]=this}yB.prototype=Object.create(iB.prototype);yB.prototype.constructor=yB;yB.prototype.iy=yB;yB.jy={};b.btDefaultSoftBodySolver=yB;yB.prototype.__destroy__=function(){ll(this.hy)};function zB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=ml(a);h(zB)[this.hy]=this}zB.prototype=Object.create(OA.prototype);zB.prototype.constructor=zB;zB.prototype.iy=zB;zB.jy={};b.btCollisionDispatcher=zB; +zB.prototype.getNumManifolds=function(){return nl(this.hy)};zB.prototype.getManifoldByIndexInternal=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ol(c,a),dB)};zB.prototype.__destroy__=function(){pl(this.hy)}; +function AB(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===d?ql(a,c):void 0===e?rl(a,c,d):void 0===g?sl(a,c,d,e):tl(a,c,d,e,g);h(AB)[this.hy]=this}AB.prototype=Object.create(f.prototype);AB.prototype.constructor=AB;AB.prototype.iy=AB;AB.jy={};b.btAxisSweep3=AB;AB.prototype.__destroy__=function(){ul(this.hy)}; +function SA(){throw"cannot construct a VoidPtr, no constructor in IDL";}SA.prototype=Object.create(f.prototype);SA.prototype.constructor=SA;SA.prototype.iy=SA;SA.jy={};b.VoidPtr=SA;SA.prototype.__destroy__=function(){vl(this.hy)};function J(){this.hy=wl();h(J)[this.hy]=this}J.prototype=Object.create(f.prototype);J.prototype.constructor=J;J.prototype.iy=J;J.jy={};b.btSoftBodyWorldInfo=J;J.prototype.get_air_density=J.prototype.Yy=function(){return xl(this.hy)}; +J.prototype.set_air_density=J.prototype.FB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yl(c,a)};Object.defineProperty(J.prototype,"air_density",{get:J.prototype.Yy,set:J.prototype.FB});J.prototype.get_water_density=J.prototype.CB=function(){return zl(this.hy)};J.prototype.set_water_density=J.prototype.iE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Al(c,a)};Object.defineProperty(J.prototype,"water_density",{get:J.prototype.CB,set:J.prototype.iE}); +J.prototype.get_water_offset=J.prototype.EB=function(){return Bl(this.hy)};J.prototype.set_water_offset=J.prototype.kE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cl(c,a)};Object.defineProperty(J.prototype,"water_offset",{get:J.prototype.EB,set:J.prototype.kE});J.prototype.get_m_maxDisplacement=J.prototype.EA=function(){return Dl(this.hy)};J.prototype.set_m_maxDisplacement=J.prototype.kD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);El(c,a)}; +Object.defineProperty(J.prototype,"m_maxDisplacement",{get:J.prototype.EA,set:J.prototype.kD});J.prototype.get_water_normal=J.prototype.DB=function(){return k(Fl(this.hy),p)};J.prototype.set_water_normal=J.prototype.jE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gl(c,a)};Object.defineProperty(J.prototype,"water_normal",{get:J.prototype.DB,set:J.prototype.jE});J.prototype.get_m_broadphase=J.prototype.Gz=function(){return k(Hl(this.hy),QA)}; +J.prototype.set_m_broadphase=J.prototype.mC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Il(c,a)};Object.defineProperty(J.prototype,"m_broadphase",{get:J.prototype.Gz,set:J.prototype.mC});J.prototype.get_m_dispatcher=J.prototype.Xz=function(){return k(Jl(this.hy),OA)};J.prototype.set_m_dispatcher=J.prototype.DC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kl(c,a)};Object.defineProperty(J.prototype,"m_dispatcher",{get:J.prototype.Xz,set:J.prototype.DC}); +J.prototype.get_m_gravity=J.prototype.fA=function(){return k(Ll(this.hy),p)};J.prototype.set_m_gravity=J.prototype.MC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ml(c,a)};Object.defineProperty(J.prototype,"m_gravity",{get:J.prototype.fA,set:J.prototype.MC});J.prototype.__destroy__=function(){Nl(this.hy)}; +function BB(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===d?Ol(a,c):void 0===e?_emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_3(a,c,d):Pl(a,c,d,e);h(BB)[this.hy]=this}BB.prototype=Object.create(TA.prototype);BB.prototype.constructor=BB;BB.prototype.iy=BB;BB.jy={};b.btConeTwistConstraint=BB; +BB.prototype.setLimit=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ql(d,a,c)};BB.prototype.setAngularOnly=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rl(c,a)};BB.prototype.setDamping=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sl(c,a)};BB.prototype.enableMotor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tl(c,a)}; +BB.prototype.setMaxMotorImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ul(c,a)};BB.prototype.setMaxMotorImpulseNormalized=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vl(c,a)};BB.prototype.setMotorTarget=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wl(c,a)};BB.prototype.setMotorTargetInConstraintSpace=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xl(c,a)}; +BB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yl(c,a)};BB.prototype.getBreakingImpulseThreshold=function(){return Zl(this.hy)};BB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$l(c,a)};BB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return am(d,a,c)}; +BB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);bm(e,a,c,d)};BB.prototype.__destroy__=function(){cm(this.hy)}; +function CB(a,c,d,e,g,n,F){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);this.hy=void 0===d?dm(a,c):void 0===e?em(a,c,d):void 0===g?fm(a,c,d,e):void 0===n?gm(a,c,d,e,g):void 0===F?hm(a,c,d,e,g,n):im(a,c,d,e,g,n,F);h(CB)[this.hy]=this}CB.prototype=Object.create(TA.prototype);CB.prototype.constructor=CB; +CB.prototype.iy=CB;CB.jy={};b.btHingeConstraint=CB;CB.prototype.setLimit=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);void 0===g?jm(n,a,c,d,e):km(n,a,c,d,e,g)};CB.prototype.enableAngularMotor=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);lm(e,a,c,d)}; +CB.prototype.setAngularOnly=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mm(c,a)};CB.prototype.enableMotor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nm(c,a)};CB.prototype.setMaxMotorImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);om(c,a)};CB.prototype.setMotorTarget=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pm(d,a,c)}; +CB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qm(c,a)};CB.prototype.getBreakingImpulseThreshold=function(){return rm(this.hy)};CB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sm(c,a)};CB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return tm(d,a,c)}; +CB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);um(e,a,c,d)};CB.prototype.__destroy__=function(){wm(this.hy)};function DB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=xm(a,c);h(DB)[this.hy]=this}DB.prototype=Object.create(YA.prototype);DB.prototype.constructor=DB;DB.prototype.iy=DB;DB.jy={};b.btConeShapeZ=DB; +DB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ym(c,a)};DB.prototype.getLocalScaling=function(){return k(zm(this.hy),p)};DB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Am(d,a,c)};DB.prototype.__destroy__=function(){Bm(this.hy)};function EB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Cm(a,c);h(EB)[this.hy]=this}EB.prototype=Object.create(YA.prototype); +EB.prototype.constructor=EB;EB.prototype.iy=EB;EB.jy={};b.btConeShapeX=EB;EB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dm(c,a)};EB.prototype.getLocalScaling=function(){return k(Em(this.hy),p)};EB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Fm(d,a,c)};EB.prototype.__destroy__=function(){Gm(this.hy)}; +function FB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Hm():void 0===c?Im(a):Jm(a,c);h(FB)[this.hy]=this}FB.prototype=Object.create(fB.prototype);FB.prototype.constructor=FB;FB.prototype.iy=FB;FB.jy={};b.btTriangleMesh=FB;FB.prototype.addTriangle=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);void 0===e?Km(g,a,c,d):Lm(g,a,c,d,e)}; +FB.prototype.findOrAddVertex=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Mm(d,a,c)};FB.prototype.addIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nm(c,a)};FB.prototype.getIndexedMeshArray=function(){return k(Om(this.hy),uB)};FB.prototype.setScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pm(c,a)};FB.prototype.__destroy__=function(){Qm(this.hy)}; +function GB(a,c){IA();"object"==typeof a&&(a=MA(a));c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Rm():void 0===c?Sm(a):Tm(a,c);h(GB)[this.hy]=this}GB.prototype=Object.create(m.prototype);GB.prototype.constructor=GB;GB.prototype.iy=GB;GB.jy={};b.btConvexHullShape=GB;GB.prototype.addPoint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Um(d,a):Vm(d,a,c)}; +GB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wm(c,a)};GB.prototype.getMargin=function(){return Xm(this.hy)};GB.prototype.getNumVertices=function(){return Ym(this.hy)};GB.prototype.initializePolyhedralFeatures=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return!!Zm(c,a)};GB.prototype.recalcLocalAabb=function(){$m(this.hy)};GB.prototype.getConvexPolyhedron=function(){return k(an(this.hy),HB)}; +GB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bn(c,a)};GB.prototype.getLocalScaling=function(){return k(cn(this.hy),p)};GB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dn(d,a,c)};GB.prototype.__destroy__=function(){en(this.hy)};function K(){this.hy=fn();h(K)[this.hy]=this}K.prototype=Object.create(f.prototype);K.prototype.constructor=K;K.prototype.iy=K;K.jy={}; +b.btVehicleTuning=K;K.prototype.get_m_suspensionStiffness=K.prototype.wy=function(){return gn(this.hy)};K.prototype.set_m_suspensionStiffness=K.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hn(c,a)};Object.defineProperty(K.prototype,"m_suspensionStiffness",{get:K.prototype.wy,set:K.prototype.Dy});K.prototype.get_m_suspensionCompression=K.prototype.bB=function(){return jn(this.hy)}; +K.prototype.set_m_suspensionCompression=K.prototype.ID=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kn(c,a)};Object.defineProperty(K.prototype,"m_suspensionCompression",{get:K.prototype.bB,set:K.prototype.ID});K.prototype.get_m_suspensionDamping=K.prototype.cB=function(){return ln(this.hy)};K.prototype.set_m_suspensionDamping=K.prototype.JD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mn(c,a)}; +Object.defineProperty(K.prototype,"m_suspensionDamping",{get:K.prototype.cB,set:K.prototype.JD});K.prototype.get_m_maxSuspensionTravelCm=K.prototype.vy=function(){return nn(this.hy)};K.prototype.set_m_maxSuspensionTravelCm=K.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);on(c,a)};Object.defineProperty(K.prototype,"m_maxSuspensionTravelCm",{get:K.prototype.vy,set:K.prototype.Cy});K.prototype.get_m_frictionSlip=K.prototype.ry=function(){return pn(this.hy)}; +K.prototype.set_m_frictionSlip=K.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qn(c,a)};Object.defineProperty(K.prototype,"m_frictionSlip",{get:K.prototype.ry,set:K.prototype.yy});K.prototype.get_m_maxSuspensionForce=K.prototype.uy=function(){return rn(this.hy)};K.prototype.set_m_maxSuspensionForce=K.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sn(c,a)};Object.defineProperty(K.prototype,"m_maxSuspensionForce",{get:K.prototype.uy,set:K.prototype.By}); +function IB(){throw"cannot construct a btCollisionObjectWrapper, no constructor in IDL";}IB.prototype=Object.create(f.prototype);IB.prototype.constructor=IB;IB.prototype.iy=IB;IB.jy={};b.btCollisionObjectWrapper=IB;IB.prototype.getWorldTransform=function(){return k(tn(this.hy),r)};IB.prototype.getCollisionObject=function(){return k(un(this.hy),q)};IB.prototype.getCollisionShape=function(){return k(vn(this.hy),m)};function JB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=wn(a);h(JB)[this.hy]=this} +JB.prototype=Object.create(f.prototype);JB.prototype.constructor=JB;JB.prototype.iy=JB;JB.jy={};b.btShapeHull=JB;JB.prototype.buildHull=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return!!xn(c,a)};JB.prototype.numVertices=function(){return yn(this.hy)};JB.prototype.getVertexPointer=function(){return k(zn(this.hy),p)};JB.prototype.__destroy__=function(){An(this.hy)}; +function KB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Bn():void 0===c?Cn(a):Dn(a,c);h(KB)[this.hy]=this}KB.prototype=Object.create(gB.prototype);KB.prototype.constructor=KB;KB.prototype.iy=KB;KB.jy={};b.btDefaultMotionState=KB;KB.prototype.getWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);En(c,a)};KB.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fn(c,a)}; +KB.prototype.get_m_graphicsWorldTrans=KB.prototype.eA=function(){return k(Gn(this.hy),r)};KB.prototype.set_m_graphicsWorldTrans=KB.prototype.LC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hn(c,a)};Object.defineProperty(KB.prototype,"m_graphicsWorldTrans",{get:KB.prototype.eA,set:KB.prototype.LC});KB.prototype.__destroy__=function(){In(this.hy)};function L(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Jn(a);h(L)[this.hy]=this}L.prototype=Object.create(f.prototype); +L.prototype.constructor=L;L.prototype.iy=L;L.jy={};b.btWheelInfo=L;L.prototype.getSuspensionRestLength=function(){return Kn(this.hy)};L.prototype.updateWheel=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ln(d,a,c)};L.prototype.get_m_suspensionStiffness=L.prototype.wy=function(){return Mn(this.hy)};L.prototype.set_m_suspensionStiffness=L.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nn(c,a)}; +Object.defineProperty(L.prototype,"m_suspensionStiffness",{get:L.prototype.wy,set:L.prototype.Dy});L.prototype.get_m_frictionSlip=L.prototype.ry=function(){return On(this.hy)};L.prototype.set_m_frictionSlip=L.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pn(c,a)};Object.defineProperty(L.prototype,"m_frictionSlip",{get:L.prototype.ry,set:L.prototype.yy});L.prototype.get_m_engineForce=L.prototype.aA=function(){return Qn(this.hy)}; +L.prototype.set_m_engineForce=L.prototype.HC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rn(c,a)};Object.defineProperty(L.prototype,"m_engineForce",{get:L.prototype.aA,set:L.prototype.HC});L.prototype.get_m_rollInfluence=L.prototype.SA=function(){return Sn(this.hy)};L.prototype.set_m_rollInfluence=L.prototype.yD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tn(c,a)};Object.defineProperty(L.prototype,"m_rollInfluence",{get:L.prototype.SA,set:L.prototype.yD}); +L.prototype.get_m_suspensionRestLength1=L.prototype.gB=function(){return Un(this.hy)};L.prototype.set_m_suspensionRestLength1=L.prototype.ND=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vn(c,a)};Object.defineProperty(L.prototype,"m_suspensionRestLength1",{get:L.prototype.gB,set:L.prototype.ND});L.prototype.get_m_wheelsRadius=L.prototype.uB=function(){return Wn(this.hy)};L.prototype.set_m_wheelsRadius=L.prototype.aE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xn(c,a)}; +Object.defineProperty(L.prototype,"m_wheelsRadius",{get:L.prototype.uB,set:L.prototype.aE});L.prototype.get_m_wheelsDampingCompression=L.prototype.My=function(){return Yn(this.hy)};L.prototype.set_m_wheelsDampingCompression=L.prototype.Vy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zn(c,a)};Object.defineProperty(L.prototype,"m_wheelsDampingCompression",{get:L.prototype.My,set:L.prototype.Vy});L.prototype.get_m_wheelsDampingRelaxation=L.prototype.Ny=function(){return $n(this.hy)}; +L.prototype.set_m_wheelsDampingRelaxation=L.prototype.Wy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ao(c,a)};Object.defineProperty(L.prototype,"m_wheelsDampingRelaxation",{get:L.prototype.Ny,set:L.prototype.Wy});L.prototype.get_m_steering=L.prototype.$A=function(){return bo(this.hy)};L.prototype.set_m_steering=L.prototype.GD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);co(c,a)};Object.defineProperty(L.prototype,"m_steering",{get:L.prototype.$A,set:L.prototype.GD}); +L.prototype.get_m_maxSuspensionForce=L.prototype.uy=function(){return eo(this.hy)};L.prototype.set_m_maxSuspensionForce=L.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fo(c,a)};Object.defineProperty(L.prototype,"m_maxSuspensionForce",{get:L.prototype.uy,set:L.prototype.By});L.prototype.get_m_maxSuspensionTravelCm=L.prototype.vy=function(){return go(this.hy)}; +L.prototype.set_m_maxSuspensionTravelCm=L.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ho(c,a)};Object.defineProperty(L.prototype,"m_maxSuspensionTravelCm",{get:L.prototype.vy,set:L.prototype.Cy});L.prototype.get_m_wheelsSuspensionForce=L.prototype.vB=function(){return io(this.hy)};L.prototype.set_m_wheelsSuspensionForce=L.prototype.bE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jo(c,a)}; +Object.defineProperty(L.prototype,"m_wheelsSuspensionForce",{get:L.prototype.vB,set:L.prototype.bE});L.prototype.get_m_bIsFrontWheel=L.prototype.Fy=function(){return!!ko(this.hy)};L.prototype.set_m_bIsFrontWheel=L.prototype.Oy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lo(c,a)};Object.defineProperty(L.prototype,"m_bIsFrontWheel",{get:L.prototype.Fy,set:L.prototype.Oy});L.prototype.get_m_raycastInfo=L.prototype.QA=function(){return k(mo(this.hy),M)}; +L.prototype.set_m_raycastInfo=L.prototype.wD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);no(c,a)};Object.defineProperty(L.prototype,"m_raycastInfo",{get:L.prototype.QA,set:L.prototype.wD});L.prototype.get_m_chassisConnectionPointCS=L.prototype.Mz=function(){return k(oo(this.hy),p)};L.prototype.set_m_chassisConnectionPointCS=L.prototype.sC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);po(c,a)}; +Object.defineProperty(L.prototype,"m_chassisConnectionPointCS",{get:L.prototype.Mz,set:L.prototype.sC});L.prototype.get_m_worldTransform=L.prototype.wB=function(){return k(qo(this.hy),r)};L.prototype.set_m_worldTransform=L.prototype.cE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ro(c,a)};Object.defineProperty(L.prototype,"m_worldTransform",{get:L.prototype.wB,set:L.prototype.cE});L.prototype.get_m_wheelDirectionCS=L.prototype.Ly=function(){return k(so(this.hy),p)}; +L.prototype.set_m_wheelDirectionCS=L.prototype.Uy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);to(c,a)};Object.defineProperty(L.prototype,"m_wheelDirectionCS",{get:L.prototype.Ly,set:L.prototype.Uy});L.prototype.get_m_wheelAxleCS=L.prototype.Ky=function(){return k(uo(this.hy),p)};L.prototype.set_m_wheelAxleCS=L.prototype.Ty=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vo(c,a)};Object.defineProperty(L.prototype,"m_wheelAxleCS",{get:L.prototype.Ky,set:L.prototype.Ty}); +L.prototype.get_m_rotation=L.prototype.UA=function(){return wo(this.hy)};L.prototype.set_m_rotation=L.prototype.AD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xo(c,a)};Object.defineProperty(L.prototype,"m_rotation",{get:L.prototype.UA,set:L.prototype.AD});L.prototype.get_m_deltaRotation=L.prototype.Vz=function(){return yo(this.hy)};L.prototype.set_m_deltaRotation=L.prototype.BC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zo(c,a)}; +Object.defineProperty(L.prototype,"m_deltaRotation",{get:L.prototype.Vz,set:L.prototype.BC});L.prototype.get_m_brake=L.prototype.Fz=function(){return Ao(this.hy)};L.prototype.set_m_brake=L.prototype.lC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bo(c,a)};Object.defineProperty(L.prototype,"m_brake",{get:L.prototype.Fz,set:L.prototype.lC});L.prototype.get_m_clippedInvContactDotSuspension=L.prototype.Nz=function(){return Co(this.hy)}; +L.prototype.set_m_clippedInvContactDotSuspension=L.prototype.tC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Do(c,a)};Object.defineProperty(L.prototype,"m_clippedInvContactDotSuspension",{get:L.prototype.Nz,set:L.prototype.tC});L.prototype.get_m_suspensionRelativeVelocity=L.prototype.eB=function(){return Eo(this.hy)};L.prototype.set_m_suspensionRelativeVelocity=L.prototype.LD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fo(c,a)}; +Object.defineProperty(L.prototype,"m_suspensionRelativeVelocity",{get:L.prototype.eB,set:L.prototype.LD});L.prototype.get_m_skidInfo=L.prototype.XA=function(){return Go(this.hy)};L.prototype.set_m_skidInfo=L.prototype.DD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ho(c,a)};Object.defineProperty(L.prototype,"m_skidInfo",{get:L.prototype.XA,set:L.prototype.DD});L.prototype.__destroy__=function(){Io(this.hy)}; +function N(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===a?Jo():void 0===c?_emscripten_bind_btVector4_btVector4_1(a):void 0===d?_emscripten_bind_btVector4_btVector4_2(a,c):void 0===e?_emscripten_bind_btVector4_btVector4_3(a,c,d):Ko(a,c,d,e);h(N)[this.hy]=this}N.prototype=Object.create(p.prototype);N.prototype.constructor=N;N.prototype.iy=N;N.jy={};b.btVector4=N;N.prototype.w=function(){return Lo(this.hy)}; +N.prototype.setValue=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);Mo(g,a,c,d,e)};N.prototype.length=N.prototype.length=function(){return No(this.hy)};N.prototype.x=N.prototype.x=function(){return Oo(this.hy)};N.prototype.y=N.prototype.y=function(){return Po(this.hy)};N.prototype.z=N.prototype.z=function(){return Qo(this.hy)}; +N.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ro(c,a)};N.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);So(c,a)};N.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);To(c,a)};N.prototype.normalize=N.prototype.normalize=function(){Uo(this.hy)};N.prototype.rotate=N.prototype.rotate=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return k(Vo(d,a,c),p)}; +N.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Wo(c,a)};N.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Xo(c,a),p)};N.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Yo(c,a),p)};N.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Zo(c,a),p)};N.prototype.__destroy__=function(){$o(this.hy)};function LB(){this.hy=ap();h(LB)[this.hy]=this}LB.prototype=Object.create(f.prototype); +LB.prototype.constructor=LB;LB.prototype.iy=LB;LB.jy={};b.btDefaultCollisionConstructionInfo=LB;LB.prototype.__destroy__=function(){bp(this.hy)};function O(){throw"cannot construct a Anchor, no constructor in IDL";}O.prototype=Object.create(f.prototype);O.prototype.constructor=O;O.prototype.iy=O;O.jy={};b.Anchor=O;O.prototype.get_m_node=O.prototype.FA=function(){return k(cp(this.hy),Node)};O.prototype.set_m_node=O.prototype.lD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dp(c,a)}; +Object.defineProperty(O.prototype,"m_node",{get:O.prototype.FA,set:O.prototype.lD});O.prototype.get_m_local=O.prototype.zA=function(){return k(ep(this.hy),p)};O.prototype.set_m_local=O.prototype.fD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fp(c,a)};Object.defineProperty(O.prototype,"m_local",{get:O.prototype.zA,set:O.prototype.fD});O.prototype.get_m_body=O.prototype.Ez=function(){return k(gp(this.hy),I)}; +O.prototype.set_m_body=O.prototype.kC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hp(c,a)};Object.defineProperty(O.prototype,"m_body",{get:O.prototype.Ez,set:O.prototype.kC});O.prototype.get_m_influence=O.prototype.sA=function(){return ip(this.hy)};O.prototype.set_m_influence=O.prototype.ZC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jp(c,a)};Object.defineProperty(O.prototype,"m_influence",{get:O.prototype.sA,set:O.prototype.ZC}); +O.prototype.get_m_c0=O.prototype.Hz=function(){return k(kp(this.hy),jB)};O.prototype.set_m_c0=O.prototype.nC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lp(c,a)};Object.defineProperty(O.prototype,"m_c0",{get:O.prototype.Hz,set:O.prototype.nC});O.prototype.get_m_c1=O.prototype.Iz=function(){return k(mp(this.hy),p)};O.prototype.set_m_c1=O.prototype.oC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);np(c,a)};Object.defineProperty(O.prototype,"m_c1",{get:O.prototype.Iz,set:O.prototype.oC}); +O.prototype.get_m_c2=O.prototype.Jz=function(){return op(this.hy)};O.prototype.set_m_c2=O.prototype.pC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pp(c,a)};Object.defineProperty(O.prototype,"m_c2",{get:O.prototype.Jz,set:O.prototype.pC});O.prototype.__destroy__=function(){qp(this.hy)};function P(){throw"cannot construct a btVehicleRaycasterResult, no constructor in IDL";}P.prototype=Object.create(f.prototype);P.prototype.constructor=P;P.prototype.iy=P;P.jy={}; +b.btVehicleRaycasterResult=P;P.prototype.get_m_hitPointInWorld=P.prototype.nA=function(){return k(rp(this.hy),p)};P.prototype.set_m_hitPointInWorld=P.prototype.UC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sp(c,a)};Object.defineProperty(P.prototype,"m_hitPointInWorld",{get:P.prototype.nA,set:P.prototype.UC});P.prototype.get_m_hitNormalInWorld=P.prototype.lA=function(){return k(tp(this.hy),p)}; +P.prototype.set_m_hitNormalInWorld=P.prototype.SC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);up(c,a)};Object.defineProperty(P.prototype,"m_hitNormalInWorld",{get:P.prototype.lA,set:P.prototype.SC});P.prototype.get_m_distFraction=P.prototype.Yz=function(){return vp(this.hy)};P.prototype.set_m_distFraction=P.prototype.EC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wp(c,a)};Object.defineProperty(P.prototype,"m_distFraction",{get:P.prototype.Yz,set:P.prototype.EC}); +P.prototype.__destroy__=function(){xp(this.hy)};function pB(){throw"cannot construct a btVector3Array, no constructor in IDL";}pB.prototype=Object.create(f.prototype);pB.prototype.constructor=pB;pB.prototype.iy=pB;pB.jy={};b.btVector3Array=pB;pB.prototype.size=pB.prototype.size=function(){return yp(this.hy)};pB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(zp(c,a),p)};pB.prototype.__destroy__=function(){Ap(this.hy)}; +function MB(){throw"cannot construct a btConstraintSolver, no constructor in IDL";}MB.prototype=Object.create(f.prototype);MB.prototype.constructor=MB;MB.prototype.iy=MB;MB.jy={};b.btConstraintSolver=MB;MB.prototype.__destroy__=function(){Bp(this.hy)};function Q(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=Cp(a,c,d);h(Q)[this.hy]=this}Q.prototype=Object.create(ZA.prototype);Q.prototype.constructor=Q;Q.prototype.iy=Q;Q.jy={}; +b.btRaycastVehicle=Q;Q.prototype.applyEngineForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Dp(d,a,c)};Q.prototype.setSteeringValue=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ep(d,a,c)};Q.prototype.getWheelTransformWS=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Fp(c,a),r)}; +Q.prototype.updateWheelTransform=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Gp(d,a,c)};Q.prototype.addWheel=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return k(Hp(aa,a,c,d,e,g,n,F),L)};Q.prototype.getNumWheels=function(){return Ip(this.hy)}; +Q.prototype.getRigidBody=function(){return k(Jp(this.hy),I)};Q.prototype.getWheelInfo=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Kp(c,a),L)};Q.prototype.setBrake=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Lp(d,a,c)};Q.prototype.setCoordinateSystem=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Mp(e,a,c,d)};Q.prototype.getCurrentSpeedKmHour=function(){return Np(this.hy)}; +Q.prototype.getChassisWorldTransform=function(){return k(Op(this.hy),r)};Q.prototype.rayCast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Pp(c,a)};Q.prototype.updateVehicle=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qp(c,a)};Q.prototype.resetSuspension=function(){Rp(this.hy)};Q.prototype.getSteeringValue=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Sp(c,a)}; +Q.prototype.updateWheelTransformsWS=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Tp(d,a):Up(d,a,c)};Q.prototype.setPitchControl=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vp(c,a)};Q.prototype.updateSuspension=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wp(c,a)};Q.prototype.updateFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xp(c,a)};Q.prototype.getRightAxis=function(){return Yp(this.hy)}; +Q.prototype.getUpAxis=function(){return Zp(this.hy)};Q.prototype.getForwardAxis=function(){return $p(this.hy)};Q.prototype.getForwardVector=function(){return k(aq(this.hy),p)};Q.prototype.getUserConstraintType=function(){return bq(this.hy)};Q.prototype.setUserConstraintType=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cq(c,a)};Q.prototype.setUserConstraintId=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dq(c,a)};Q.prototype.getUserConstraintId=function(){return eq(this.hy)}; +Q.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);fq(d,a,c)};Q.prototype.__destroy__=function(){gq(this.hy)};function NB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=hq(a);h(NB)[this.hy]=this}NB.prototype=Object.create(bB.prototype);NB.prototype.constructor=NB;NB.prototype.iy=NB;NB.jy={};b.btCylinderShapeX=NB;NB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);iq(c,a)};NB.prototype.getMargin=function(){return jq(this.hy)}; +NB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kq(c,a)};NB.prototype.getLocalScaling=function(){return k(lq(this.hy),p)};NB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);mq(d,a,c)};NB.prototype.__destroy__=function(){nq(this.hy)};function OB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=oq(a);h(OB)[this.hy]=this}OB.prototype=Object.create(bB.prototype);OB.prototype.constructor=OB; +OB.prototype.iy=OB;OB.jy={};b.btCylinderShapeZ=OB;OB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pq(c,a)};OB.prototype.getMargin=function(){return qq(this.hy)};OB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rq(c,a)};OB.prototype.getLocalScaling=function(){return k(sq(this.hy),p)};OB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tq(d,a,c)}; +OB.prototype.__destroy__=function(){uq(this.hy)};function HB(){throw"cannot construct a btConvexPolyhedron, no constructor in IDL";}HB.prototype=Object.create(f.prototype);HB.prototype.constructor=HB;HB.prototype.iy=HB;HB.jy={};b.btConvexPolyhedron=HB;HB.prototype.get_m_vertices=HB.prototype.qB=function(){return k(vq(this.hy),pB)};HB.prototype.set_m_vertices=HB.prototype.XD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wq(c,a)}; +Object.defineProperty(HB.prototype,"m_vertices",{get:HB.prototype.qB,set:HB.prototype.XD});HB.prototype.get_m_faces=HB.prototype.Gy=function(){return k(xq(this.hy),PB)};HB.prototype.set_m_faces=HB.prototype.Py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yq(c,a)};Object.defineProperty(HB.prototype,"m_faces",{get:HB.prototype.Gy,set:HB.prototype.Py});HB.prototype.__destroy__=function(){zq(this.hy)};function QB(){this.hy=Aq();h(QB)[this.hy]=this}QB.prototype=Object.create(f.prototype); +QB.prototype.constructor=QB;QB.prototype.iy=QB;QB.jy={};b.btSequentialImpulseConstraintSolver=QB;QB.prototype.__destroy__=function(){Bq(this.hy)};function RB(){throw"cannot construct a tAnchorArray, no constructor in IDL";}RB.prototype=Object.create(f.prototype);RB.prototype.constructor=RB;RB.prototype.iy=RB;RB.jy={};b.tAnchorArray=RB;RB.prototype.size=RB.prototype.size=function(){return Cq(this.hy)};RB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Dq(c,a),O)}; +RB.prototype.clear=RB.prototype.clear=function(){Eq(this.hy)};RB.prototype.push_back=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fq(c,a)};RB.prototype.pop_back=function(){Gq(this.hy)};RB.prototype.__destroy__=function(){Hq(this.hy)};function M(){throw"cannot construct a RaycastInfo, no constructor in IDL";}M.prototype=Object.create(f.prototype);M.prototype.constructor=M;M.prototype.iy=M;M.jy={};b.RaycastInfo=M; +M.prototype.get_m_contactNormalWS=M.prototype.Pz=function(){return k(Iq(this.hy),p)};M.prototype.set_m_contactNormalWS=M.prototype.vC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jq(c,a)};Object.defineProperty(M.prototype,"m_contactNormalWS",{get:M.prototype.Pz,set:M.prototype.vC});M.prototype.get_m_contactPointWS=M.prototype.Qz=function(){return k(Kq(this.hy),p)};M.prototype.set_m_contactPointWS=M.prototype.wC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lq(c,a)}; +Object.defineProperty(M.prototype,"m_contactPointWS",{get:M.prototype.Qz,set:M.prototype.wC});M.prototype.get_m_suspensionLength=M.prototype.dB=function(){return Mq(this.hy)};M.prototype.set_m_suspensionLength=M.prototype.KD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nq(c,a)};Object.defineProperty(M.prototype,"m_suspensionLength",{get:M.prototype.dB,set:M.prototype.KD});M.prototype.get_m_hardPointWS=M.prototype.hA=function(){return k(Oq(this.hy),p)}; +M.prototype.set_m_hardPointWS=M.prototype.OC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pq(c,a)};Object.defineProperty(M.prototype,"m_hardPointWS",{get:M.prototype.hA,set:M.prototype.OC});M.prototype.get_m_wheelDirectionWS=M.prototype.sB=function(){return k(Qq(this.hy),p)};M.prototype.set_m_wheelDirectionWS=M.prototype.ZD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rq(c,a)};Object.defineProperty(M.prototype,"m_wheelDirectionWS",{get:M.prototype.sB,set:M.prototype.ZD}); +M.prototype.get_m_wheelAxleWS=M.prototype.rB=function(){return k(Sq(this.hy),p)};M.prototype.set_m_wheelAxleWS=M.prototype.YD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tq(c,a)};Object.defineProperty(M.prototype,"m_wheelAxleWS",{get:M.prototype.rB,set:M.prototype.YD});M.prototype.get_m_isInContact=M.prototype.tA=function(){return!!Uq(this.hy)};M.prototype.set_m_isInContact=M.prototype.$C=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vq(c,a)}; +Object.defineProperty(M.prototype,"m_isInContact",{get:M.prototype.tA,set:M.prototype.$C});M.prototype.get_m_groundObject=M.prototype.gA=function(){return Wq(this.hy)};M.prototype.set_m_groundObject=M.prototype.NC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xq(c,a)};Object.defineProperty(M.prototype,"m_groundObject",{get:M.prototype.gA,set:M.prototype.NC});M.prototype.__destroy__=function(){Yq(this.hy)}; +function SB(a,c,d){IA();a&&"object"===typeof a&&(a=a.hy);"object"==typeof c&&(c=MA(c));d&&"object"===typeof d&&(d=d.hy);this.hy=Zq(a,c,d);h(SB)[this.hy]=this}SB.prototype=Object.create(m.prototype);SB.prototype.constructor=SB;SB.prototype.iy=SB;SB.jy={};b.btMultiSphereShape=SB;SB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$q(c,a)};SB.prototype.getLocalScaling=function(){return k(ar(this.hy),p)}; +SB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);br(d,a,c)};SB.prototype.__destroy__=function(){cr(this.hy)};function R(a,c,d,e){IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);"object"==typeof e&&(e=MA(e));this.hy=dr(a,c,d,e);h(R)[this.hy]=this}R.prototype=Object.create(q.prototype);R.prototype.constructor=R;R.prototype.iy=R;R.jy={};b.btSoftBody=R; +R.prototype.checkLink=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return!!er(d,a,c)};R.prototype.checkFace=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return!!fr(e,a,c,d)};R.prototype.appendMaterial=function(){return k(gr(this.hy),A)};R.prototype.appendNode=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);hr(d,a,c)}; +R.prototype.appendLink=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);ir(g,a,c,d,e)};R.prototype.appendFace=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);jr(g,a,c,d,e)}; +R.prototype.appendTetra=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);kr(n,a,c,d,e,g)};R.prototype.appendAnchor=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);lr(g,a,c,d,e)}; +R.prototype.addForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?mr(d,a):nr(d,a,c)};R.prototype.addAeroForceToNode=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);or(d,a,c)};R.prototype.getTotalMass=function(){return pr(this.hy)};R.prototype.setTotalMass=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);qr(d,a,c)}; +R.prototype.setMass=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);rr(d,a,c)};R.prototype.transform=R.prototype.transform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sr(c,a)};R.prototype.translate=R.prototype.translate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tr(c,a)};R.prototype.rotate=R.prototype.rotate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ur(c,a)}; +R.prototype.scale=R.prototype.scale=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vr(c,a)};R.prototype.generateClusters=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return void 0===c?wr(d,a):xr(d,a,c)};R.prototype.generateBendingConstraints=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return yr(d,a,c)}; +R.prototype.upcast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(zr(c,a),R)};R.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ar(d,a,c)};R.prototype.getCollisionShape=function(){return k(Br(this.hy),m)};R.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cr(c,a)}; +R.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dr(c,a)};R.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Er(c,a)};R.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Fr(c):Gr(c,a)};R.prototype.isActive=function(){return!!Hr(this.hy)};R.prototype.isKinematicObject=function(){return!!Ir(this.hy)};R.prototype.isStaticObject=function(){return!!Jr(this.hy)}; +R.prototype.isStaticOrKinematicObject=function(){return!!Kr(this.hy)};R.prototype.getRestitution=function(){return Lr(this.hy)};R.prototype.getFriction=function(){return Mr(this.hy)};R.prototype.getRollingFriction=function(){return Nr(this.hy)};R.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Or(c,a)};R.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pr(c,a)}; +R.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qr(c,a)};R.prototype.getWorldTransform=function(){return k(Rr(this.hy),r)};R.prototype.getCollisionFlags=function(){return Sr(this.hy)};R.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tr(c,a)};R.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ur(c,a)}; +R.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vr(c,a)};R.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wr(c,a)};R.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xr(c,a)};R.prototype.getUserIndex=function(){return Yr(this.hy)};R.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zr(c,a)}; +R.prototype.getUserPointer=function(){return k($r(this.hy),SA)};R.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);as(c,a)};R.prototype.getBroadphaseHandle=function(){return k(bs(this.hy),t)};R.prototype.get_m_cfg=R.prototype.Kz=function(){return k(cs(this.hy),S)};R.prototype.set_m_cfg=R.prototype.qC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ds(c,a)};Object.defineProperty(R.prototype,"m_cfg",{get:R.prototype.Kz,set:R.prototype.qC}); +R.prototype.get_m_nodes=R.prototype.GA=function(){return k(es(this.hy),TB)};R.prototype.set_m_nodes=R.prototype.mD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gs(c,a)};Object.defineProperty(R.prototype,"m_nodes",{get:R.prototype.GA,set:R.prototype.mD});R.prototype.get_m_faces=R.prototype.Gy=function(){return k(hs(this.hy),UB)};R.prototype.set_m_faces=R.prototype.Py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);is(c,a)}; +Object.defineProperty(R.prototype,"m_faces",{get:R.prototype.Gy,set:R.prototype.Py});R.prototype.get_m_materials=R.prototype.DA=function(){return k(js(this.hy),qB)};R.prototype.set_m_materials=R.prototype.jD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ks(c,a)};Object.defineProperty(R.prototype,"m_materials",{get:R.prototype.DA,set:R.prototype.jD});R.prototype.get_m_anchors=R.prototype.Az=function(){return k(ls(this.hy),RB)}; +R.prototype.set_m_anchors=R.prototype.gC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ms(c,a)};Object.defineProperty(R.prototype,"m_anchors",{get:R.prototype.Az,set:R.prototype.gC});R.prototype.__destroy__=function(){ns(this.hy)};function VB(){throw"cannot construct a btIntArray, no constructor in IDL";}VB.prototype=Object.create(f.prototype);VB.prototype.constructor=VB;VB.prototype.iy=VB;VB.jy={};b.btIntArray=VB;VB.prototype.size=VB.prototype.size=function(){return ps(this.hy)}; +VB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return qs(c,a)};VB.prototype.__destroy__=function(){rs(this.hy)};function S(){throw"cannot construct a Config, no constructor in IDL";}S.prototype=Object.create(f.prototype);S.prototype.constructor=S;S.prototype.iy=S;S.jy={};b.Config=S;S.prototype.get_kVCF=S.prototype.sz=function(){return ss(this.hy)};S.prototype.set_kVCF=S.prototype.$B=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ts(c,a)}; +Object.defineProperty(S.prototype,"kVCF",{get:S.prototype.sz,set:S.prototype.$B});S.prototype.get_kDP=S.prototype.fz=function(){return us(this.hy)};S.prototype.set_kDP=S.prototype.NB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vs(c,a)};Object.defineProperty(S.prototype,"kDP",{get:S.prototype.fz,set:S.prototype.NB});S.prototype.get_kDG=S.prototype.ez=function(){return xs(this.hy)};S.prototype.set_kDG=S.prototype.MB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ys(c,a)}; +Object.defineProperty(S.prototype,"kDG",{get:S.prototype.ez,set:S.prototype.MB});S.prototype.get_kLF=S.prototype.hz=function(){return zs(this.hy)};S.prototype.set_kLF=S.prototype.PB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);As(c,a)};Object.defineProperty(S.prototype,"kLF",{get:S.prototype.hz,set:S.prototype.PB});S.prototype.get_kPR=S.prototype.jz=function(){return Bs(this.hy)};S.prototype.set_kPR=S.prototype.RB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cs(c,a)}; +Object.defineProperty(S.prototype,"kPR",{get:S.prototype.jz,set:S.prototype.RB});S.prototype.get_kVC=S.prototype.rz=function(){return Ds(this.hy)};S.prototype.set_kVC=S.prototype.ZB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Es(c,a)};Object.defineProperty(S.prototype,"kVC",{get:S.prototype.rz,set:S.prototype.ZB});S.prototype.get_kDF=S.prototype.dz=function(){return Fs(this.hy)};S.prototype.set_kDF=S.prototype.LB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gs(c,a)}; +Object.defineProperty(S.prototype,"kDF",{get:S.prototype.dz,set:S.prototype.LB});S.prototype.get_kMT=S.prototype.iz=function(){return Hs(this.hy)};S.prototype.set_kMT=S.prototype.QB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Is(c,a)};Object.defineProperty(S.prototype,"kMT",{get:S.prototype.iz,set:S.prototype.QB});S.prototype.get_kCHR=S.prototype.cz=function(){return Js(this.hy)};S.prototype.set_kCHR=S.prototype.KB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ks(c,a)}; +Object.defineProperty(S.prototype,"kCHR",{get:S.prototype.cz,set:S.prototype.KB});S.prototype.get_kKHR=S.prototype.gz=function(){return Ls(this.hy)};S.prototype.set_kKHR=S.prototype.OB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ms(c,a)};Object.defineProperty(S.prototype,"kKHR",{get:S.prototype.gz,set:S.prototype.OB});S.prototype.get_kSHR=S.prototype.kz=function(){return Ns(this.hy)}; +S.prototype.set_kSHR=S.prototype.SB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Os(c,a)};Object.defineProperty(S.prototype,"kSHR",{get:S.prototype.kz,set:S.prototype.SB});S.prototype.get_kAHR=S.prototype.bz=function(){return Ps(this.hy)};S.prototype.set_kAHR=S.prototype.JB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qs(c,a)};Object.defineProperty(S.prototype,"kAHR",{get:S.prototype.bz,set:S.prototype.JB});S.prototype.get_kSRHR_CL=S.prototype.nz=function(){return Rs(this.hy)}; +S.prototype.set_kSRHR_CL=S.prototype.VB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ss(c,a)};Object.defineProperty(S.prototype,"kSRHR_CL",{get:S.prototype.nz,set:S.prototype.VB});S.prototype.get_kSKHR_CL=S.prototype.lz=function(){return Ts(this.hy)};S.prototype.set_kSKHR_CL=S.prototype.TB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Us(c,a)};Object.defineProperty(S.prototype,"kSKHR_CL",{get:S.prototype.lz,set:S.prototype.TB});S.prototype.get_kSSHR_CL=S.prototype.pz=function(){return Vs(this.hy)}; +S.prototype.set_kSSHR_CL=S.prototype.XB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ws(c,a)};Object.defineProperty(S.prototype,"kSSHR_CL",{get:S.prototype.pz,set:S.prototype.XB});S.prototype.get_kSR_SPLT_CL=S.prototype.oz=function(){return Xs(this.hy)};S.prototype.set_kSR_SPLT_CL=S.prototype.WB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ys(c,a)};Object.defineProperty(S.prototype,"kSR_SPLT_CL",{get:S.prototype.oz,set:S.prototype.WB}); +S.prototype.get_kSK_SPLT_CL=S.prototype.mz=function(){return Zs(this.hy)};S.prototype.set_kSK_SPLT_CL=S.prototype.UB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$s(c,a)};Object.defineProperty(S.prototype,"kSK_SPLT_CL",{get:S.prototype.mz,set:S.prototype.UB});S.prototype.get_kSS_SPLT_CL=S.prototype.qz=function(){return at(this.hy)};S.prototype.set_kSS_SPLT_CL=S.prototype.YB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bt(c,a)}; +Object.defineProperty(S.prototype,"kSS_SPLT_CL",{get:S.prototype.qz,set:S.prototype.YB});S.prototype.get_maxvolume=S.prototype.yB=function(){return ct(this.hy)};S.prototype.set_maxvolume=S.prototype.eE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dt(c,a)};Object.defineProperty(S.prototype,"maxvolume",{get:S.prototype.yB,set:S.prototype.eE});S.prototype.get_timescale=S.prototype.AB=function(){return et(this.hy)}; +S.prototype.set_timescale=S.prototype.gE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ft(c,a)};Object.defineProperty(S.prototype,"timescale",{get:S.prototype.AB,set:S.prototype.gE});S.prototype.get_viterations=S.prototype.BB=function(){return gt(this.hy)};S.prototype.set_viterations=S.prototype.hE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ht(c,a)};Object.defineProperty(S.prototype,"viterations",{get:S.prototype.BB,set:S.prototype.hE}); +S.prototype.get_piterations=S.prototype.zB=function(){return it(this.hy)};S.prototype.set_piterations=S.prototype.fE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jt(c,a)};Object.defineProperty(S.prototype,"piterations",{get:S.prototype.zB,set:S.prototype.fE});S.prototype.get_diterations=S.prototype.az=function(){return kt(this.hy)};S.prototype.set_diterations=S.prototype.IB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lt(c,a)}; +Object.defineProperty(S.prototype,"diterations",{get:S.prototype.az,set:S.prototype.IB});S.prototype.get_citerations=S.prototype.Zy=function(){return mt(this.hy)};S.prototype.set_citerations=S.prototype.GB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nt(c,a)};Object.defineProperty(S.prototype,"citerations",{get:S.prototype.Zy,set:S.prototype.GB});S.prototype.get_collisions=S.prototype.$y=function(){return ot(this.hy)}; +S.prototype.set_collisions=S.prototype.HB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pt(c,a)};Object.defineProperty(S.prototype,"collisions",{get:S.prototype.$y,set:S.prototype.HB});S.prototype.__destroy__=function(){qt(this.hy)};function Node(){throw"cannot construct a Node, no constructor in IDL";}Node.prototype=Object.create(f.prototype);Node.prototype.constructor=Node;Node.prototype.iy=Node;Node.jy={};b.Node=Node; +Node.prototype.get_m_x=Node.prototype.xB=function(){return k(rt(this.hy),p)};Node.prototype.set_m_x=Node.prototype.dE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);st(c,a)};Object.defineProperty(Node.prototype,"m_x",{get:Node.prototype.xB,set:Node.prototype.dE});Node.prototype.get_m_q=Node.prototype.OA=function(){return k(tt(this.hy),p)};Node.prototype.set_m_q=Node.prototype.uD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ut(c,a)}; +Object.defineProperty(Node.prototype,"m_q",{get:Node.prototype.OA,set:Node.prototype.uD});Node.prototype.get_m_v=Node.prototype.pB=function(){return k(vt(this.hy),p)};Node.prototype.set_m_v=Node.prototype.WD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wt(c,a)};Object.defineProperty(Node.prototype,"m_v",{get:Node.prototype.pB,set:Node.prototype.WD});Node.prototype.get_m_f=Node.prototype.bA=function(){return k(xt(this.hy),p)}; +Node.prototype.set_m_f=Node.prototype.IC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yt(c,a)};Object.defineProperty(Node.prototype,"m_f",{get:Node.prototype.bA,set:Node.prototype.IC});Node.prototype.get_m_n=Node.prototype.Hy=function(){return k(zt(this.hy),p)};Node.prototype.set_m_n=Node.prototype.Qy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);At(c,a)};Object.defineProperty(Node.prototype,"m_n",{get:Node.prototype.Hy,set:Node.prototype.Qy}); +Node.prototype.get_m_im=Node.prototype.pA=function(){return Bt(this.hy)};Node.prototype.set_m_im=Node.prototype.WC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ct(c,a)};Object.defineProperty(Node.prototype,"m_im",{get:Node.prototype.pA,set:Node.prototype.WC});Node.prototype.get_m_area=Node.prototype.Dz=function(){return Dt(this.hy)};Node.prototype.set_m_area=Node.prototype.jC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Et(c,a)}; +Object.defineProperty(Node.prototype,"m_area",{get:Node.prototype.Dz,set:Node.prototype.jC});Node.prototype.__destroy__=function(){Ft(this.hy)};function WB(){this.hy=Gt();h(WB)[this.hy]=this}WB.prototype=Object.create(f.prototype);WB.prototype.constructor=WB;WB.prototype.iy=WB;WB.jy={};b.btGhostPairCallback=WB;WB.prototype.__destroy__=function(){Ht(this.hy)};function XB(){throw"cannot construct a btOverlappingPairCallback, no constructor in IDL";}XB.prototype=Object.create(f.prototype); +XB.prototype.constructor=XB;XB.prototype.iy=XB;XB.jy={};b.btOverlappingPairCallback=XB;XB.prototype.__destroy__=function(){It(this.hy)};function T(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===e?Jt(a,c,d):Kt(a,c,d,e);h(T)[this.hy]=this}T.prototype=Object.create(ZA.prototype);T.prototype.constructor=T;T.prototype.iy=T;T.jy={};b.btKinematicCharacterController=T; +T.prototype.setUpAxis=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lt(c,a)};T.prototype.setWalkDirection=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mt(c,a)};T.prototype.setVelocityForTimeInterval=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Nt(d,a,c)};T.prototype.warp=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ot(c,a)};T.prototype.preStep=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pt(c,a)}; +T.prototype.playerStep=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Qt(d,a,c)};T.prototype.setFallSpeed=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rt(c,a)};T.prototype.setJumpSpeed=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);St(c,a)};T.prototype.setMaxJumpHeight=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tt(c,a)};T.prototype.canJump=function(){return!!Ut(this.hy)};T.prototype.jump=function(){Vt(this.hy)}; +T.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wt(c,a)};T.prototype.getGravity=function(){return Xt(this.hy)};T.prototype.setMaxSlope=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yt(c,a)};T.prototype.getMaxSlope=function(){return Zt(this.hy)};T.prototype.getGhostObject=function(){return k($t(this.hy),U)};T.prototype.setUseGhostSweepTest=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);au(c,a)};T.prototype.onGround=function(){return!!bu(this.hy)}; +T.prototype.setUpInterpolate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cu(c,a)};T.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);du(d,a,c)};T.prototype.__destroy__=function(){eu(this.hy)};function YB(){throw"cannot construct a btSoftBodyArray, no constructor in IDL";}YB.prototype=Object.create(f.prototype);YB.prototype.constructor=YB;YB.prototype.iy=YB;YB.jy={};b.btSoftBodyArray=YB; +YB.prototype.size=YB.prototype.size=function(){return fu(this.hy)};YB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(gu(c,a),R)};YB.prototype.__destroy__=function(){hu(this.hy)};function PB(){throw"cannot construct a btFaceArray, no constructor in IDL";}PB.prototype=Object.create(f.prototype);PB.prototype.constructor=PB;PB.prototype.iy=PB;PB.jy={};b.btFaceArray=PB;PB.prototype.size=PB.prototype.size=function(){return iu(this.hy)}; +PB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ju(c,a),ZB)};PB.prototype.__destroy__=function(){ku(this.hy)};function $B(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=lu(a,c);h($B)[this.hy]=this}$B.prototype=Object.create(UA.prototype);$B.prototype.constructor=$B;$B.prototype.iy=$B;$B.jy={};b.btStaticPlaneShape=$B;$B.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mu(c,a)}; +$B.prototype.getLocalScaling=function(){return k(nu(this.hy),p)};$B.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);ou(d,a,c)};$B.prototype.__destroy__=function(){pu(this.hy)};function PA(){throw"cannot construct a btOverlappingPairCache, no constructor in IDL";}PA.prototype=Object.create(f.prototype);PA.prototype.constructor=PA;PA.prototype.iy=PA;PA.jy={};b.btOverlappingPairCache=PA; +PA.prototype.setInternalGhostPairCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qu(c,a)};PA.prototype.getNumOverlappingPairs=function(){return ru(this.hy)};PA.prototype.__destroy__=function(){su(this.hy)};function vB(){throw"cannot construct a btIndexedMesh, no constructor in IDL";}vB.prototype=Object.create(f.prototype);vB.prototype.constructor=vB;vB.prototype.iy=vB;vB.jy={};b.btIndexedMesh=vB;vB.prototype.get_m_numTriangles=vB.prototype.KA=function(){return tu(this.hy)}; +vB.prototype.set_m_numTriangles=vB.prototype.qD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uu(c,a)};Object.defineProperty(vB.prototype,"m_numTriangles",{get:vB.prototype.KA,set:vB.prototype.qD});vB.prototype.__destroy__=function(){vu(this.hy)};function V(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=wu(a,c,d,e,g);h(V)[this.hy]=this}V.prototype=Object.create(x.prototype); +V.prototype.constructor=V;V.prototype.iy=V;V.jy={};b.btSoftRigidDynamicsWorld=V;V.prototype.addSoftBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);xu(e,a,c,d)};V.prototype.removeSoftBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yu(c,a)};V.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zu(c,a)};V.prototype.getWorldInfo=function(){return k(Au(this.hy),J)}; +V.prototype.getSoftBodyArray=function(){return k(Bu(this.hy),YB)};V.prototype.getDispatcher=function(){return k(Cu(this.hy),OA)};V.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Du(e,a,c,d)};V.prototype.getPairCache=function(){return k(Eu(this.hy),PA)};V.prototype.getDispatchInfo=function(){return k(Fu(this.hy),l)}; +V.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Gu(e,a):void 0===d?Hu(e,a,c):Iu(e,a,c,d)};V.prototype.getBroadphase=function(){return k(Ju(this.hy),QA)}; +V.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);Ku(n,a,c,d,e,g)};V.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Lu(e,a,c,d)}; +V.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Mu(d,a,c)};V.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nu(c,a)};V.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ou(c,a)};V.prototype.getDebugDrawer=function(){return k(Pu(this.hy),RA)};V.prototype.debugDrawWorld=function(){Qu(this.hy)}; +V.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ru(e,a,c,d)};V.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Su(c,a)};V.prototype.getGravity=function(){return k(Tu(this.hy),p)}; +V.prototype.addRigidBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Uu(e,a):void 0===d?_emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_2(e,a,c):Vu(e,a,c,d)};V.prototype.removeRigidBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wu(c,a)}; +V.prototype.addConstraint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Xu(d,a):Yu(d,a,c)};V.prototype.removeConstraint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zu(c,a)};V.prototype.stepSimulation=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return void 0===c?$u(e,a):void 0===d?av(e,a,c):bv(e,a,c,d)}; +V.prototype.setContactAddedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cv(c,a)};V.prototype.setContactProcessedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dv(c,a)};V.prototype.setContactDestroyedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ev(c,a)};V.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fv(c,a)};V.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gv(c,a)}; +V.prototype.getSolverInfo=function(){return k(hv(this.hy),v)};V.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?iv(e,a):void 0===d?jv(e,a,c):kv(e,a,c,d)};V.prototype.__destroy__=function(){lv(this.hy)}; +function aC(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=mv(a,c,d,e);h(aC)[this.hy]=this}aC.prototype=Object.create(TA.prototype);aC.prototype.constructor=aC;aC.prototype.iy=aC;aC.jy={};b.btFixedConstraint=aC;aC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nv(c,a)};aC.prototype.getBreakingImpulseThreshold=function(){return ov(this.hy)}; +aC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pv(c,a)};aC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return qv(d,a,c)};aC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);rv(e,a,c,d)};aC.prototype.__destroy__=function(){sv(this.hy)}; +function r(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?tv():void 0===c?_emscripten_bind_btTransform_btTransform_1(a):uv(a,c);h(r)[this.hy]=this}r.prototype=Object.create(f.prototype);r.prototype.constructor=r;r.prototype.iy=r;r.jy={};b.btTransform=r;r.prototype.setIdentity=function(){vv(this.hy)};r.prototype.setOrigin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wv(c,a)}; +r.prototype.setRotation=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xv(c,a)};r.prototype.getOrigin=function(){return k(yv(this.hy),p)};r.prototype.getRotation=function(){return k(zv(this.hy),W)};r.prototype.getBasis=function(){return k(Av(this.hy),jB)};r.prototype.setFromOpenGLMatrix=function(a){var c=this.hy;IA();"object"==typeof a&&(a=MA(a));Bv(c,a)};r.prototype.inverse=r.prototype.inverse=function(){return k(Cv(this.hy),r)}; +r.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Dv(c,a),r)};r.prototype.__destroy__=function(){Ev(this.hy)};function X(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Fv(a,c);h(X)[this.hy]=this}X.prototype=Object.create(z.prototype);X.prototype.constructor=X;X.prototype.iy=X;X.jy={};b.ClosestRayResultCallback=X;X.prototype.hasHit=function(){return!!Gv(this.hy)}; +X.prototype.get_m_rayFromWorld=X.prototype.Iy=function(){return k(Hv(this.hy),p)};X.prototype.set_m_rayFromWorld=X.prototype.Ry=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Iv(c,a)};Object.defineProperty(X.prototype,"m_rayFromWorld",{get:X.prototype.Iy,set:X.prototype.Ry});X.prototype.get_m_rayToWorld=X.prototype.Jy=function(){return k(Jv(this.hy),p)};X.prototype.set_m_rayToWorld=X.prototype.Sy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kv(c,a)}; +Object.defineProperty(X.prototype,"m_rayToWorld",{get:X.prototype.Jy,set:X.prototype.Sy});X.prototype.get_m_hitNormalWorld=X.prototype.sy=function(){return k(Lv(this.hy),p)};X.prototype.set_m_hitNormalWorld=X.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mv(c,a)};Object.defineProperty(X.prototype,"m_hitNormalWorld",{get:X.prototype.sy,set:X.prototype.zy});X.prototype.get_m_hitPointWorld=X.prototype.ty=function(){return k(Nv(this.hy),p)}; +X.prototype.set_m_hitPointWorld=X.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ov(c,a)};Object.defineProperty(X.prototype,"m_hitPointWorld",{get:X.prototype.ty,set:X.prototype.Ay});X.prototype.get_m_collisionFilterGroup=X.prototype.ky=function(){return Pv(this.hy)};X.prototype.set_m_collisionFilterGroup=X.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qv(c,a)};Object.defineProperty(X.prototype,"m_collisionFilterGroup",{get:X.prototype.ky,set:X.prototype.my}); +X.prototype.get_m_collisionFilterMask=X.prototype.ly=function(){return Rv(this.hy)};X.prototype.set_m_collisionFilterMask=X.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sv(c,a)};Object.defineProperty(X.prototype,"m_collisionFilterMask",{get:X.prototype.ly,set:X.prototype.ny});X.prototype.get_m_closestHitFraction=X.prototype.oy=function(){return Tv(this.hy)}; +X.prototype.set_m_closestHitFraction=X.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uv(c,a)};Object.defineProperty(X.prototype,"m_closestHitFraction",{get:X.prototype.oy,set:X.prototype.py});X.prototype.get_m_collisionObject=X.prototype.qy=function(){return k(Vv(this.hy),q)};X.prototype.set_m_collisionObject=X.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wv(c,a)};Object.defineProperty(X.prototype,"m_collisionObject",{get:X.prototype.qy,set:X.prototype.xy}); +X.prototype.__destroy__=function(){Xv(this.hy)};function bC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?Yv():Zv(a);h(bC)[this.hy]=this}bC.prototype=Object.create(WA.prototype);bC.prototype.constructor=bC;bC.prototype.iy=bC;bC.jy={};b.btSoftBodyRigidBodyCollisionConfiguration=bC;bC.prototype.__destroy__=function(){$v(this.hy)};function cC(){this.hy=aw();h(cC)[this.hy]=this}cC.prototype=Object.create(hB.prototype);cC.prototype.constructor=cC;cC.prototype.iy=cC;cC.jy={}; +b.ConcreteContactResultCallback=cC;cC.prototype.addSingleResult=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return bw(aa,a,c,d,e,g,n,F)};cC.prototype.__destroy__=function(){cw(this.hy)}; +function dC(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=void 0===d?dw(a,c):ew(a,c,d);h(dC)[this.hy]=this}dC.prototype=Object.create(XA.prototype);dC.prototype.constructor=dC;dC.prototype.iy=dC;dC.jy={};b.btBvhTriangleMeshShape=dC;dC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fw(c,a)};dC.prototype.getLocalScaling=function(){return k(gw(this.hy),p)}; +dC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);hw(d,a,c)};dC.prototype.__destroy__=function(){iw(this.hy)};function oB(){throw"cannot construct a btConstCollisionObjectArray, no constructor in IDL";}oB.prototype=Object.create(f.prototype);oB.prototype.constructor=oB;oB.prototype.iy=oB;oB.jy={};b.btConstCollisionObjectArray=oB;oB.prototype.size=oB.prototype.size=function(){return jw(this.hy)}; +oB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(kw(c,a),q)};oB.prototype.__destroy__=function(){lw(this.hy)};function eC(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?mw(a,c,d):void 0===g?_emscripten_bind_btSliderConstraint_btSliderConstraint_4(a,c,d,e):nw(a,c,d,e,g);h(eC)[this.hy]=this}eC.prototype=Object.create(TA.prototype); +eC.prototype.constructor=eC;eC.prototype.iy=eC;eC.jy={};b.btSliderConstraint=eC;eC.prototype.setLowerLinLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ow(c,a)};eC.prototype.setUpperLinLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pw(c,a)};eC.prototype.setLowerAngLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qw(c,a)};eC.prototype.setUpperAngLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rw(c,a)}; +eC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sw(c,a)};eC.prototype.getBreakingImpulseThreshold=function(){return tw(this.hy)};eC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uw(c,a)};eC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return vw(d,a,c)}; +eC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ww(e,a,c,d)};eC.prototype.__destroy__=function(){xw(this.hy)};function U(){this.hy=yw();h(U)[this.hy]=this}U.prototype=Object.create(w.prototype);U.prototype.constructor=U;U.prototype.iy=U;U.jy={};b.btPairCachingGhostObject=U; +U.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);zw(d,a,c)};U.prototype.getCollisionShape=function(){return k(Aw(this.hy),m)};U.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bw(c,a)};U.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cw(c,a)}; +U.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dw(c,a)};U.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Ew(c):Fw(c,a)};U.prototype.isActive=function(){return!!Gw(this.hy)};U.prototype.isKinematicObject=function(){return!!Hw(this.hy)};U.prototype.isStaticObject=function(){return!!Iw(this.hy)};U.prototype.isStaticOrKinematicObject=function(){return!!Jw(this.hy)};U.prototype.getRestitution=function(){return Kw(this.hy)}; +U.prototype.getFriction=function(){return Lw(this.hy)};U.prototype.getRollingFriction=function(){return Mw(this.hy)};U.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nw(c,a)};U.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ow(c,a)};U.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pw(c,a)};U.prototype.getWorldTransform=function(){return k(Qw(this.hy),r)};U.prototype.getCollisionFlags=function(){return Rw(this.hy)}; +U.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sw(c,a)};U.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tw(c,a)};U.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uw(c,a)};U.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vw(c,a)};U.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ww(c,a)}; +U.prototype.getUserIndex=function(){return Xw(this.hy)};U.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yw(c,a)};U.prototype.getUserPointer=function(){return k(Zw(this.hy),SA)};U.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$w(c,a)};U.prototype.getBroadphaseHandle=function(){return k(ax(this.hy),t)};U.prototype.getNumOverlappingObjects=function(){return bx(this.hy)}; +U.prototype.getOverlappingObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(cx(c,a),q)};U.prototype.__destroy__=function(){dx(this.hy)};function D(){throw"cannot construct a btManifoldPoint, no constructor in IDL";}D.prototype=Object.create(f.prototype);D.prototype.constructor=D;D.prototype.iy=D;D.jy={};b.btManifoldPoint=D;D.prototype.getPositionWorldOnA=function(){return k(ex(this.hy),p)};D.prototype.getPositionWorldOnB=function(){return k(fx(this.hy),p)}; +D.prototype.getAppliedImpulse=function(){return gx(this.hy)};D.prototype.getDistance=function(){return hx(this.hy)};D.prototype.get_m_localPointA=D.prototype.AA=function(){return k(ix(this.hy),p)};D.prototype.set_m_localPointA=D.prototype.gD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jx(c,a)};Object.defineProperty(D.prototype,"m_localPointA",{get:D.prototype.AA,set:D.prototype.gD});D.prototype.get_m_localPointB=D.prototype.BA=function(){return k(kx(this.hy),p)}; +D.prototype.set_m_localPointB=D.prototype.hD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lx(c,a)};Object.defineProperty(D.prototype,"m_localPointB",{get:D.prototype.BA,set:D.prototype.hD});D.prototype.get_m_positionWorldOnB=D.prototype.NA=function(){return k(mx(this.hy),p)};D.prototype.set_m_positionWorldOnB=D.prototype.tD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nx(c,a)};Object.defineProperty(D.prototype,"m_positionWorldOnB",{get:D.prototype.NA,set:D.prototype.tD}); +D.prototype.get_m_positionWorldOnA=D.prototype.MA=function(){return k(ox(this.hy),p)};D.prototype.set_m_positionWorldOnA=D.prototype.sD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);px(c,a)};Object.defineProperty(D.prototype,"m_positionWorldOnA",{get:D.prototype.MA,set:D.prototype.sD});D.prototype.get_m_normalWorldOnB=D.prototype.IA=function(){return k(qx(this.hy),p)};D.prototype.set_m_normalWorldOnB=D.prototype.oD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rx(c,a)}; +Object.defineProperty(D.prototype,"m_normalWorldOnB",{get:D.prototype.IA,set:D.prototype.oD});D.prototype.get_m_userPersistentData=D.prototype.oB=function(){return sx(this.hy)};D.prototype.set_m_userPersistentData=D.prototype.VD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tx(c,a)};Object.defineProperty(D.prototype,"m_userPersistentData",{get:D.prototype.oB,set:D.prototype.VD});D.prototype.__destroy__=function(){ux(this.hy)}; +function fC(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===d?vx(a,c):void 0===e?_emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_3(a,c,d):wx(a,c,d,e);h(fC)[this.hy]=this}fC.prototype=Object.create(TA.prototype);fC.prototype.constructor=fC;fC.prototype.iy=fC;fC.jy={};b.btPoint2PointConstraint=fC; +fC.prototype.setPivotA=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xx(c,a)};fC.prototype.setPivotB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yx(c,a)};fC.prototype.getPivotInA=function(){return k(zx(this.hy),p)};fC.prototype.getPivotInB=function(){return k(Ax(this.hy),p)};fC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bx(c,a)};fC.prototype.getBreakingImpulseThreshold=function(){return Cx(this.hy)}; +fC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dx(c,a)};fC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Ex(d,a,c)};fC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Fx(e,a,c,d)};fC.prototype.get_m_setting=fC.prototype.VA=function(){return k(Gx(this.hy),H)}; +fC.prototype.set_m_setting=fC.prototype.BD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hx(c,a)};Object.defineProperty(fC.prototype,"m_setting",{get:fC.prototype.VA,set:fC.prototype.BD});fC.prototype.__destroy__=function(){Ix(this.hy)};function gC(){this.hy=Jx();h(gC)[this.hy]=this}gC.prototype=Object.create(f.prototype);gC.prototype.constructor=gC;gC.prototype.iy=gC;gC.jy={};b.btSoftBodyHelpers=gC; +gC.prototype.CreateRope=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);return k(Kx(n,a,c,d,e,g),R)}; +gC.prototype.CreatePatch=function(a,c,d,e,g,n,F,aa,ta){var Rb=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);return k(Lx(Rb,a,c,d,e,g,n,F,aa,ta),R)}; +gC.prototype.CreatePatchUV=function(a,c,d,e,g,n,F,aa,ta,Rb){var nC=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);"object"==typeof Rb&&(Rb=MA(Rb));return k(Mx(nC,a,c,d,e,g,n,F,aa,ta,Rb),R)}; +gC.prototype.CreateEllipsoid=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);return k(Nx(g,a,c,d,e),R)}; +gC.prototype.CreateFromTriMesh=function(a,c,d,e,g){var n=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);"object"==typeof c&&(c=MA(c));if("object"==typeof d&&"object"===typeof d){var F=JA(d,Aa);KA(d,Aa,F);d=F}e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);return k(Ox(n,a,c,d,e,g),R)}; +gC.prototype.CreateFromConvexHull=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);return k(Px(g,a,c,d,e),R)};gC.prototype.__destroy__=function(){Qx(this.hy)};function t(){throw"cannot construct a btBroadphaseProxy, no constructor in IDL";}t.prototype=Object.create(f.prototype);t.prototype.constructor=t;t.prototype.iy=t;t.jy={};b.btBroadphaseProxy=t; +t.prototype.get_m_collisionFilterGroup=t.prototype.ky=function(){return Rx(this.hy)};t.prototype.set_m_collisionFilterGroup=t.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sx(c,a)};Object.defineProperty(t.prototype,"m_collisionFilterGroup",{get:t.prototype.ky,set:t.prototype.my});t.prototype.get_m_collisionFilterMask=t.prototype.ly=function(){return Tx(this.hy)}; +t.prototype.set_m_collisionFilterMask=t.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ux(c,a)};Object.defineProperty(t.prototype,"m_collisionFilterMask",{get:t.prototype.ly,set:t.prototype.ny});t.prototype.__destroy__=function(){Vx(this.hy)};function TB(){throw"cannot construct a tNodeArray, no constructor in IDL";}TB.prototype=Object.create(f.prototype);TB.prototype.constructor=TB;TB.prototype.iy=TB;TB.jy={};b.tNodeArray=TB;TB.prototype.size=TB.prototype.size=function(){return Wx(this.hy)}; +TB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Xx(c,a),Node)};TB.prototype.__destroy__=function(){Yx(this.hy)};function hC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Zx(a);h(hC)[this.hy]=this}hC.prototype=Object.create(m.prototype);hC.prototype.constructor=hC;hC.prototype.iy=hC;hC.jy={};b.btBoxShape=hC;hC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$x(c,a)};hC.prototype.getMargin=function(){return ay(this.hy)}; +hC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);by(c,a)};hC.prototype.getLocalScaling=function(){return k(cy(this.hy),p)};hC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dy(d,a,c)};hC.prototype.__destroy__=function(){ey(this.hy)};function ZB(){throw"cannot construct a btFace, no constructor in IDL";}ZB.prototype=Object.create(f.prototype);ZB.prototype.constructor=ZB; +ZB.prototype.iy=ZB;ZB.jy={};b.btFace=ZB;ZB.prototype.get_m_indices=ZB.prototype.rA=function(){return k(fy(this.hy),VB)};ZB.prototype.set_m_indices=ZB.prototype.YC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gy(c,a)};Object.defineProperty(ZB.prototype,"m_indices",{get:ZB.prototype.rA,set:ZB.prototype.YC});ZB.prototype.get_m_plane=ZB.prototype.LA=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return hy(c,a)}; +ZB.prototype.set_m_plane=ZB.prototype.rD=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);iy(d,a,c)};Object.defineProperty(ZB.prototype,"m_plane",{get:ZB.prototype.LA,set:ZB.prototype.rD});ZB.prototype.__destroy__=function(){jy(this.hy)};function iC(){this.hy=ky();h(iC)[this.hy]=this}iC.prototype=Object.create(RA.prototype);iC.prototype.constructor=iC;iC.prototype.iy=iC;iC.jy={};b.DebugDrawer=iC; +iC.prototype.drawLine=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ly(e,a,c,d)};iC.prototype.drawContactPoint=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);my(n,a,c,d,e,g)}; +iC.prototype.reportErrorWarning=function(a){var c=this.hy;IA();a=a&&"object"===typeof a?a.hy:LA(a);ny(c,a)};iC.prototype.draw3dText=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c=c&&"object"===typeof c?c.hy:LA(c);oy(d,a,c)};iC.prototype.setDebugMode=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);py(c,a)};iC.prototype.getDebugMode=function(){return qy(this.hy)};iC.prototype.__destroy__=function(){ry(this.hy)}; +function jC(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=sy(a,c);h(jC)[this.hy]=this}jC.prototype=Object.create(VA.prototype);jC.prototype.constructor=jC;jC.prototype.iy=jC;jC.jy={};b.btCapsuleShapeX=jC;jC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ty(c,a)};jC.prototype.getMargin=function(){return uy(this.hy)};jC.prototype.getUpAxis=function(){return vy(this.hy)};jC.prototype.getRadius=function(){return wy(this.hy)}; +jC.prototype.getHalfHeight=function(){return xy(this.hy)};jC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yy(c,a)};jC.prototype.getLocalScaling=function(){return k(zy(this.hy),p)};jC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ay(d,a,c)};jC.prototype.__destroy__=function(){By(this.hy)}; +function W(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=Cy(a,c,d,e);h(W)[this.hy]=this}W.prototype=Object.create(aB.prototype);W.prototype.constructor=W;W.prototype.iy=W;W.jy={};b.btQuaternion=W;W.prototype.setValue=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);Dy(g,a,c,d,e)}; +W.prototype.setEulerZYX=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ey(e,a,c,d)};W.prototype.setRotation=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Fy(d,a,c)};W.prototype.normalize=W.prototype.normalize=function(){Gy(this.hy)};W.prototype.length2=function(){return Hy(this.hy)};W.prototype.length=W.prototype.length=function(){return Iy(this.hy)}; +W.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Jy(c,a)};W.prototype.normalized=function(){return k(Ky(this.hy),W)};W.prototype.getAxis=function(){return k(Ly(this.hy),p)};W.prototype.inverse=W.prototype.inverse=function(){return k(My(this.hy),W)};W.prototype.getAngle=function(){return Ny(this.hy)};W.prototype.getAngleShortestPath=function(){return Oy(this.hy)}; +W.prototype.angle=W.prototype.angle=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Py(c,a)};W.prototype.angleShortestPath=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Qy(c,a)};W.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Ry(c,a),W)};W.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Sy(c,a),W)}; +W.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Ty(c,a),W)};W.prototype.op_mulq=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Uy(c,a),W)};W.prototype.op_div=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Vy(c,a),W)};W.prototype.x=W.prototype.x=function(){return Wy(this.hy)};W.prototype.y=W.prototype.y=function(){return Xy(this.hy)};W.prototype.z=W.prototype.z=function(){return Yy(this.hy)};W.prototype.w=function(){return Zy(this.hy)}; +W.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$y(c,a)};W.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);az(c,a)};W.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bz(c,a)};W.prototype.setW=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cz(c,a)};W.prototype.__destroy__=function(){dz(this.hy)}; +function kC(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=ez(a,c);h(kC)[this.hy]=this}kC.prototype=Object.create(VA.prototype);kC.prototype.constructor=kC;kC.prototype.iy=kC;kC.jy={};b.btCapsuleShapeZ=kC;kC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fz(c,a)};kC.prototype.getMargin=function(){return gz(this.hy)};kC.prototype.getUpAxis=function(){return hz(this.hy)};kC.prototype.getRadius=function(){return iz(this.hy)}; +kC.prototype.getHalfHeight=function(){return jz(this.hy)};kC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kz(c,a)};kC.prototype.getLocalScaling=function(){return k(lz(this.hy),p)};kC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);mz(d,a,c)};kC.prototype.__destroy__=function(){nz(this.hy)};function v(){throw"cannot construct a btContactSolverInfo, no constructor in IDL";} +v.prototype=Object.create(f.prototype);v.prototype.constructor=v;v.prototype.iy=v;v.jy={};b.btContactSolverInfo=v;v.prototype.get_m_splitImpulse=v.prototype.YA=function(){return!!oz(this.hy)};v.prototype.set_m_splitImpulse=v.prototype.ED=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pz(c,a)};Object.defineProperty(v.prototype,"m_splitImpulse",{get:v.prototype.YA,set:v.prototype.ED});v.prototype.get_m_splitImpulsePenetrationThreshold=v.prototype.ZA=function(){return qz(this.hy)}; +v.prototype.set_m_splitImpulsePenetrationThreshold=v.prototype.FD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rz(c,a)};Object.defineProperty(v.prototype,"m_splitImpulsePenetrationThreshold",{get:v.prototype.ZA,set:v.prototype.FD});v.prototype.get_m_numIterations=v.prototype.JA=function(){return sz(this.hy)};v.prototype.set_m_numIterations=v.prototype.pD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tz(c,a)}; +Object.defineProperty(v.prototype,"m_numIterations",{get:v.prototype.JA,set:v.prototype.pD});v.prototype.__destroy__=function(){uz(this.hy)};function lC(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?vz(a,c,d):void 0===g?_emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_4(a,c,d,e):wz(a,c,d,e,g);h(lC)[this.hy]=this} +lC.prototype=Object.create(eB.prototype);lC.prototype.constructor=lC;lC.prototype.iy=lC;lC.jy={};b.btGeneric6DofSpringConstraint=lC;lC.prototype.enableSpring=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);xz(d,a,c)};lC.prototype.setStiffness=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);yz(d,a,c)}; +lC.prototype.setDamping=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);zz(d,a,c)};lC.prototype.setEquilibriumPoint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===a?Az(d):void 0===c?Bz(d,a):Cz(d,a,c)};lC.prototype.setLinearLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dz(c,a)}; +lC.prototype.setLinearUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ez(c,a)};lC.prototype.setAngularLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fz(c,a)};lC.prototype.setAngularUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gz(c,a)};lC.prototype.getFrameOffsetA=function(){return k(Hz(this.hy),r)};lC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Iz(c,a)}; +lC.prototype.getBreakingImpulseThreshold=function(){return Jz(this.hy)};lC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kz(c,a)};lC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Lz(d,a,c)};lC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Mz(e,a,c,d)}; +lC.prototype.__destroy__=function(){Nz(this.hy)};function mC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Oz(a);h(mC)[this.hy]=this}mC.prototype=Object.create(m.prototype);mC.prototype.constructor=mC;mC.prototype.iy=mC;mC.jy={};b.btSphereShape=mC;mC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pz(c,a)};mC.prototype.getMargin=function(){return Qz(this.hy)};mC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rz(c,a)}; +mC.prototype.getLocalScaling=function(){return k(Sz(this.hy),p)};mC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Tz(d,a,c)};mC.prototype.__destroy__=function(){Uz(this.hy)};function Y(){throw"cannot construct a Face, no constructor in IDL";}Y.prototype=Object.create(f.prototype);Y.prototype.constructor=Y;Y.prototype.iy=Y;Y.jy={};b.Face=Y; +Y.prototype.get_m_n=Y.prototype.Hy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Vz(c,a),Node)};Y.prototype.set_m_n=Y.prototype.Qy=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Wz(d,a,c)};Object.defineProperty(Y.prototype,"m_n",{get:Y.prototype.Hy,set:Y.prototype.Qy});Y.prototype.get_m_normal=Y.prototype.HA=function(){return k(Xz(this.hy),p)}; +Y.prototype.set_m_normal=Y.prototype.nD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yz(c,a)};Object.defineProperty(Y.prototype,"m_normal",{get:Y.prototype.HA,set:Y.prototype.nD});Y.prototype.get_m_ra=Y.prototype.PA=function(){return Zz(this.hy)};Y.prototype.set_m_ra=Y.prototype.vD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$z(c,a)};Object.defineProperty(Y.prototype,"m_ra",{get:Y.prototype.PA,set:Y.prototype.vD});Y.prototype.__destroy__=function(){aA(this.hy)}; +function UB(){throw"cannot construct a tFaceArray, no constructor in IDL";}UB.prototype=Object.create(f.prototype);UB.prototype.constructor=UB;UB.prototype.iy=UB;UB.jy={};b.tFaceArray=UB;UB.prototype.size=UB.prototype.size=function(){return bA(this.hy)};UB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(cA(c,a),Y)};UB.prototype.__destroy__=function(){dA(this.hy)}; +function Z(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=eA(a,c,d,e,g);h(Z)[this.hy]=this}Z.prototype=Object.create(f.prototype);Z.prototype.constructor=Z;Z.prototype.iy=Z;Z.jy={};b.LocalConvexResult=Z;Z.prototype.get_m_hitCollisionObject=Z.prototype.iA=function(){return k(fA(this.hy),q)}; +Z.prototype.set_m_hitCollisionObject=Z.prototype.PC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gA(c,a)};Object.defineProperty(Z.prototype,"m_hitCollisionObject",{get:Z.prototype.iA,set:Z.prototype.PC});Z.prototype.get_m_localShapeInfo=Z.prototype.CA=function(){return k(hA(this.hy),tB)};Z.prototype.set_m_localShapeInfo=Z.prototype.iD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);iA(c,a)};Object.defineProperty(Z.prototype,"m_localShapeInfo",{get:Z.prototype.CA,set:Z.prototype.iD}); +Z.prototype.get_m_hitNormalLocal=Z.prototype.mA=function(){return k(jA(this.hy),p)};Z.prototype.set_m_hitNormalLocal=Z.prototype.TC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kA(c,a)};Object.defineProperty(Z.prototype,"m_hitNormalLocal",{get:Z.prototype.mA,set:Z.prototype.TC});Z.prototype.get_m_hitPointLocal=Z.prototype.oA=function(){return k(lA(this.hy),p)};Z.prototype.set_m_hitPointLocal=Z.prototype.VC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mA(c,a)}; +Object.defineProperty(Z.prototype,"m_hitPointLocal",{get:Z.prototype.oA,set:Z.prototype.VC});Z.prototype.get_m_hitFraction=Z.prototype.jA=function(){return nA(this.hy)};Z.prototype.set_m_hitFraction=Z.prototype.QC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);oA(c,a)};Object.defineProperty(Z.prototype,"m_hitFraction",{get:Z.prototype.jA,set:Z.prototype.QC});Z.prototype.__destroy__=function(){pA(this.hy)}; +(function(){function a(){b.BT_CONSTRAINT_ERP=qA();b.BT_CONSTRAINT_STOP_ERP=rA();b.BT_CONSTRAINT_CFM=sA();b.BT_CONSTRAINT_STOP_CFM=tA();b.PHY_FLOAT=uA();b.PHY_DOUBLE=vA();b.PHY_INTEGER=wA();b.PHY_SHORT=xA();b.PHY_FIXEDPOINT88=yA();b.PHY_UCHAR=zA()}Ka?a():Ia.unshift(a)})();this.Ammo=b; + + + return Ammo.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = Ammo; + else if (typeof define === 'function' && define['amd']) + define([], function() { return Ammo; }); + else if (typeof exports === 'object') + exports["Ammo"] = Ammo; + diff --git a/renderer/jsm/libs/ammo.wasm.wasm b/renderer/jsm/libs/ammo.wasm.wasm new file mode 100644 index 0000000000000000000000000000000000000000..fb4eff284d1f8b32ba9817027d0652860604d436 GIT binary patch literal 651386 zcmZQbEY4+QU|?W;&6b?NSkI8aSkG9Wz*Jw)03sOc6Ikl&K^$f<$ym==n*d^h)zmU1 zu!3ak86c_{>p^n03<+#t(Rv0D7o>v$YECUkq!uh*3s(kbKrLphg__D(pTGb%8Ki@; zma#U08)R;6ZEbCRJ=|`_+5|3;Fa(1vsIO(LPhf}e>lqSwKrE1^+Io;dZ1o`R^$ZD| zAaO8;cm_n)g0vzThiW+37qwvHK|ZVng$qkPi~{)xW-DWT0teXW`g)N6k*umkvKJbB zwGdB&!vXA0FdwWDY7HbvYQaKG^`MYoss)kY@BrCU3$h&SZgAk#LreyFm$e?^Kvob1 z76(}Ykq7$(>`qXSfP4p%W2{eLtYNGLC4?G;FOb5kmH{qY%K#7jT2PdL4XdvQxd!6r zT5z&~2-kw#0}dfDiw*3edWHmc5Ca^Fptu1uAR0h{R}YDFkS8HrUMLenAz~U7b5L!y zpp*m(x_Yn=p)LUhA0#=0l!6j2SRF_f5@?_R0EHGf8H42*K`NQROlGKdkcU7DYQaeb zVhJdUAuLd&fJ}zQ5lDg+6s90?aJH#QV5+HStYLEGU`%98WMF4ZWK3dUW=v#EW=LdA zWK02zq%trvCNicmh%qLz<)-H57gaJbHgGg>Feb8=BqrsgG8Ql_VrPED|A3!`fq|Wo zfq{{gQH+&=ot065k%>V7!ot42v zhJ~GhRfJQVmxGOol}nb1m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*FyT-sRIgLT8UJ|MNbj4?Fv<8m!%6WS z42co586Jl3VF+wK#&E+kHG^SZ$N>ibwqFck zY=0P@R<2{{R5D|*SgXX4KKTwq=!;bhO==blr=HJd2;^PDFw=M=!^-P?44JGR45^zw zFw}P}XXx;m&hYc18H3`a%?#B|UJNtND>69Dzr%3HJ(S^Li4{ZoYbS<(bMG_6U5RI? zPG7>XYfTkH=(j}-+8xRaj=Mq`BJ(&H6t&tIEZv(KIv+n{cslP2gXeDthW}wN8D#iR zF&vHTVwmzvo8j`oqYV5<&okVPTF2miw2h(FIf+5B&6+`{ateb$VmpJDPc=h>jueCQ zej$bqwFwLrHk}MBjyz#_db^t8h}9tmwJ)z2zNdFF@J`y#kh)l#!FKXShP^f13`+v< zFsR>6X2^VamtocvNrn}gQyDVOX)tiU-NN89UxC4I#wmt^reub?8f6Clokk4HzxFYR zggs|a{K&zub*>geew{DFQprGutv^>YG~K_(Fzs$4gP0i;!x5|b49$xcG8DbdWw7k6 zVrbg2k|EnDhQUoent{ROEyE>-a)v)&LKzq%eHk7UHZV9oKFP?vpT*&~;!k@}yIa?# z1ayja!wk0{pcA;T9f(5Z#D`8^$O z^Lrj(U;wR0Jpi`<&iRX=Q^FY-4v5;v$0t`L#;2Di7Nx`|CKr}w7NshrfY0GfO;IRH zO)f1e&IF&!lL;Ep&#VF;&BG8-T9m3#mRVF%nus_-T>*49Kx&F2LvV>@No7H5Jm@eV zkUKzQ=Vwwu*C!Z&tgA>&$}BT9G>eZf&dAJ-hbwgjsVzxkV0eEJfVx2<9pZ+0XlBo6W?)#r z%)qb^!)(L&__AEAhJ*a~0b;h}l5>pQ8eG>G+knn~0Ub#Kiqwn>28KRn28MoS28IdD P3=9*Q85sWm|NkEVV^}#Y literal 0 HcmV?d00001 diff --git a/renderer/jsm/libs/basis/README.md b/renderer/jsm/libs/basis/README.md new file mode 100644 index 0000000..2d7744f --- /dev/null +++ b/renderer/jsm/libs/basis/README.md @@ -0,0 +1,46 @@ +# Basis Universal GPU Texture Compression + +Basis Universal is a "[supercompressed](http://gamma.cs.unc.edu/GST/gst.pdf)" +GPU texture and texture video compression system that outputs a highly +compressed intermediate file format (.basis) that can be quickly transcoded to +a wide variety of GPU texture compression formats. + +[GitHub](https://github.com/BinomialLLC/basis_universal) + +## Transcoders + +Basis Universal texture data may be used in two different file formats: +`.basis` and `.ktx2`, where `ktx2` is a standardized wrapper around basis texture data. + +For further documentation about the Basis compressor and transcoder, refer to +the [Basis GitHub repository](https://github.com/BinomialLLC/basis_universal). + +The folder contains two files required for transcoding `.basis` or `.ktx2` textures: + +* `basis_transcoder.js` — JavaScript wrapper for the WebAssembly transcoder. +* `basis_transcoder.wasm` — WebAssembly transcoder. + +Both are dependencies of `KTX2Loader`: + +```js +const ktx2Loader = new KTX2Loader(); +ktx2Loader.setTranscoderPath( 'examples/jsm/libs/basis/' ); +ktx2Loader.detectSupport( renderer ); +ktx2Loader.load( 'diffuse.ktx2', function ( texture ) { + + const material = new THREE.MeshStandardMaterial( { map: texture } ); + +}, function () { + + console.log( 'onProgress' ); + +}, function ( e ) { + + console.error( e ); + +} ); +``` + +## License + +[Apache License 2.0](https://github.com/BinomialLLC/basis_universal/blob/master/LICENSE) diff --git a/renderer/jsm/libs/basis/basis_transcoder.js b/renderer/jsm/libs/basis/basis_transcoder.js new file mode 100644 index 0000000..9e285dd --- /dev/null +++ b/renderer/jsm/libs/basis/basis_transcoder.js @@ -0,0 +1,21 @@ + +var BASIS = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(BASIS) { + BASIS = BASIS || {}; + +var Module=typeof BASIS!=="undefined"?BASIS:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="basis_transcoder.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return Promise.resolve().then(getBinary)}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["K"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["L"];removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var structRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationGroup=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function attachFinalizer(handle){if("undefined"===typeof FinalizationGroup){attachFinalizer=function(handle){return handle};return handle}finalizationGroup=new FinalizationGroup(function(iter){for(var result=iter.next();!result.done;result=iter.next()){var $$=result.value;if(!$$.ptr){console.warn("object already deleted: "+$$.ptr)}else{releaseClassHandle($$)}}});attachFinalizer=function(handle){finalizationGroup.register(handle,handle.$$,handle.$$);return handle};detachFinalizer=function(handle){finalizationGroup.unregister(handle.$$)};return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}var delayFunction=undefined;var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}var registeredPointers={};function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,__emval_register(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){if(args&&args.length){return Module["dynCall_"+sig].apply(null,[ptr].concat(args))}return Module["dynCall_"+sig].call(null,ptr)}function dynCall(sig,ptr,args){if(sig.indexOf("j")!=-1){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function getDynCaller(sig,ptr){assert(sig.indexOf("j")>=0,"getDynCaller should only be called with i64 sigs");var argCache=[];return function(){argCache.length=arguments.length;for(var i=0;i>2)+i])}return array}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);var args=[rawConstructor];var destructors=[];whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=function unboundTypeHandler(){throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){classType.registeredClass.constructor_body[argCount-1]=function constructor_body(){if(arguments.length!==argCount-1){throwBindingError(humanName+" called with "+arguments.length+" arguments, expected "+(argCount-1))}destructors.length=0;args.length=argCount;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function __embind_register_function(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn){var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError("Cannot call "+name+" due to unbound types",argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn),argCount-1);return[]})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.indexOf("unsigned")!=-1;registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}else{return symbol}}var emval_methodCallers=[];function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_get_global(){if(typeof globalThis==="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return __emval_register(emval_get_global())}else{name=getStringOrSymbol(name);return __emval_register(emval_get_global()[name])}}function __emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_get_method_caller(argCount,argTypes){var types=__emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function craftEmvalAllocator(argCount){var argsList="";for(var i=0;i>> 2) + "+i+'], "parameter '+i+'");\n'+"var arg"+i+" = argType"+i+".readValueFromPointer(args);\n"+"args += argType"+i+"['argPackAdvance'];\n"}functionBody+="var obj = new constructor("+argsList+");\n"+"return __emval_register(obj);\n"+"}\n";return new Function("requireRegisteredType","Module","__emval_register",functionBody)(requireRegisteredType,Module,__emval_register)}var emval_newers={};function __emval_new(handle,argCount,argTypes,args){handle=requireHandle(handle);var newer=emval_newers[argCount];if(!newer){newer=craftEmvalAllocator(argCount);emval_newers[argCount]=newer}return newer(handle,argTypes,args)}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){requestedSize=requestedSize>>>0;var oldSize=_emscripten_get_heap_size();var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}var minHeapSize=16777216;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(minHeapSize,requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _setTempRet0($i){setTempRet0($i|0)}InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_RegisteredPointer();init_embind();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();__ATINIT__.push({func:function(){___wasm_call_ctors()}});var asmLibraryArg={"t":__embind_finalize_value_object,"I":__embind_register_bool,"x":__embind_register_class,"w":__embind_register_class_constructor,"d":__embind_register_class_function,"k":__embind_register_constant,"H":__embind_register_emval,"n":__embind_register_enum,"a":__embind_register_enum_value,"A":__embind_register_float,"i":__embind_register_function,"j":__embind_register_integer,"h":__embind_register_memory_view,"B":__embind_register_std_string,"v":__embind_register_std_wstring,"u":__embind_register_value_object,"c":__embind_register_value_object_field,"J":__embind_register_void,"m":__emval_as,"s":__emval_call_void_method,"b":__emval_decref,"y":__emval_get_global,"p":__emval_get_method_caller,"r":__emval_get_module_property,"e":__emval_get_property,"g":__emval_incref,"q":__emval_new,"f":__emval_new_cstring,"l":__emval_run_destructors,"o":_abort,"E":_emscripten_memcpy_big,"F":_emscripten_resize_heap,"G":_fd_close,"C":_fd_seek,"z":_fd_write,"D":_setTempRet0};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["M"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["N"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["O"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["P"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["Q"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["R"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}noExitRuntime=true;run(); + + + return BASIS.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = BASIS; +else if (typeof define === 'function' && define['amd']) + define([], function() { return BASIS; }); +else if (typeof exports === 'object') + exports["BASIS"] = BASIS; diff --git a/renderer/jsm/libs/basis/basis_transcoder.wasm b/renderer/jsm/libs/basis/basis_transcoder.wasm new file mode 100644 index 0000000000000000000000000000000000000000..4b9c3437170cf226600057096490d0a2fa8d74ea GIT binary patch literal 499935 zcmZQbEY4+QU|?XJ#;lgWSkG9Wz*G+<84{T5!EDBQ2$La!fgypV9wNvJqCqOb0t^Wd zK0^Wkue7> zo6Dfen8=vNz{!}%n9sn*n8;WFHldJ#oiUNI2y9L%_psn8@hNz`>Zv=mOU3%D~K+$mj-E=?*46z-m0fuJU4FVm{4ul8J?Z znVFNBpNWZ`fs2)qQI=VVk%dbIB+AOl!OFcctJTk&u(j4rJtW1oY>~jc$;r&bz{0@5$i&1f#vm%H#LCFX%FMvPz=j4G*qPZmSe02hSeSX) zS(y1)nK*da8CjTk*%_ro7c=+Y{8F@K) zSQywjnOPZ`1o#*@*qPaxnL+uNiG_iMow0y%F5_HAR(3|l2BwAvCN@sSdPc_!?=CZO zv#WA2dNVOF`Yk@I>v&vjB6NIGp=G>$+(1ZG2OsAO^F`i;N$uyVo1k-V*V@z`yk21|;Ji>IC z=@8Q##)C`;nD#U6W17RbmuU~vZl+yKJDGMcZD-oXw3TTK(`KekOdFXtFs)}=$F!Dd z4by6-RZJ_HRxmARTE?`LX$jL}rbSHO7(X+6?9Go$$f#*2(s z8SgWiUuL|NV9;RVG-Kib(+W&xOe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Qz`!8Lz{Maa2(Gn3RXqa(1E?Ni098VuN{m5}fuBoIP>`96oq>^olbajV zrr~B_;D*%nAf1kl^Mtq+ku-3DG%#?1RyA>gggHT`aWgpXo+rf3$iv`xe4Y@uD7bwC zCOE+)0}rUn?f4a>hL6FqalR0@D5z=40wNeVAH-ZUd=Q4m-o|&4NTUdhDoVmIsOl1MD;ed^* zF~r9wS0u)#mnIga#3v>fmSz^EDx{>Aq$Zc7rYIDpCYKf!XO^WZz!z>MmVoB*gG($y zGZgWlaZ2zwU&gMope zlYxPui-Ccm8*~?np#dT+jf}x=NlDC2%_~XFL3R!(d@LqG!l#UZfk9;w3q#H%76z9* z2)kku3qulAyk!y#`0Q_xnhBFw7(nM@gV=K>u`nb;)vTDr!T=gv28nN(#KKSl6+bWu zG;anm^UNd`@IV_#%?*%!P&H2`u`uL9*&imcFr-1*eK)CPVxT3PXp95VQJ_%<2aX>@h$F_+W#3H=uS-MpHM1fq`Kv0|Ub} zbo)VRpg0p-vINKDhRG}pAiF_sFqr~z!*n#WXMhGY85kI5VVG?gA77S>)o@Up@=QUP zy#VUJ*+^#3VQ_r1LWo=FLJ|YRlw<~mOGyk250V%dJ|rA^Nj;mKAisKKfg}9jmzJ~w+v>cJ9 literal 0 HcmV?d00001 diff --git a/renderer/jsm/libs/chevrotain.module.min.js b/renderer/jsm/libs/chevrotain.module.min.js new file mode 100644 index 0000000..424790c --- /dev/null +++ b/renderer/jsm/libs/chevrotain.module.min.js @@ -0,0 +1,141 @@ +/*! chevrotain - v9.0.1 */ +var R=(t,e)=>()=>(e||(e={exports:{}},t(e.exports,e)),e.exports);var Er=R(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.VERSION=void 0;Pt.VERSION="9.0.1"});var k=R((exports,module)=>{"use strict";var __spreadArray=exports&&exports.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r{(function(t,e){typeof define=="function"&&define.amd?define([],e):typeof St=="object"&&St.exports?St.exports=e():t.regexpToAst=e()})(typeof self!="undefined"?self:sn,function(){function t(){}t.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},t.prototype.restoreState=function(u){this.idx=u.idx,this.input=u.input,this.groupIdx=u.groupIdx},t.prototype.pattern=function(u){this.idx=0,this.input=u,this.groupIdx=0,this.consumeChar("/");var d=this.disjunction();this.consumeChar("/");for(var A={type:"Flags",loc:{begin:this.idx,end:u.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":o(A,"global");break;case"i":o(A,"ignoreCase");break;case"m":o(A,"multiLine");break;case"u":o(A,"unicode");break;case"y":o(A,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:A,value:d,loc:this.loc(0)}},t.prototype.disjunction=function(){var u=[],d=this.idx;for(u.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),u.push(this.alternative());return{type:"Disjunction",value:u,loc:this.loc(d)}},t.prototype.alternative=function(){for(var u=[],d=this.idx;this.isTerm();)u.push(this.term());return{type:"Alternative",value:u,loc:this.loc(d)}},t.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},t.prototype.assertion=function(){var u=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(u)};case"$":return{type:"EndAnchor",loc:this.loc(u)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(u)};case"B":return{type:"NonWordBoundary",loc:this.loc(u)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var d;switch(this.popChar()){case"=":d="Lookahead";break;case"!":d="NegativeLookahead";break}s(d);var A=this.disjunction();return this.consumeChar(")"),{type:d,value:A,loc:this.loc(u)}}c()},t.prototype.quantifier=function(u){var d,A=this.idx;switch(this.popChar()){case"*":d={atLeast:0,atMost:Infinity};break;case"+":d={atLeast:1,atMost:Infinity};break;case"?":d={atLeast:0,atMost:1};break;case"{":var _=this.integerIncludingZero();switch(this.popChar()){case"}":d={atLeast:_,atMost:_};break;case",":var g;this.isDigit()?(g=this.integerIncludingZero(),d={atLeast:_,atMost:g}):d={atLeast:_,atMost:Infinity},this.consumeChar("}");break}if(u===!0&&d===void 0)return;s(d);break}if(!(u===!0&&d===void 0))return s(d),this.peekChar(0)==="?"?(this.consumeChar("?"),d.greedy=!1):d.greedy=!0,d.type="Quantifier",d.loc=this.loc(A),d},t.prototype.atom=function(){var u,d=this.idx;switch(this.peekChar()){case".":u=this.dotAll();break;case"\\":u=this.atomEscape();break;case"[":u=this.characterClass();break;case"(":u=this.group();break}return u===void 0&&this.isPatternCharacter()&&(u=this.patternCharacter()),s(u),u.loc=this.loc(d),this.isQuantifier()&&(u.quantifier=this.quantifier()),u},t.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[i(` +`),i("\r"),i("\u2028"),i("\u2029")]}},t.prototype.atomEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},t.prototype.decimalEscapeAtom=function(){var u=this.positiveInteger();return{type:"GroupBackReference",value:u}},t.prototype.characterClassEscape=function(){var u,d=!1;switch(this.popChar()){case"d":u=p;break;case"D":u=p,d=!0;break;case"s":u=m;break;case"S":u=m,d=!0;break;case"w":u=l;break;case"W":u=l,d=!0;break}return s(u),{type:"Set",value:u,complement:d}},t.prototype.controlEscapeAtom=function(){var u;switch(this.popChar()){case"f":u=i("\f");break;case"n":u=i(` +`);break;case"r":u=i("\r");break;case"t":u=i(" ");break;case"v":u=i("\v");break}return s(u),{type:"Character",value:u}},t.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var u=this.popChar();if(/[a-zA-Z]/.test(u)===!1)throw Error("Invalid ");var d=u.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:d}},t.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:i("\0")}},t.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},t.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},t.prototype.identityEscapeAtom=function(){var u=this.popChar();return{type:"Character",value:i(u)}},t.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var u=this.popChar();return{type:"Character",value:i(u)}}},t.prototype.characterClass=function(){var u=[],d=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),d=!0);this.isClassAtom();){var A=this.classAtom(),_=A.type==="Character";if(_&&this.isRangeDash()){this.consumeChar("-");var g=this.classAtom(),y=g.type==="Character";if(y){if(g.value=this.input.length)throw Error("Unexpected end of input");this.idx++},t.prototype.loc=function(u){return{begin:u,end:this.idx}};var e=/[0-9a-fA-F]/,r=/[0-9]/,n=/[1-9]/;function i(u){return u.charCodeAt(0)}function a(u,d){u.length!==void 0?u.forEach(function(A){d.push(A)}):d.push(u)}function o(u,d){if(u[d]===!0)throw"duplicate flag "+d;u[d]=!0}function s(u){if(u===void 0)throw Error("Internal Error - Should never get here!")}function c(){throw Error("Internal Error - Should never get here!")}var f,p=[];for(f=i("0");f<=i("9");f++)p.push(f);var l=[i("_")].concat(p);for(f=i("a");f<=i("z");f++)l.push(f);for(f=i("A");f<=i("Z");f++)l.push(f);var m=[i(" "),i("\f"),i(` +`),i("\r"),i(" "),i("\v"),i(" "),i("\xA0"),i("\u1680"),i("\u2000"),i("\u2001"),i("\u2002"),i("\u2003"),i("\u2004"),i("\u2005"),i("\u2006"),i("\u2007"),i("\u2008"),i("\u2009"),i("\u200A"),i("\u2028"),i("\u2029"),i("\u202F"),i("\u205F"),i("\u3000"),i("\uFEFF")];function v(){}return v.prototype.visitChildren=function(u){for(var d in u){var A=u[d];u.hasOwnProperty(d)&&(A.type!==void 0?this.visit(A):Array.isArray(A)&&A.forEach(function(_){this.visit(_)},this))}},v.prototype.visit=function(u){switch(u.type){case"Pattern":this.visitPattern(u);break;case"Flags":this.visitFlags(u);break;case"Disjunction":this.visitDisjunction(u);break;case"Alternative":this.visitAlternative(u);break;case"StartAnchor":this.visitStartAnchor(u);break;case"EndAnchor":this.visitEndAnchor(u);break;case"WordBoundary":this.visitWordBoundary(u);break;case"NonWordBoundary":this.visitNonWordBoundary(u);break;case"Lookahead":this.visitLookahead(u);break;case"NegativeLookahead":this.visitNegativeLookahead(u);break;case"Character":this.visitCharacter(u);break;case"Set":this.visitSet(u);break;case"Group":this.visitGroup(u);break;case"GroupBackReference":this.visitGroupBackReference(u);break;case"Quantifier":this.visitQuantifier(u);break}this.visitChildren(u)},v.prototype.visitPattern=function(u){},v.prototype.visitFlags=function(u){},v.prototype.visitDisjunction=function(u){},v.prototype.visitAlternative=function(u){},v.prototype.visitStartAnchor=function(u){},v.prototype.visitEndAnchor=function(u){},v.prototype.visitWordBoundary=function(u){},v.prototype.visitNonWordBoundary=function(u){},v.prototype.visitLookahead=function(u){},v.prototype.visitNegativeLookahead=function(u){},v.prototype.visitCharacter=function(u){},v.prototype.visitSet=function(u){},v.prototype.visitGroup=function(u){},v.prototype.visitGroupBackReference=function(u){},v.prototype.visitQuantifier=function(u){},{RegExpParser:t,BaseRegExpVisitor:v,VERSION:"0.5.0"}})});var Lt=R(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.clearRegExpParserCache=He.getRegExpAst=void 0;var Ga=xt(),Ct={},Wa=new Ga.RegExpParser;function Ba(t){var e=t.toString();if(Ct.hasOwnProperty(e))return Ct[e];var r=Wa.pattern(e);return Ct[e]=r,r}He.getRegExpAst=Ba;function qa(){Ct={}}He.clearRegExpParserCache=qa});var pn=R(re=>{"use strict";var ja=re&&re.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(re,"__esModule",{value:!0});re.canMatchCharCode=re.firstCharOptimizedIndices=re.getOptimizedStartCodesIndices=re.failedOptimizationPrefixMsg=void 0;var un=xt(),pe=k(),cn=Lt(),Ce=Tr(),ln="Complement Sets are not supported for first char optimization";re.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations: +`;function Va(t,e){e===void 0&&(e=!1);try{var r=cn.getRegExpAst(t),n=Mt(r.value,{},r.flags.ignoreCase);return n}catch(a){if(a.message===ln)e&&pe.PRINT_WARNING(""+re.failedOptimizationPrefixMsg+(" Unable to optimize: < "+t.toString()+` > +`)+` Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{var i="";e&&(i=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),pe.PRINT_ERROR(re.failedOptimizationPrefixMsg+` +`+(" Failed parsing: < "+t.toString()+` > +`)+(" Using the regexp-to-ast library version: "+un.VERSION+` +`)+" Please open an issue at: https://github.com/bd82/regexp-to-ast/issues"+i)}}return[]}re.getOptimizedStartCodesIndices=Va;function Mt(t,e,r){switch(t.type){case"Disjunction":for(var n=0;n=Ce.minOptimizationVal)for(var m=p.from>=Ce.minOptimizationVal?p.from:Ce.minOptimizationVal,v=p.to,u=Ce.charCodeToOptimizedIndex(m),d=Ce.charCodeToOptimizedIndex(v),A=u;A<=d;A++)e[A]=A}}});break;case"Group":Mt(o.value,e,r);break;default:throw Error("Non Exhaustive Match")}var s=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&yr(o)===!1||o.type!=="Group"&&s===!1)break}break;default:throw Error("non exhaustive match!")}return pe.values(e)}re.firstCharOptimizedIndices=Mt;function bt(t,e,r){var n=Ce.charCodeToOptimizedIndex(t);e[n]=n,r===!0&&Ka(t,e)}function Ka(t,e){var r=String.fromCharCode(t),n=r.toUpperCase();if(n!==r){var i=Ce.charCodeToOptimizedIndex(n.charCodeAt(0));e[i]=i}else{var a=r.toLowerCase();if(a!==r){var i=Ce.charCodeToOptimizedIndex(a.charCodeAt(0));e[i]=i}}}function fn(t,e){return pe.find(t.value,function(r){if(typeof r=="number")return pe.contains(e,r);var n=r;return pe.find(e,function(i){return n.from<=i&&i<=n.to})!==void 0})}function yr(t){return t.quantifier&&t.quantifier.atLeast===0?!0:t.value?pe.isArray(t.value)?pe.every(t.value,yr):yr(t.value):!1}var za=function(t){ja(e,t);function e(r){var n=t.call(this)||this;return n.targetCharCodes=r,n.found=!1,n}return e.prototype.visitChildren=function(r){if(this.found!==!0){switch(r.type){case"Lookahead":this.visitLookahead(r);return;case"NegativeLookahead":this.visitNegativeLookahead(r);return}t.prototype.visitChildren.call(this,r)}},e.prototype.visitCharacter=function(r){pe.contains(this.targetCharCodes,r.value)&&(this.found=!0)},e.prototype.visitSet=function(r){r.complement?fn(r,this.targetCharCodes)===void 0&&(this.found=!0):fn(r,this.targetCharCodes)!==void 0&&(this.found=!0)},e}(un.BaseRegExpVisitor);function Ha(t,e){if(e instanceof RegExp){var r=cn.getRegExpAst(e),n=new za(t);return n.visit(r),n.found}else return pe.find(e,function(i){return pe.contains(t,i.charCodeAt(0))})!==void 0}re.canMatchCharCode=Ha});var Tr=R(T=>{"use strict";var hn=T&&T.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(T,"__esModule",{value:!0});T.charCodeToOptimizedIndex=T.minOptimizationVal=T.buildLineBreakIssueMessage=T.LineTerminatorOptimizedTester=T.isShortPattern=T.isCustomPattern=T.cloneEmptyGroups=T.performWarningRuntimeChecks=T.performRuntimeChecks=T.addStickyFlag=T.addStartOfInput=T.findUnreachablePatterns=T.findModesThatDoNotExist=T.findInvalidGroupType=T.findDuplicatePatterns=T.findUnsupportedFlags=T.findStartOfInputAnchor=T.findEmptyMatchRegExps=T.findEndOfInputAnchor=T.findInvalidPatterns=T.findMissingPatterns=T.validatePatterns=T.analyzeTokenTypes=T.enableSticky=T.disableSticky=T.SUPPORT_STICKY=T.MODES=T.DEFAULT_MODE=void 0;var dn=xt(),F=ft(),h=k(),Ye=pn(),vn=Lt(),Ae="PATTERN";T.DEFAULT_MODE="defaultMode";T.MODES="modes";T.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky=="boolean";function Ya(){T.SUPPORT_STICKY=!1}T.disableSticky=Ya;function Xa(){T.SUPPORT_STICKY=!0}T.enableSticky=Xa;function Za(t,e){e=h.defaults(e,{useSticky:T.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:function(g,y){return y()}});var r=e.tracer;r("initCharCodeToOptimizedIndexMap",function(){$a()});var n;r("Reject Lexer.NA",function(){n=h.reject(t,function(g){return g[Ae]===F.Lexer.NA})});var i=!1,a;r("Transform Patterns",function(){i=!1,a=h.map(n,function(g){var y=g[Ae];if(h.isRegExp(y)){var b=y.source;return b.length===1&&b!=="^"&&b!=="$"&&b!=="."&&!y.ignoreCase?b:b.length===2&&b[0]==="\\"&&!h.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],b[1])?b[1]:e.useSticky?gr(y):_r(y)}else{if(h.isFunction(y))return i=!0,{exec:y};if(h.has(y,"exec"))return i=!0,y;if(typeof y=="string"){if(y.length===1)return y;var L=y.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),se=new RegExp(L);return e.useSticky?gr(se):_r(se)}else throw Error("non exhaustive match")}})});var o,s,c,f,p;r("misc mapping",function(){o=h.map(n,function(g){return g.tokenTypeIdx}),s=h.map(n,function(g){var y=g.GROUP;if(y!==F.Lexer.SKIPPED){if(h.isString(y))return y;if(h.isUndefined(y))return!1;throw Error("non exhaustive match")}}),c=h.map(n,function(g){var y=g.LONGER_ALT;if(y){var b=h.indexOf(n,y);return b}}),f=h.map(n,function(g){return g.PUSH_MODE}),p=h.map(n,function(g){return h.has(g,"POP_MODE")})});var l;r("Line Terminator Handling",function(){var g=Tn(e.lineTerminatorCharacters);l=h.map(n,function(y){return!1}),e.positionTracking!=="onlyOffset"&&(l=h.map(n,function(y){if(h.has(y,"LINE_BREAKS"))return y.LINE_BREAKS;if(En(y,g)===!1)return Ye.canMatchCharCode(g,y.PATTERN)}))});var m,v,u,d;r("Misc Mapping #2",function(){m=h.map(n,Ar),v=h.map(a,mn),u=h.reduce(n,function(g,y){var b=y.GROUP;return h.isString(b)&&b!==F.Lexer.SKIPPED&&(g[b]=[]),g},{}),d=h.map(a,function(g,y){return{pattern:a[y],longerAlt:c[y],canLineTerminator:l[y],isCustom:m[y],short:v[y],group:s[y],push:f[y],pop:p[y],tokenTypeIdx:o[y],tokenType:n[y]}})});var A=!0,_=[];return e.safeMode||r("First Char Optimization",function(){_=h.reduce(n,function(g,y,b){if(typeof y.PATTERN=="string"){var L=y.PATTERN.charCodeAt(0),se=Or(L);Rr(g,se,d[b])}else if(h.isArray(y.START_CHARS_HINT)){var fe;h.forEach(y.START_CHARS_HINT,function(ue){var Q=typeof ue=="string"?ue.charCodeAt(0):ue,te=Or(Q);fe!==te&&(fe=te,Rr(g,te,d[b]))})}else if(h.isRegExp(y.PATTERN))if(y.PATTERN.unicode)A=!1,e.ensureOptimizations&&h.PRINT_ERROR(""+Ye.failedOptimizationPrefixMsg+(" Unable to analyze < "+y.PATTERN.toString()+` > pattern. +`)+` The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{var Z=Ye.getOptimizedStartCodesIndices(y.PATTERN,e.ensureOptimizations);h.isEmpty(Z)&&(A=!1),h.forEach(Z,function(ue){Rr(g,ue,d[b])})}else e.ensureOptimizations&&h.PRINT_ERROR(""+Ye.failedOptimizationPrefixMsg+(" TokenType: <"+y.name+`> is using a custom token pattern without providing parameter. +`)+` This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),A=!1;return g},[])}),r("ArrayPacking",function(){_=h.packArray(_)}),{emptyGroups:u,patternIdxToConfig:d,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:A}}T.analyzeTokenTypes=Za;function Ja(t,e){var r=[],n=yn(t);r=r.concat(n.errors);var i=_n(n.valid),a=i.valid;return r=r.concat(i.errors),r=r.concat(Qa(a)),r=r.concat(gn(a)),r=r.concat(An(a,e)),r=r.concat(Rn(a)),r}T.validatePatterns=Ja;function Qa(t){var e=[],r=h.filter(t,function(n){return h.isRegExp(n[Ae])});return e=e.concat(On(r)),e=e.concat(In(r)),e=e.concat(kn(r)),e=e.concat(Pn(r)),e=e.concat(Nn(r)),e}function yn(t){var e=h.filter(t,function(i){return!h.has(i,Ae)}),r=h.map(e,function(i){return{message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:F.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[i]}}),n=h.difference(t,e);return{errors:r,valid:n}}T.findMissingPatterns=yn;function _n(t){var e=h.filter(t,function(i){var a=i[Ae];return!h.isRegExp(a)&&!h.isFunction(a)&&!h.has(a,"exec")&&!h.isString(a)}),r=h.map(e,function(i){return{message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:F.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[i]}}),n=h.difference(t,e);return{errors:r,valid:n}}T.findInvalidPatterns=_n;var eo=/[^\\][\$]/;function On(t){var e=function(i){hn(a,i);function a(){var o=i!==null&&i.apply(this,arguments)||this;return o.found=!1,o}return a.prototype.visitEndAnchor=function(o){this.found=!0},a}(dn.BaseRegExpVisitor),r=h.filter(t,function(i){var a=i[Ae];try{var o=vn.getRegExpAst(a),s=new e;return s.visit(o),s.found}catch(c){return eo.test(a.source)}}),n=h.map(r,function(i){return{message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:F.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[i]}});return n}T.findEndOfInputAnchor=On;function Nn(t){var e=h.filter(t,function(n){var i=n[Ae];return i.test("")}),r=h.map(e,function(n){return{message:"Token Type: ->"+n.name+"<- static 'PATTERN' must not match an empty string",type:F.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[n]}});return r}T.findEmptyMatchRegExps=Nn;var to=/[^\\[][\^]|^\^/;function In(t){var e=function(i){hn(a,i);function a(){var o=i!==null&&i.apply(this,arguments)||this;return o.found=!1,o}return a.prototype.visitStartAnchor=function(o){this.found=!0},a}(dn.BaseRegExpVisitor),r=h.filter(t,function(i){var a=i[Ae];try{var o=vn.getRegExpAst(a),s=new e;return s.visit(o),s.found}catch(c){return to.test(a.source)}}),n=h.map(r,function(i){return{message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:F.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[i]}});return n}T.findStartOfInputAnchor=In;function kn(t){var e=h.filter(t,function(n){var i=n[Ae];return i instanceof RegExp&&(i.multiline||i.global)}),r=h.map(e,function(n){return{message:"Token Type: ->"+n.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:F.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[n]}});return r}T.findUnsupportedFlags=kn;function Pn(t){var e=[],r=h.map(t,function(a){return h.reduce(t,function(o,s){return a.PATTERN.source===s.PATTERN.source&&!h.contains(e,s)&&s.PATTERN!==F.Lexer.NA&&(e.push(s),o.push(s)),o},[])});r=h.compact(r);var n=h.filter(r,function(a){return a.length>1}),i=h.map(n,function(a){var o=h.map(a,function(c){return c.name}),s=h.first(a).PATTERN;return{message:"The same RegExp pattern ->"+s+"<-"+("has been used in all of the following Token Types: "+o.join(", ")+" <-"),type:F.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:a}});return i}T.findDuplicatePatterns=Pn;function gn(t){var e=h.filter(t,function(n){if(!h.has(n,"GROUP"))return!1;var i=n.GROUP;return i!==F.Lexer.SKIPPED&&i!==F.Lexer.NA&&!h.isString(i)}),r=h.map(e,function(n){return{message:"Token Type: ->"+n.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:F.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[n]}});return r}T.findInvalidGroupType=gn;function An(t,e){var r=h.filter(t,function(i){return i.PUSH_MODE!==void 0&&!h.contains(e,i.PUSH_MODE)}),n=h.map(r,function(i){var a="Token Type: ->"+i.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+i.PUSH_MODE+"<-which does not exist";return{message:a,type:F.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}});return n}T.findModesThatDoNotExist=An;function Rn(t){var e=[],r=h.reduce(t,function(n,i,a){var o=i.PATTERN;return o===F.Lexer.NA||(h.isString(o)?n.push({str:o,idx:a,tokenType:i}):h.isRegExp(o)&&no(o)&&n.push({str:o.source,idx:a,tokenType:i})),n},[]);return h.forEach(t,function(n,i){h.forEach(r,function(a){var o=a.str,s=a.idx,c=a.tokenType;if(i"+n.name+"<-")+`in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:f,type:F.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[n,c]})}})}),e}T.findUnreachablePatterns=Rn;function ro(t,e){if(h.isRegExp(e)){var r=e.exec(t);return r!==null&&r.index===0}else{if(h.isFunction(e))return e(t,0,[],{});if(h.has(e,"exec"))return e.exec(t,0,[],{});if(typeof e=="string")return e===t;throw Error("non exhaustive match")}}function no(t){var e=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return h.find(e,function(r){return t.source.indexOf(r)!==-1})===void 0}function _r(t){var e=t.ignoreCase?"i":"";return new RegExp("^(?:"+t.source+")",e)}T.addStartOfInput=_r;function gr(t){var e=t.ignoreCase?"iy":"y";return new RegExp(""+t.source,e)}T.addStickyFlag=gr;function io(t,e,r){var n=[];return h.has(t,T.DEFAULT_MODE)||n.push({message:"A MultiMode Lexer cannot be initialized without a <"+T.DEFAULT_MODE+`> property in its definition +`,type:F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),h.has(t,T.MODES)||n.push({message:"A MultiMode Lexer cannot be initialized without a <"+T.MODES+`> property in its definition +`,type:F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),h.has(t,T.MODES)&&h.has(t,T.DEFAULT_MODE)&&!h.has(t.modes,t.defaultMode)&&n.push({message:"A MultiMode Lexer cannot be initialized with a "+T.DEFAULT_MODE+": <"+t.defaultMode+`>which does not exist +`,type:F.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),h.has(t,T.MODES)&&h.forEach(t.modes,function(i,a){h.forEach(i,function(o,s){h.isUndefined(o)&&n.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+a+"> at index: <"+s+`> +`),type:F.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),n}T.performRuntimeChecks=io;function ao(t,e,r){var n=[],i=!1,a=h.compact(h.flatten(h.mapValues(t.modes,function(c){return c}))),o=h.reject(a,function(c){return c[Ae]===F.Lexer.NA}),s=Tn(r);return e&&h.forEach(o,function(c){var f=En(c,s);if(f!==!1){var p=Sn(c,f),l={message:p,type:f.issue,tokenType:c};n.push(l)}else h.has(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):Ye.canMatchCharCode(s,c.PATTERN)&&(i=!0)}),e&&!i&&n.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:F.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),n}T.performWarningRuntimeChecks=ao;function oo(t){var e={},r=h.keys(t);return h.forEach(r,function(n){var i=t[n];if(h.isArray(i))e[n]=[];else throw Error("non exhaustive match")}),e}T.cloneEmptyGroups=oo;function Ar(t){var e=t.PATTERN;if(h.isRegExp(e))return!1;if(h.isFunction(e))return!0;if(h.has(e,"exec"))return!0;if(h.isString(e))return!1;throw Error("non exhaustive match")}T.isCustomPattern=Ar;function mn(t){return h.isString(t)&&t.length===1?t.charCodeAt(0):!1}T.isShortPattern=mn;T.LineTerminatorOptimizedTester={test:function(t){for(var e=t.length,r=this.lastIndex;r Token Type +`)+(" Root cause: "+e.errMsg+`. +`)+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(e.issue===F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. +`+(" The problem is in the <"+t.name+`> Token Type +`)+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}T.buildLineBreakIssueMessage=Sn;function Tn(t){var e=h.map(t,function(r){return h.isString(r)&&r.length>0?r.charCodeAt(0):r});return e}function Rr(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}T.minOptimizationVal=256;var Ft=[];function Or(t){return t255?255+~~(t/255):t}}});var Xe=R(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.isTokenType=N.hasExtendingTokensTypesMapProperty=N.hasExtendingTokensTypesProperty=N.hasCategoriesProperty=N.hasShortKeyProperty=N.singleAssignCategoriesToksMap=N.assignCategoriesMapProp=N.assignCategoriesTokensProp=N.assignTokenDefaultProps=N.expandCategories=N.augmentTokenTypes=N.tokenIdxToClass=N.tokenShortNameIdx=N.tokenStructuredMatcherNoCategories=N.tokenStructuredMatcher=void 0;var V=k();function so(t,e){var r=t.tokenTypeIdx;return r===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[r]===!0}N.tokenStructuredMatcher=so;function uo(t,e){return t.tokenTypeIdx===e.tokenTypeIdx}N.tokenStructuredMatcherNoCategories=uo;N.tokenShortNameIdx=1;N.tokenIdxToClass={};function co(t){var e=xn(t);Cn(e),Mn(e),Ln(e),V.forEach(e,function(r){r.isParent=r.categoryMatches.length>0})}N.augmentTokenTypes=co;function xn(t){for(var e=V.cloneArr(t),r=t,n=!0;n;){r=V.compact(V.flatten(V.map(r,function(a){return a.CATEGORIES})));var i=V.difference(r,e);e=e.concat(i),V.isEmpty(i)?n=!1:r=i}return e}N.expandCategories=xn;function Cn(t){V.forEach(t,function(e){bn(e)||(N.tokenIdxToClass[N.tokenShortNameIdx]=e,e.tokenTypeIdx=N.tokenShortNameIdx++),Nr(e)&&!V.isArray(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Nr(e)||(e.CATEGORIES=[]),Fn(e)||(e.categoryMatches=[]),wn(e)||(e.categoryMatchesMap={})})}N.assignTokenDefaultProps=Cn;function Ln(t){V.forEach(t,function(e){e.categoryMatches=[],V.forEach(e.categoryMatchesMap,function(r,n){e.categoryMatches.push(N.tokenIdxToClass[n].tokenTypeIdx)})})}N.assignCategoriesTokensProp=Ln;function Mn(t){V.forEach(t,function(e){Ir([],e)})}N.assignCategoriesMapProp=Mn;function Ir(t,e){V.forEach(t,function(r){e.categoryMatchesMap[r.tokenTypeIdx]=!0}),V.forEach(e.CATEGORIES,function(r){var n=t.concat(e);V.contains(n,r)||Ir(n,r)})}N.singleAssignCategoriesToksMap=Ir;function bn(t){return V.has(t,"tokenTypeIdx")}N.hasShortKeyProperty=bn;function Nr(t){return V.has(t,"CATEGORIES")}N.hasCategoriesProperty=Nr;function Fn(t){return V.has(t,"categoryMatches")}N.hasExtendingTokensTypesProperty=Fn;function wn(t){return V.has(t,"categoryMatchesMap")}N.hasExtendingTokensTypesMapProperty=wn;function lo(t){return V.has(t,"tokenTypeIdx")}N.isTokenType=lo});var kr=R(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.defaultLexerErrorProvider=void 0;wt.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(t){return"Unable to pop Lexer Mode after encountering Token ->"+t.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(t,e,r,n,i){return"unexpected character: ->"+t.charAt(e)+"<- at offset: "+e+","+(" skipped "+r+" characters.")}}});var ft=R(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Lexer=qe.LexerDefinitionErrorType=void 0;var Ee=Tr(),w=k(),fo=Xe(),po=kr(),ho=Lt(),vo;(function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"})(vo=qe.LexerDefinitionErrorType||(qe.LexerDefinitionErrorType={}));var pt={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:po.defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(pt);var mo=function(){function t(e,r){var n=this;if(r===void 0&&(r=pt),this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},typeof r=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=w.merge(pt,r);var i=this.config.traceInitPerf;i===!0?(this.traceInitMaxIdent=Infinity,this.traceInitPerf=!0):typeof i=="number"&&(this.traceInitMaxIdent=i,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var a,o=!0;n.TRACE_INIT("Lexer Config handling",function(){if(n.config.lineTerminatorsPattern===pt.lineTerminatorsPattern)n.config.lineTerminatorsPattern=Ee.LineTerminatorOptimizedTester;else if(n.config.lineTerminatorCharacters===pt.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(r.safeMode&&r.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');n.trackStartLines=/full|onlyStart/i.test(n.config.positionTracking),n.trackEndLines=/full/i.test(n.config.positionTracking),w.isArray(e)?(a={modes:{}},a.modes[Ee.DEFAULT_MODE]=w.cloneArr(e),a[Ee.DEFAULT_MODE]=Ee.DEFAULT_MODE):(o=!1,a=w.cloneObj(e))}),n.config.skipValidations===!1&&(n.TRACE_INIT("performRuntimeChecks",function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(Ee.performRuntimeChecks(a,n.trackStartLines,n.config.lineTerminatorCharacters))}),n.TRACE_INIT("performWarningRuntimeChecks",function(){n.lexerDefinitionWarning=n.lexerDefinitionWarning.concat(Ee.performWarningRuntimeChecks(a,n.trackStartLines,n.config.lineTerminatorCharacters))})),a.modes=a.modes?a.modes:{},w.forEach(a.modes,function(p,l){a.modes[l]=w.reject(p,function(m){return w.isUndefined(m)})});var s=w.keys(a.modes);if(w.forEach(a.modes,function(p,l){n.TRACE_INIT("Mode: <"+l+"> processing",function(){if(n.modes.push(l),n.config.skipValidations===!1&&n.TRACE_INIT("validatePatterns",function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(Ee.validatePatterns(p,s))}),w.isEmpty(n.lexerDefinitionErrors)){fo.augmentTokenTypes(p);var m;n.TRACE_INIT("analyzeTokenTypes",function(){m=Ee.analyzeTokenTypes(p,{lineTerminatorCharacters:n.config.lineTerminatorCharacters,positionTracking:r.positionTracking,ensureOptimizations:r.ensureOptimizations,safeMode:r.safeMode,tracer:n.TRACE_INIT.bind(n)})}),n.patternIdxToConfig[l]=m.patternIdxToConfig,n.charCodeToPatternIdxToConfig[l]=m.charCodeToPatternIdxToConfig,n.emptyGroups=w.merge(n.emptyGroups,m.emptyGroups),n.hasCustom=m.hasCustom||n.hasCustom,n.canModeBeOptimized[l]=m.canBeOptimized}})}),n.defaultMode=a.defaultMode,!w.isEmpty(n.lexerDefinitionErrors)&&!n.config.deferDefinitionErrorsHandling){var c=w.map(n.lexerDefinitionErrors,function(p){return p.message}),f=c.join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+f)}w.forEach(n.lexerDefinitionWarning,function(p){w.PRINT_WARNING(p.message)}),n.TRACE_INIT("Choosing sub-methods implementations",function(){if(Ee.SUPPORT_STICKY?(n.chopInput=w.IDENTITY,n.match=n.matchWithTest):(n.updateLastIndex=w.NOOP,n.match=n.matchWithExec),o&&(n.handleModes=w.NOOP),n.trackStartLines===!1&&(n.computeNewColumn=w.IDENTITY),n.trackEndLines===!1&&(n.updateTokenEndLineColumnLocation=w.NOOP),/full/i.test(n.config.positionTracking))n.createTokenInstance=n.createFullToken;else if(/onlyStart/i.test(n.config.positionTracking))n.createTokenInstance=n.createStartOnlyToken;else if(/onlyOffset/i.test(n.config.positionTracking))n.createTokenInstance=n.createOffsetOnlyToken;else throw Error('Invalid config option: "'+n.config.positionTracking+'"');n.hasCustom?(n.addToken=n.addTokenUsingPush,n.handlePayload=n.handlePayloadWithCustom):(n.addToken=n.addTokenUsingMemberAccess,n.handlePayload=n.handlePayloadNoCustom)}),n.TRACE_INIT("Failed Optimization Warnings",function(){var p=w.reduce(n.canModeBeOptimized,function(l,m,v){return m===!1&&l.push(v),l},[]);if(r.ensureOptimizations&&!w.isEmpty(p))throw Error("Lexer Modes: < "+p.join(", ")+` > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),n.TRACE_INIT("clearRegExpParserCache",function(){ho.clearRegExpParserCache()}),n.TRACE_INIT("toFastProperties",function(){w.toFastProperties(n)})})}return t.prototype.tokenize=function(e,r){if(r===void 0&&(r=this.defaultMode),!w.isEmpty(this.lexerDefinitionErrors)){var n=w.map(this.lexerDefinitionErrors,function(o){return o.message}),i=n.join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+i)}var a=this.tokenizeInternal(e,r);return a},t.prototype.tokenizeInternal=function(e,r){var n=this,i,a,o,s,c,f,p,l,m,v,u,d,A,_,g,y=e,b=y.length,L=0,se=0,fe=this.hasCustom?0:Math.floor(e.length/10),Z=new Array(fe),ue=[],Q=this.trackStartLines?1:void 0,te=this.trackStartLines?1:void 0,xe=Ee.cloneEmptyGroups(this.emptyGroups),it=this.trackStartLines,at=this.config.lineTerminatorsPattern,Ke=0,we=[],ot=[],It=[],Qr=[];Object.freeze(Qr);var st=void 0;function Jr(){return we}function en(J){var lt=Ee.charCodeToOptimizedIndex(J),ze=ot[lt];return ze===void 0?Qr:ze}var wa=function(J){if(It.length===1&&J.tokenType.PUSH_MODE===void 0){var lt=n.config.errorMessageProvider.buildUnableToPopLexerModeMessage(J);ue.push({offset:J.startOffset,line:J.startLine!==void 0?J.startLine:void 0,column:J.startColumn!==void 0?J.startColumn:void 0,length:J.image.length,message:lt})}else{It.pop();var ze=w.last(It);we=n.patternIdxToConfig[ze],ot=n.charCodeToPatternIdxToConfig[ze],Ke=we.length;var Ua=n.canModeBeOptimized[ze]&&n.config.safeMode===!1;ot&&Ua?st=en:st=Jr}};function tn(J){It.push(J),ot=this.charCodeToPatternIdxToConfig[J],we=this.patternIdxToConfig[J],Ke=we.length,Ke=we.length;var lt=this.canModeBeOptimized[J]&&this.config.safeMode===!1;ot&<?st=en:st=Jr}tn.call(this,r);for(var me;Lc.length&&(c=o,f=p,me=fr)}break}}if(c!==null){if(l=c.length,m=me.group,m!==void 0&&(v=me.tokenTypeIdx,u=this.createTokenInstance(c,L,v,me.tokenType,Q,te,l),this.handlePayload(u,f),m===!1?se=this.addToken(Z,se,u):xe[m].push(u)),e=this.chopInput(e,l),L=L+l,te=this.computeNewColumn(te,l),it===!0&&me.canLineTerminator===!0){var kt=0,hr=void 0,dr=void 0;at.lastIndex=0;do hr=at.test(c),hr===!0&&(dr=at.lastIndex-1,kt++);while(hr===!0);kt!==0&&(Q=Q+kt,te=l-dr,this.updateTokenEndLineColumnLocation(u,m,dr,kt,Q,te,l))}this.handleModes(me,wa,tn,u)}else{for(var vr=L,an=Q,on=te,ct=!1;!ct&&L <"+e+">");var i=w.timer(r),a=i.time,o=i.value,s=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,o}else return r()},t.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",t.NA=/NOT_APPLICABLE/,t}();qe.Lexer=mo});var Ue=R(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.tokenMatcher=H.createTokenInstance=H.EOF=H.createToken=H.hasTokenLabel=H.tokenName=H.tokenLabel=void 0;var Te=k(),Eo=ft(),Pr=Xe();function To(t){return Dn(t)?t.LABEL:t.name}H.tokenLabel=To;function yo(t){return t.name}H.tokenName=yo;function Dn(t){return Te.isString(t.LABEL)&&t.LABEL!==""}H.hasTokenLabel=Dn;var _o="parent",Un="categories",Gn="label",Wn="group",Bn="push_mode",qn="pop_mode",jn="longer_alt",Vn="line_breaks",Kn="start_chars_hint";function zn(t){return go(t)}H.createToken=zn;function go(t){var e=t.pattern,r={};if(r.name=t.name,Te.isUndefined(e)||(r.PATTERN=e),Te.has(t,_o))throw`The parent property is no longer supported. +See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return Te.has(t,Un)&&(r.CATEGORIES=t[Un]),Pr.augmentTokenTypes([r]),Te.has(t,Gn)&&(r.LABEL=t[Gn]),Te.has(t,Wn)&&(r.GROUP=t[Wn]),Te.has(t,qn)&&(r.POP_MODE=t[qn]),Te.has(t,Bn)&&(r.PUSH_MODE=t[Bn]),Te.has(t,jn)&&(r.LONGER_ALT=t[jn]),Te.has(t,Vn)&&(r.LINE_BREAKS=t[Vn]),Te.has(t,Kn)&&(r.START_CHARS_HINT=t[Kn]),r}H.EOF=zn({name:"EOF",pattern:Eo.Lexer.NA});Pr.augmentTokenTypes([H.EOF]);function Ao(t,e,r,n,i,a,o,s){return{image:e,startOffset:r,endOffset:n,startLine:i,endLine:a,startColumn:o,endColumn:s,tokenTypeIdx:t.tokenTypeIdx,tokenType:t}}H.createTokenInstance=Ao;function Ro(t,e){return Pr.tokenStructuredMatcher(t,e)}H.tokenMatcher=Ro});var ne=R(S=>{"use strict";var Le=S&&S.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(S,"__esModule",{value:!0});S.serializeProduction=S.serializeGrammar=S.Terminal=S.Alternation=S.RepetitionWithSeparator=S.Repetition=S.RepetitionMandatoryWithSeparator=S.RepetitionMandatory=S.Option=S.Alternative=S.Rule=S.NonTerminal=S.AbstractProduction=void 0;var G=k(),Oo=Ue(),Re=function(){function t(e){this._definition=e}return Object.defineProperty(t.prototype,"definition",{get:function(){return this._definition},set:function(e){this._definition=e},enumerable:!1,configurable:!0}),t.prototype.accept=function(e){e.visit(this),G.forEach(this.definition,function(r){r.accept(e)})},t}();S.AbstractProduction=Re;var Hn=function(t){Le(e,t);function e(r){var n=t.call(this,[])||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return Object.defineProperty(e.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(r){},enumerable:!1,configurable:!0}),e.prototype.accept=function(r){r.visit(this)},e}(Re);S.NonTerminal=Hn;var Yn=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.orgText="",G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.Rule=Yn;var Xn=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.ignoreAmbiguities=!1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.Alternative=Xn;var $n=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.Option=$n;var Zn=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.RepetitionMandatory=Zn;var Qn=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.RepetitionMandatoryWithSeparator=Qn;var Jn=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.Repetition=Jn;var ei=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return e}(Re);S.RepetitionWithSeparator=ei;var ti=function(t){Le(e,t);function e(r){var n=t.call(this,r.definition)||this;return n.idx=1,n.ignoreAmbiguities=!1,n.hasPredicates=!1,G.assign(n,G.pick(r,function(i){return i!==void 0})),n}return Object.defineProperty(e.prototype,"definition",{get:function(){return this._definition},set:function(r){this._definition=r},enumerable:!1,configurable:!0}),e}(Re);S.Alternation=ti;var Dt=function(){function t(e){this.idx=1,G.assign(this,G.pick(e,function(r){return r!==void 0}))}return t.prototype.accept=function(e){e.visit(this)},t}();S.Terminal=Dt;function No(t){return G.map(t,ht)}S.serializeGrammar=No;function ht(t){function e(i){return G.map(i,ht)}if(t instanceof Hn)return{type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};if(t instanceof Xn)return{type:"Alternative",definition:e(t.definition)};if(t instanceof $n)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof Zn)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof Qn)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:ht(new Dt({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof ei)return{type:"RepetitionWithSeparator",idx:t.idx,separator:ht(new Dt({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof Jn)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof ti)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof Dt){var r={type:"Terminal",name:t.terminalType.name,label:Oo.tokenLabel(t.terminalType),idx:t.idx},n=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(r.pattern=G.isRegExp(n)?n.source:n),r}else{if(t instanceof Yn)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}}S.serializeProduction=ht});var Gt=R(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.RestWalker=void 0;var Sr=k(),ie=ne(),Io=function(){function t(){}return t.prototype.walk=function(e,r){var n=this;r===void 0&&(r=[]),Sr.forEach(e.definition,function(i,a){var o=Sr.drop(e.definition,a+1);if(i instanceof ie.NonTerminal)n.walkProdRef(i,o,r);else if(i instanceof ie.Terminal)n.walkTerminal(i,o,r);else if(i instanceof ie.Alternative)n.walkFlat(i,o,r);else if(i instanceof ie.Option)n.walkOption(i,o,r);else if(i instanceof ie.RepetitionMandatory)n.walkAtLeastOne(i,o,r);else if(i instanceof ie.RepetitionMandatoryWithSeparator)n.walkAtLeastOneSep(i,o,r);else if(i instanceof ie.RepetitionWithSeparator)n.walkManySep(i,o,r);else if(i instanceof ie.Repetition)n.walkMany(i,o,r);else if(i instanceof ie.Alternation)n.walkOr(i,o,r);else throw Error("non exhaustive match")})},t.prototype.walkTerminal=function(e,r,n){},t.prototype.walkProdRef=function(e,r,n){},t.prototype.walkFlat=function(e,r,n){var i=r.concat(n);this.walk(e,i)},t.prototype.walkOption=function(e,r,n){var i=r.concat(n);this.walk(e,i)},t.prototype.walkAtLeastOne=function(e,r,n){var i=[new ie.Option({definition:e.definition})].concat(r,n);this.walk(e,i)},t.prototype.walkAtLeastOneSep=function(e,r,n){var i=ri(e,r,n);this.walk(e,i)},t.prototype.walkMany=function(e,r,n){var i=[new ie.Option({definition:e.definition})].concat(r,n);this.walk(e,i)},t.prototype.walkManySep=function(e,r,n){var i=ri(e,r,n);this.walk(e,i)},t.prototype.walkOr=function(e,r,n){var i=this,a=r.concat(n);Sr.forEach(e.definition,function(o){var s=new ie.Alternative({definition:[o]});i.walk(s,a)})},t}();Ut.RestWalker=Io;function ri(t,e,r){var n=[new ie.Option({definition:[new ie.Terminal({terminalType:t.separator})].concat(t.definition)})],i=n.concat(e,r);return i}});var $e=R(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.GAstVisitor=void 0;var Oe=ne(),ko=function(){function t(){}return t.prototype.visit=function(e){var r=e;switch(r.constructor){case Oe.NonTerminal:return this.visitNonTerminal(r);case Oe.Alternative:return this.visitAlternative(r);case Oe.Option:return this.visitOption(r);case Oe.RepetitionMandatory:return this.visitRepetitionMandatory(r);case Oe.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(r);case Oe.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(r);case Oe.Repetition:return this.visitRepetition(r);case Oe.Alternation:return this.visitAlternation(r);case Oe.Terminal:return this.visitTerminal(r);case Oe.Rule:return this.visitRule(r);default:throw Error("non exhaustive match")}},t.prototype.visitNonTerminal=function(e){},t.prototype.visitAlternative=function(e){},t.prototype.visitOption=function(e){},t.prototype.visitRepetition=function(e){},t.prototype.visitRepetitionMandatory=function(e){},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){},t.prototype.visitRepetitionWithSeparator=function(e){},t.prototype.visitAlternation=function(e){},t.prototype.visitTerminal=function(e){},t.prototype.visitRule=function(e){},t}();Wt.GAstVisitor=ko});var vt=R(X=>{"use strict";var Po=X&&X.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(X,"__esModule",{value:!0});X.collectMethods=X.DslMethodsCollectorVisitor=X.getProductionDslName=X.isBranchingProd=X.isOptionalProd=X.isSequenceProd=void 0;var dt=k(),W=ne(),So=$e();function xo(t){return t instanceof W.Alternative||t instanceof W.Option||t instanceof W.Repetition||t instanceof W.RepetitionMandatory||t instanceof W.RepetitionMandatoryWithSeparator||t instanceof W.RepetitionWithSeparator||t instanceof W.Terminal||t instanceof W.Rule}X.isSequenceProd=xo;function xr(t,e){e===void 0&&(e=[]);var r=t instanceof W.Option||t instanceof W.Repetition||t instanceof W.RepetitionWithSeparator;return r?!0:t instanceof W.Alternation?dt.some(t.definition,function(n){return xr(n,e)}):t instanceof W.NonTerminal&&dt.contains(e,t)?!1:t instanceof W.AbstractProduction?(t instanceof W.NonTerminal&&e.push(t),dt.every(t.definition,function(n){return xr(n,e)})):!1}X.isOptionalProd=xr;function Co(t){return t instanceof W.Alternation}X.isBranchingProd=Co;function Lo(t){if(t instanceof W.NonTerminal)return"SUBRULE";if(t instanceof W.Option)return"OPTION";if(t instanceof W.Alternation)return"OR";if(t instanceof W.RepetitionMandatory)return"AT_LEAST_ONE";if(t instanceof W.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(t instanceof W.RepetitionWithSeparator)return"MANY_SEP";if(t instanceof W.Repetition)return"MANY";if(t instanceof W.Terminal)return"CONSUME";throw Error("non exhaustive match")}X.getProductionDslName=Lo;var ni=function(t){Po(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.separator="-",r.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},r}return e.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},e.prototype.visitTerminal=function(r){var n=r.terminalType.name+this.separator+"Terminal";dt.has(this.dslMethods,n)||(this.dslMethods[n]=[]),this.dslMethods[n].push(r)},e.prototype.visitNonTerminal=function(r){var n=r.nonTerminalName+this.separator+"Terminal";dt.has(this.dslMethods,n)||(this.dslMethods[n]=[]),this.dslMethods[n].push(r)},e.prototype.visitOption=function(r){this.dslMethods.option.push(r)},e.prototype.visitRepetitionWithSeparator=function(r){this.dslMethods.repetitionWithSeparator.push(r)},e.prototype.visitRepetitionMandatory=function(r){this.dslMethods.repetitionMandatory.push(r)},e.prototype.visitRepetitionMandatoryWithSeparator=function(r){this.dslMethods.repetitionMandatoryWithSeparator.push(r)},e.prototype.visitRepetition=function(r){this.dslMethods.repetition.push(r)},e.prototype.visitAlternation=function(r){this.dslMethods.alternation.push(r)},e}(So.GAstVisitor);X.DslMethodsCollectorVisitor=ni;var Bt=new ni;function Mo(t){Bt.reset(),t.accept(Bt);var e=Bt.dslMethods;return Bt.reset(),e}X.collectMethods=Mo});var Lr=R(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.firstForTerminal=Ne.firstForBranching=Ne.firstForSequence=Ne.first=void 0;var qt=k(),ii=ne(),Cr=vt();function jt(t){if(t instanceof ii.NonTerminal)return jt(t.referencedRule);if(t instanceof ii.Terminal)return si(t);if(Cr.isSequenceProd(t))return ai(t);if(Cr.isBranchingProd(t))return oi(t);throw Error("non exhaustive match")}Ne.first=jt;function ai(t){for(var e=[],r=t.definition,n=0,i=r.length>n,a,o=!0;i&&o;)a=r[n],o=Cr.isOptionalProd(a),e=e.concat(jt(a)),n=n+1,i=r.length>n;return qt.uniq(e)}Ne.firstForSequence=ai;function oi(t){var e=qt.map(t.definition,function(r){return jt(r)});return qt.uniq(qt.flatten(e))}Ne.firstForBranching=oi;function si(t){return[t.terminalType]}Ne.firstForTerminal=si});var Mr=R(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.IN=void 0;Vt.IN="_~IN~_"});var pi=R(he=>{"use strict";var bo=he&&he.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(he,"__esModule",{value:!0});he.buildInProdFollowPrefix=he.buildBetweenProdsFollowPrefix=he.computeAllProdsFollows=he.ResyncFollowsWalker=void 0;var Fo=Gt(),wo=Lr(),ui=k(),ci=Mr(),Do=ne(),fi=function(t){bo(e,t);function e(r){var n=t.call(this)||this;return n.topProd=r,n.follows={},n}return e.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},e.prototype.walkTerminal=function(r,n,i){},e.prototype.walkProdRef=function(r,n,i){var a=li(r.referencedRule,r.idx)+this.topProd.name,o=n.concat(i),s=new Do.Alternative({definition:o}),c=wo.first(s);this.follows[a]=c},e}(Fo.RestWalker);he.ResyncFollowsWalker=fi;function Uo(t){var e={};return ui.forEach(t,function(r){var n=new fi(r).startWalking();ui.assign(e,n)}),e}he.computeAllProdsFollows=Uo;function li(t,e){return t.name+e+ci.IN}he.buildBetweenProdsFollowPrefix=li;function Go(t){var e=t.terminalType.name;return e+t.idx+ci.IN}he.buildInProdFollowPrefix=Go});var mt=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.defaultGrammarValidatorErrorProvider=Me.defaultGrammarResolverErrorProvider=Me.defaultParserErrorProvider=void 0;var Ze=Ue(),Wo=k(),ye=k(),br=ne(),hi=vt();Me.defaultParserErrorProvider={buildMismatchTokenMessage:function(t){var e=t.expected,r=t.actual,n=t.previous,i=t.ruleName,a=Ze.hasTokenLabel(e),o=a?"--> "+Ze.tokenLabel(e)+" <--":"token of type --> "+e.name+" <--",s="Expecting "+o+" but found --> '"+r.image+"' <--";return s},buildNotAllInputParsedMessage:function(t){var e=t.firstRedundant,r=t.ruleName;return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage:function(t){var e=t.expectedPathsPerAlt,r=t.actual,n=t.previous,i=t.customUserDescription,a=t.ruleName,o="Expecting: ",s=ye.first(r).image,c=` +but found: '`+s+"'";if(i)return o+i+c;var f=ye.reduce(e,function(v,u){return v.concat(u)},[]),p=ye.map(f,function(v){return"["+ye.map(v,function(u){return Ze.tokenLabel(u)}).join(", ")+"]"}),l=ye.map(p,function(v,u){return" "+(u+1)+". "+v}),m=`one of these possible Token sequences: +`+l.join(` +`);return o+m+c},buildEarlyExitMessage:function(t){var e=t.expectedIterationPaths,r=t.actual,n=t.customUserDescription,i=t.ruleName,a="Expecting: ",o=ye.first(r).image,s=` +but found: '`+o+"'";if(n)return a+n+s;var c=ye.map(e,function(p){return"["+ye.map(p,function(l){return Ze.tokenLabel(l)}).join(",")+"]"}),f=`expecting at least one iteration which starts with one of these possible Token sequences:: + `+("<"+c.join(" ,")+">");return a+f+s}};Object.freeze(Me.defaultParserErrorProvider);Me.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(t,e){var r="Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+t.name+"<-";return r}};Me.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(t,e){function r(p){return p instanceof br.Terminal?p.terminalType.name:p instanceof br.NonTerminal?p.nonTerminalName:""}var n=t.name,i=ye.first(e),a=i.idx,o=hi.getProductionDslName(i),s=r(i),c=a>0,f="->"+o+(c?a:"")+"<- "+(s?"with argument: ->"+s+"<-":"")+` + appears more than once (`+e.length+" times) in the top level rule: ->"+n+`<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return f=f.replace(/[ \t]+/g," "),f=f.replace(/\s\s+/g,` +`),f},buildNamespaceConflictError:function(t){var e=`Namespace conflict found in grammar. +`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+t.name+`>. +`)+`To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`;return e},buildAlternationPrefixAmbiguityError:function(t){var e=ye.map(t.prefixPath,function(i){return Ze.tokenLabel(i)}).join(", "),r=t.alternation.idx===0?"":t.alternation.idx,n="Ambiguous alternatives: <"+t.ambiguityIndices.join(" ,")+`> due to common lookahead prefix +`+("in inside <"+t.topLevelRule.name+`> Rule, +`)+("<"+e+`> may appears as a prefix path in all these alternatives. +`)+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`;return n},buildAlternationAmbiguityError:function(t){var e=ye.map(t.prefixPath,function(i){return Ze.tokenLabel(i)}).join(", "),r=t.alternation.idx===0?"":t.alternation.idx,n="Ambiguous Alternatives Detected: <"+t.ambiguityIndices.join(" ,")+"> in "+(" inside <"+t.topLevelRule.name+`> Rule, +`)+("<"+e+`> may appears as a prefix path in all these alternatives. +`);return n=n+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,n},buildEmptyRepetitionError:function(t){var e=hi.getProductionDslName(t.repetition);t.repetition.idx!==0&&(e+=t.repetition.idx);var r="The repetition <"+e+"> within Rule <"+t.topLevelRule.name+`> can never consume any tokens. +This could lead to an infinite loop.`;return r},buildTokenNameError:function(t){return"deprecated"},buildEmptyAlternationError:function(t){var e="Ambiguous empty alternative: <"+(t.emptyChoiceIdx+1)+">"+(" in inside <"+t.topLevelRule.name+`> Rule. +`)+"Only the last alternative may be an empty alternative.";return e},buildTooManyAlternativesError:function(t){var e=`An Alternation cannot have more than 256 alternatives: +`+(" inside <"+t.topLevelRule.name+`> Rule. + has `+(t.alternation.definition.length+1)+" alternatives.");return e},buildLeftRecursionError:function(t){var e=t.topLevelRule.name,r=Wo.map(t.leftRecursionPath,function(a){return a.name}),n=e+" --> "+r.concat([e]).join(" --> "),i=`Left Recursion found in grammar. +`+("rule: <"+e+`> can be invoked from itself (directly or indirectly) +`)+(`without consuming any Tokens. The grammar path that causes this is: + `+n+` +`)+` To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;return i},buildInvalidRuleNameError:function(t){return"deprecated"},buildDuplicateRuleNameError:function(t){var e;t.topLevelRule instanceof br.Rule?e=t.topLevelRule.name:e=t.topLevelRule;var r="Duplicate definition, rule: ->"+e+"<- is already defined in the grammar: ->"+t.grammarName+"<-";return r}}});var mi=R(Ge=>{"use strict";var Bo=Ge&&Ge.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.GastRefResolverVisitor=Ge.resolveGrammar=void 0;var qo=ce(),di=k(),jo=$e();function Vo(t,e){var r=new vi(t,e);return r.resolveRefs(),r.errors}Ge.resolveGrammar=Vo;var vi=function(t){Bo(e,t);function e(r,n){var i=t.call(this)||this;return i.nameToTopRule=r,i.errMsgProvider=n,i.errors=[],i}return e.prototype.resolveRefs=function(){var r=this;di.forEach(di.values(this.nameToTopRule),function(n){r.currTopLevel=n,n.accept(r)})},e.prototype.visitNonTerminal=function(r){var n=this.nameToTopRule[r.nonTerminalName];if(n)r.referencedRule=n;else{var i=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,r);this.errors.push({message:i,type:qo.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:r.nonTerminalName})}},e}(jo.GAstVisitor);Ge.GastRefResolverVisitor=vi});var Tt=R(j=>{"use strict";var je=j&&j.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(j,"__esModule",{value:!0});j.nextPossibleTokensAfter=j.possiblePathsFrom=j.NextTerminalAfterAtLeastOneSepWalker=j.NextTerminalAfterAtLeastOneWalker=j.NextTerminalAfterManySepWalker=j.NextTerminalAfterManyWalker=j.AbstractNextTerminalAfterProductionWalker=j.NextAfterTokenWalker=j.AbstractNextPossibleTokensWalker=void 0;var Ei=Gt(),I=k(),Ko=Lr(),O=ne(),Ti=function(t){je(e,t);function e(r,n){var i=t.call(this)||this;return i.topProd=r,i.path=n,i.possibleTokTypes=[],i.nextProductionName="",i.nextProductionOccurrence=0,i.found=!1,i.isAtEndOfPath=!1,i}return e.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=I.cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=I.cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},e.prototype.walk=function(r,n){n===void 0&&(n=[]),this.found||t.prototype.walk.call(this,r,n)},e.prototype.walkProdRef=function(r,n,i){if(r.referencedRule.name===this.nextProductionName&&r.idx===this.nextProductionOccurrence){var a=n.concat(i);this.updateExpectedNext(),this.walk(r.referencedRule,a)}},e.prototype.updateExpectedNext=function(){I.isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},e}(Ei.RestWalker);j.AbstractNextPossibleTokensWalker=Ti;var zo=function(t){je(e,t);function e(r,n){var i=t.call(this,r,n)||this;return i.path=n,i.nextTerminalName="",i.nextTerminalOccurrence=0,i.nextTerminalName=i.path.lastTok.name,i.nextTerminalOccurrence=i.path.lastTokOccurrence,i}return e.prototype.walkTerminal=function(r,n,i){if(this.isAtEndOfPath&&r.terminalType.name===this.nextTerminalName&&r.idx===this.nextTerminalOccurrence&&!this.found){var a=n.concat(i),o=new O.Alternative({definition:a});this.possibleTokTypes=Ko.first(o),this.found=!0}},e}(Ti);j.NextAfterTokenWalker=zo;var Et=function(t){je(e,t);function e(r,n){var i=t.call(this)||this;return i.topRule=r,i.occurrence=n,i.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},i}return e.prototype.startWalking=function(){return this.walk(this.topRule),this.result},e}(Ei.RestWalker);j.AbstractNextTerminalAfterProductionWalker=Et;var Ho=function(t){je(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.walkMany=function(r,n,i){if(r.idx===this.occurrence){var a=I.first(n.concat(i));this.result.isEndOfRule=a===void 0,a instanceof O.Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else t.prototype.walkMany.call(this,r,n,i)},e}(Et);j.NextTerminalAfterManyWalker=Ho;var Yo=function(t){je(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.walkManySep=function(r,n,i){if(r.idx===this.occurrence){var a=I.first(n.concat(i));this.result.isEndOfRule=a===void 0,a instanceof O.Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else t.prototype.walkManySep.call(this,r,n,i)},e}(Et);j.NextTerminalAfterManySepWalker=Yo;var Xo=function(t){je(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.walkAtLeastOne=function(r,n,i){if(r.idx===this.occurrence){var a=I.first(n.concat(i));this.result.isEndOfRule=a===void 0,a instanceof O.Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else t.prototype.walkAtLeastOne.call(this,r,n,i)},e}(Et);j.NextTerminalAfterAtLeastOneWalker=Xo;var $o=function(t){je(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.walkAtLeastOneSep=function(r,n,i){if(r.idx===this.occurrence){var a=I.first(n.concat(i));this.result.isEndOfRule=a===void 0,a instanceof O.Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else t.prototype.walkAtLeastOneSep.call(this,r,n,i)},e}(Et);j.NextTerminalAfterAtLeastOneSepWalker=$o;function yi(t,e,r){r===void 0&&(r=[]),r=I.cloneArr(r);var n=[],i=0;function a(f){return f.concat(I.drop(t,i+1))}function o(f){var p=yi(a(f),e,r);return n.concat(p)}for(;r.length=0;it--){var at=_.definition[it],Ke={idx:u,def:at.definition.concat(I.drop(v)),ruleStack:d,occurrenceStack:A};l.push(Ke),l.push(o)}else if(_ instanceof O.Alternative)l.push({idx:u,def:_.definition.concat(I.drop(v)),ruleStack:d,occurrenceStack:A});else if(_ instanceof O.Rule)l.push(Zo(_,u,d,A));else throw Error("non exhaustive match")}}return p}j.nextPossibleTokensAfter=Qo;function Zo(t,e,r,n){var i=I.cloneArr(r);i.push(t.name);var a=I.cloneArr(n);return a.push(1),{idx:e,def:t.definition,ruleStack:i,occurrenceStack:a}}});var yt=R(C=>{"use strict";var _i=C&&C.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(C,"__esModule",{value:!0});C.areTokenCategoriesNotUsed=C.isStrictPrefixOfPath=C.containsPath=C.getLookaheadPathsForOptionalProd=C.getLookaheadPathsForOr=C.lookAheadSequenceFromAlternatives=C.buildSingleAlternativeLookaheadFunction=C.buildAlternativesLookAheadFunc=C.buildLookaheadFuncForOptionalProd=C.buildLookaheadFuncForOr=C.getProdType=C.PROD_TYPE=void 0;var D=k(),gi=Tt(),Jo=Gt(),Kt=Xe(),We=ne(),es=$e(),z;(function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"})(z=C.PROD_TYPE||(C.PROD_TYPE={}));function ts(t){if(t instanceof We.Option)return z.OPTION;if(t instanceof We.Repetition)return z.REPETITION;if(t instanceof We.RepetitionMandatory)return z.REPETITION_MANDATORY;if(t instanceof We.RepetitionMandatoryWithSeparator)return z.REPETITION_MANDATORY_WITH_SEPARATOR;if(t instanceof We.RepetitionWithSeparator)return z.REPETITION_WITH_SEPARATOR;if(t instanceof We.Alternation)return z.ALTERNATION;throw Error("non exhaustive match")}C.getProdType=ts;function rs(t,e,r,n,i,a){var o=Ai(t,e,r),s=Fr(o)?Kt.tokenStructuredMatcherNoCategories:Kt.tokenStructuredMatcher;return a(o,n,s,i)}C.buildLookaheadFuncForOr=rs;function ns(t,e,r,n,i,a){var o=Ri(t,e,i,r),s=Fr(o)?Kt.tokenStructuredMatcherNoCategories:Kt.tokenStructuredMatcher;return a(o[0],s,n)}C.buildLookaheadFuncForOptionalProd=ns;function is(t,e,r,n){var i=t.length,a=D.every(t,function(c){return D.every(c,function(f){return f.length===1})});if(e)return function(c){for(var f=D.map(c,function(y){return y.GATE}),p=0;p{"use strict";var Ur=x&&x.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(x,"__esModule",{value:!0});x.checkPrefixAlternativesAmbiguities=x.validateSomeNonEmptyLookaheadPath=x.validateTooManyAlts=x.RepetionCollector=x.validateAmbiguousAlternationAlternatives=x.validateEmptyOrAlternative=x.getFirstNoneTerminal=x.validateNoLeftRecursion=x.validateRuleIsOverridden=x.validateRuleDoesNotAlreadyExist=x.OccurrenceValidationCollector=x.identifyProductionForDuplicates=x.validateGrammar=void 0;var M=k(),B=k(),Ie=ce(),Gr=vt(),Qe=yt(),cs=Tt(),_e=ne(),Wr=$e();function ps(t,e,r,n,i){var a=M.map(t,function(v){return ls(v,n)}),o=M.map(t,function(v){return Br(v,v,n)}),s=[],c=[],f=[];B.every(o,B.isEmpty)&&(s=B.map(t,function(v){return Pi(v,n)}),c=B.map(t,function(v){return Si(v,e,n)}),f=Ci(t,e,n));var p=fs(t,r,n),l=B.map(t,function(v){return xi(v,n)}),m=B.map(t,function(v){return ki(v,t,i,n)});return M.flatten(a.concat(f,o,s,c,p,l,m))}x.validateGrammar=ps;function ls(t,e){var r=new bi;t.accept(r);var n=r.allProductions,i=M.groupBy(n,Li),a=M.pick(i,function(s){return s.length>1}),o=M.map(M.values(a),function(s){var c=M.first(s),f=e.buildDuplicateFoundError(t,s),p=Gr.getProductionDslName(c),l={message:f,type:Ie.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:p,occurrence:c.idx},m=Mi(c);return m&&(l.parameter=m),l});return o}function Li(t){return Gr.getProductionDslName(t)+"_#_"+t.idx+"_#_"+Mi(t)}x.identifyProductionForDuplicates=Li;function Mi(t){return t instanceof _e.Terminal?t.terminalType.name:t instanceof _e.NonTerminal?t.nonTerminalName:""}var bi=function(t){Ur(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.allProductions=[],r}return e.prototype.visitNonTerminal=function(r){this.allProductions.push(r)},e.prototype.visitOption=function(r){this.allProductions.push(r)},e.prototype.visitRepetitionWithSeparator=function(r){this.allProductions.push(r)},e.prototype.visitRepetitionMandatory=function(r){this.allProductions.push(r)},e.prototype.visitRepetitionMandatoryWithSeparator=function(r){this.allProductions.push(r)},e.prototype.visitRepetition=function(r){this.allProductions.push(r)},e.prototype.visitAlternation=function(r){this.allProductions.push(r)},e.prototype.visitTerminal=function(r){this.allProductions.push(r)},e}(Wr.GAstVisitor);x.OccurrenceValidationCollector=bi;function ki(t,e,r,n){var i=[],a=B.reduce(e,function(s,c){return c.name===t.name?s+1:s},0);if(a>1){var o=n.buildDuplicateRuleNameError({topLevelRule:t,grammarName:r});i.push({message:o,type:Ie.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:t.name})}return i}x.validateRuleDoesNotAlreadyExist=ki;function hs(t,e,r){var n=[],i;return M.contains(e,t)||(i="Invalid rule override, rule: ->"+t+"<- cannot be overridden in the grammar: ->"+r+"<-as it is not defined in any of the super grammars ",n.push({message:i,type:Ie.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:t})),n}x.validateRuleIsOverridden=hs;function Br(t,e,r,n){n===void 0&&(n=[]);var i=[],a=_t(e.definition);if(M.isEmpty(a))return[];var o=t.name,s=M.contains(a,t);s&&i.push({message:r.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:n}),type:Ie.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:o});var c=M.difference(a,n.concat([t])),f=M.map(c,function(p){var l=M.cloneArr(n);return l.push(p),Br(t,p,r,l)});return i.concat(M.flatten(f))}x.validateNoLeftRecursion=Br;function _t(t){var e=[];if(M.isEmpty(t))return e;var r=M.first(t);if(r instanceof _e.NonTerminal)e.push(r.referencedRule);else if(r instanceof _e.Alternative||r instanceof _e.Option||r instanceof _e.RepetitionMandatory||r instanceof _e.RepetitionMandatoryWithSeparator||r instanceof _e.RepetitionWithSeparator||r instanceof _e.Repetition)e=e.concat(_t(r.definition));else if(r instanceof _e.Alternation)e=M.flatten(M.map(r.definition,function(o){return _t(o.definition)}));else if(!(r instanceof _e.Terminal))throw Error("non exhaustive match");var n=Gr.isOptionalProd(r),i=t.length>1;if(n&&i){var a=M.drop(t);return e.concat(_t(a))}else return e}x.getFirstNoneTerminal=_t;var qr=function(t){Ur(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.alternations=[],r}return e.prototype.visitAlternation=function(r){this.alternations.push(r)},e}(Wr.GAstVisitor);function Pi(t,e){var r=new qr;t.accept(r);var n=r.alternations,i=M.reduce(n,function(a,o){var s=M.dropRight(o.definition),c=M.map(s,function(f,p){var l=cs.nextPossibleTokensAfter([f],[],null,1);return M.isEmpty(l)?{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:o,emptyChoiceIdx:p}),type:Ie.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:o.idx,alternative:p+1}:null});return a.concat(M.compact(c))},[]);return i}x.validateEmptyOrAlternative=Pi;function Si(t,e,r){var n=new qr;t.accept(n);var i=n.alternations;i=B.reject(i,function(o){return o.ignoreAmbiguities===!0});var a=M.reduce(i,function(o,s){var c=s.idx,f=s.maxLookahead||e,p=Qe.getLookaheadPathsForOr(c,t,f,s),l=ds(p,s,t,r),m=Fi(p,s,t,r);return o.concat(l,m)},[]);return a}x.validateAmbiguousAlternationAlternatives=Si;var wi=function(t){Ur(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.allProductions=[],r}return e.prototype.visitRepetitionWithSeparator=function(r){this.allProductions.push(r)},e.prototype.visitRepetitionMandatory=function(r){this.allProductions.push(r)},e.prototype.visitRepetitionMandatoryWithSeparator=function(r){this.allProductions.push(r)},e.prototype.visitRepetition=function(r){this.allProductions.push(r)},e}(Wr.GAstVisitor);x.RepetionCollector=wi;function xi(t,e){var r=new qr;t.accept(r);var n=r.alternations,i=M.reduce(n,function(a,o){return o.definition.length>255&&a.push({message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:o}),type:Ie.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:t.name,occurrence:o.idx}),a},[]);return i}x.validateTooManyAlts=xi;function Ci(t,e,r){var n=[];return B.forEach(t,function(i){var a=new wi;i.accept(a);var o=a.allProductions;B.forEach(o,function(s){var c=Qe.getProdType(s),f=s.maxLookahead||e,p=s.idx,l=Qe.getLookaheadPathsForOptionalProd(p,i,c,f),m=l[0];if(B.isEmpty(B.flatten(m))){var v=r.buildEmptyRepetitionError({topLevelRule:i,repetition:s});n.push({message:v,type:Ie.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),n}x.validateSomeNonEmptyLookaheadPath=Ci;function ds(t,e,r,n){var i=[],a=B.reduce(t,function(s,c,f){return e.definition[f].ignoreAmbiguities===!0||B.forEach(c,function(p){var l=[f];B.forEach(t,function(m,v){f!==v&&Qe.containsPath(m,p)&&e.definition[v].ignoreAmbiguities!==!0&&l.push(v)}),l.length>1&&!Qe.containsPath(i,p)&&(i.push(p),s.push({alts:l,path:p}))}),s},[]),o=M.map(a,function(s){var c=B.map(s.alts,function(p){return p+1}),f=n.buildAlternationAmbiguityError({topLevelRule:r,alternation:e,ambiguityIndices:c,prefixPath:s.path});return{message:f,type:Ie.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:r.name,occurrence:e.idx,alternatives:[s.alts]}});return o}function Fi(t,e,r,n){var i=[],a=B.reduce(t,function(o,s,c){var f=B.map(s,function(p){return{idx:c,path:p}});return o.concat(f)},[]);return B.forEach(a,function(o){var s=e.definition[o.idx];if(s.ignoreAmbiguities!==!0){var c=o.idx,f=o.path,p=B.findAll(a,function(m){return e.definition[m.idx].ignoreAmbiguities!==!0&&m.idx{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateGrammar=Je.resolveGrammar=void 0;var Vr=k(),vs=mi(),ms=jr(),Di=mt();function Es(t){t=Vr.defaults(t,{errMsgProvider:Di.defaultGrammarResolverErrorProvider});var e={};return Vr.forEach(t.rules,function(r){e[r.name]=r}),vs.resolveGrammar(e,t.errMsgProvider)}Je.resolveGrammar=Es;function Ts(t){return t=Vr.defaults(t,{errMsgProvider:Di.defaultGrammarValidatorErrorProvider}),ms.validateGrammar(t.rules,t.maxLookahead,t.tokenTypes,t.errMsgProvider,t.grammarName)}Je.validateGrammar=Ts});var et=R(ae=>{"use strict";var gt=ae&&ae.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(ae,"__esModule",{value:!0});ae.EarlyExitException=ae.NotAllInputParsedException=ae.NoViableAltException=ae.MismatchedTokenException=ae.isRecognitionException=void 0;var ys=k(),Gi="MismatchedTokenException",Wi="NoViableAltException",Bi="EarlyExitException",qi="NotAllInputParsedException",ji=[Gi,Wi,Bi,qi];Object.freeze(ji);function _s(t){return ys.contains(ji,t.name)}ae.isRecognitionException=_s;var zt=function(t){gt(e,t);function e(r,n){var i=this.constructor,a=t.call(this,r)||this;return a.token=n,a.resyncedTokens=[],Object.setPrototypeOf(a,i.prototype),Error.captureStackTrace&&Error.captureStackTrace(a,a.constructor),a}return e}(Error),gs=function(t){gt(e,t);function e(r,n,i){var a=t.call(this,r,n)||this;return a.previousToken=i,a.name=Gi,a}return e}(zt);ae.MismatchedTokenException=gs;var As=function(t){gt(e,t);function e(r,n,i){var a=t.call(this,r,n)||this;return a.previousToken=i,a.name=Wi,a}return e}(zt);ae.NoViableAltException=As;var Rs=function(t){gt(e,t);function e(r,n){var i=t.call(this,r,n)||this;return i.name=qi,i}return e}(zt);ae.NotAllInputParsedException=Rs;var Os=function(t){gt(e,t);function e(r,n,i){var a=t.call(this,r,n)||this;return a.previousToken=i,a.name=Bi,a}return e}(zt);ae.EarlyExitException=Os});var zr=R($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.attemptInRepetitionRecovery=$.Recoverable=$.InRuleRecoveryException=$.IN_RULE_RECOVERY_EXCEPTION=$.EOF_FOLLOW_KEY=void 0;var Ht=Ue(),de=k(),Ns=et(),Is=Mr(),ks=ce();$.EOF_FOLLOW_KEY={};$.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function Kr(t){this.name=$.IN_RULE_RECOVERY_EXCEPTION,this.message=t}$.InRuleRecoveryException=Kr;Kr.prototype=Error.prototype;var Ps=function(){function t(){}return t.prototype.initRecoverable=function(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=de.has(e,"recoveryEnabled")?e.recoveryEnabled:ks.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=Vi)},t.prototype.getTokenToInsert=function(e){var r=Ht.createTokenInstance(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return r.isInsertedInRecovery=!0,r},t.prototype.canTokenTypeBeInsertedInRecovery=function(e){return!0},t.prototype.tryInRepetitionRecovery=function(e,r,n,i){for(var a=this,o=this.findReSyncTokenType(),s=this.exportLexerState(),c=[],f=!1,p=this.LA(1),l=this.LA(1),m=function(){var v=a.LA(0),u=a.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:p,previous:v,ruleName:a.getCurrRuleFullName()}),d=new Ns.MismatchedTokenException(u,p,a.LA(0));d.resyncedTokens=de.dropRight(c),a.SAVE_ERROR(d)};!f;)if(this.tokenMatcher(l,i)){m();return}else if(n.call(this)){m(),e.apply(this,r);return}else this.tokenMatcher(l,o)?f=!0:(l=this.SKIP_TOKEN(),this.addToResyncTokens(l,c));this.importLexerState(s)},t.prototype.shouldInRepetitionRecoveryBeTried=function(e,r,n){return!(n===!1||e===void 0||r===void 0||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,r)))},t.prototype.getFollowsForInRuleRecovery=function(e,r){var n=this.getCurrentGrammarPath(e,r),i=this.getNextPossibleTokenTypes(n);return i},t.prototype.tryInRuleRecovery=function(e,r){if(this.canRecoverWithSingleTokenInsertion(e,r)){var n=this.getTokenToInsert(e);return n}if(this.canRecoverWithSingleTokenDeletion(e)){var i=this.SKIP_TOKEN();return this.consumeToken(),i}throw new Kr("sad sad panda")},t.prototype.canPerformInRuleRecovery=function(e,r){return this.canRecoverWithSingleTokenInsertion(e,r)||this.canRecoverWithSingleTokenDeletion(e)},t.prototype.canRecoverWithSingleTokenInsertion=function(e,r){var n=this;if(!this.canTokenTypeBeInsertedInRecovery(e)||de.isEmpty(r))return!1;var i=this.LA(1),a=de.find(r,function(o){return n.tokenMatcher(i,o)})!==void 0;return a},t.prototype.canRecoverWithSingleTokenDeletion=function(e){var r=this.tokenMatcher(this.LA(2),e);return r},t.prototype.isInCurrentRuleReSyncSet=function(e){var r=this.getCurrFollowKey(),n=this.getFollowSetFromFollowKey(r);return de.contains(n,e)},t.prototype.findReSyncTokenType=function(){for(var e=this.flattenFollowSet(),r=this.LA(1),n=2;;){var i=r.tokenType;if(de.contains(e,i))return i;r=this.LA(n),n++}},t.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return $.EOF_FOLLOW_KEY;var e=this.getLastExplicitRuleShortName(),r=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:r,inRule:this.shortRuleNameToFullName(n)}},t.prototype.buildFullFollowKeyStack=function(){var e=this,r=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return de.map(r,function(i,a){return a===0?$.EOF_FOLLOW_KEY:{ruleName:e.shortRuleNameToFullName(i),idxInCallingRule:n[a],inRule:e.shortRuleNameToFullName(r[a-1])}})},t.prototype.flattenFollowSet=function(){var e=this,r=de.map(this.buildFullFollowKeyStack(),function(n){return e.getFollowSetFromFollowKey(n)});return de.flatten(r)},t.prototype.getFollowSetFromFollowKey=function(e){if(e===$.EOF_FOLLOW_KEY)return[Ht.EOF];var r=e.ruleName+e.idxInCallingRule+Is.IN+e.inRule;return this.resyncFollows[r]},t.prototype.addToResyncTokens=function(e,r){return this.tokenMatcher(e,Ht.EOF)||r.push(e),r},t.prototype.reSyncTo=function(e){for(var r=[],n=this.LA(1);this.tokenMatcher(n,e)===!1;)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,r);return de.dropRight(r)},t.prototype.attemptInRepetitionRecovery=function(e,r,n,i,a,o,s){},t.prototype.getCurrentGrammarPath=function(e,r){var n=this.getHumanReadableRuleStack(),i=de.cloneArr(this.RULE_OCCURRENCE_STACK),a={ruleStack:n,occurrenceStack:i,lastTok:e,lastTokOccurrence:r};return a},t.prototype.getHumanReadableRuleStack=function(){var e=this;return de.map(this.RULE_STACK,function(r){return e.shortRuleNameToFullName(r)})},t}();$.Recoverable=Ps;function Vi(t,e,r,n,i,a,o){var s=this.getKeyForAutomaticLookahead(n,i),c=this.firstAfterRepMap[s];if(c===void 0){var f=this.getCurrRuleFullName(),p=this.getGAstProductions()[f],l=new a(p,i);c=l.startWalking(),this.firstAfterRepMap[s]=c}var m=c.token,v=c.occurrence,u=c.isEndOfRule;this.RULE_STACK.length===1&&u&&m===void 0&&(m=Ht.EOF,v=1),this.shouldInRepetitionRecoveryBeTried(m,v,o)&&this.tryInRepetitionRecovery(t,e,r,m)}$.attemptInRepetitionRecovery=Vi});var Yt=R(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.getKeyForAutomaticLookahead=P.AT_LEAST_ONE_SEP_IDX=P.MANY_SEP_IDX=P.AT_LEAST_ONE_IDX=P.MANY_IDX=P.OPTION_IDX=P.OR_IDX=P.BITS_FOR_ALT_IDX=P.BITS_FOR_RULE_IDX=P.BITS_FOR_OCCURRENCE_IDX=P.BITS_FOR_METHOD_TYPE=void 0;P.BITS_FOR_METHOD_TYPE=4;P.BITS_FOR_OCCURRENCE_IDX=8;P.BITS_FOR_RULE_IDX=12;P.BITS_FOR_ALT_IDX=8;P.OR_IDX=1<{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.LooksAhead=void 0;var be=yt(),ge=k(),Ki=ce(),Fe=Yt(),Ve=vt(),xs=function(){function t(){}return t.prototype.initLooksAhead=function(e){this.dynamicTokensEnabled=ge.has(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:Ki.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=ge.has(e,"maxLookahead")?e.maxLookahead:Ki.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=ge.isES2015MapSupported()?new Map:[],ge.isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},t.prototype.preComputeLookaheadFunctions=function(e){var r=this;ge.forEach(e,function(n){r.TRACE_INIT(n.name+" Rule Lookahead",function(){var i=Ve.collectMethods(n),a=i.alternation,o=i.repetition,s=i.option,c=i.repetitionMandatory,f=i.repetitionMandatoryWithSeparator,p=i.repetitionWithSeparator;ge.forEach(a,function(l){var m=l.idx===0?"":l.idx;r.TRACE_INIT(""+Ve.getProductionDslName(l)+m,function(){var v=be.buildLookaheadFuncForOr(l.idx,n,l.maxLookahead||r.maxLookahead,l.hasPredicates,r.dynamicTokensEnabled,r.lookAheadBuilderForAlternatives),u=Fe.getKeyForAutomaticLookahead(r.fullRuleNameToShort[n.name],Fe.OR_IDX,l.idx);r.setLaFuncCache(u,v)})}),ge.forEach(o,function(l){r.computeLookaheadFunc(n,l.idx,Fe.MANY_IDX,be.PROD_TYPE.REPETITION,l.maxLookahead,Ve.getProductionDslName(l))}),ge.forEach(s,function(l){r.computeLookaheadFunc(n,l.idx,Fe.OPTION_IDX,be.PROD_TYPE.OPTION,l.maxLookahead,Ve.getProductionDslName(l))}),ge.forEach(c,function(l){r.computeLookaheadFunc(n,l.idx,Fe.AT_LEAST_ONE_IDX,be.PROD_TYPE.REPETITION_MANDATORY,l.maxLookahead,Ve.getProductionDslName(l))}),ge.forEach(f,function(l){r.computeLookaheadFunc(n,l.idx,Fe.AT_LEAST_ONE_SEP_IDX,be.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,l.maxLookahead,Ve.getProductionDslName(l))}),ge.forEach(p,function(l){r.computeLookaheadFunc(n,l.idx,Fe.MANY_SEP_IDX,be.PROD_TYPE.REPETITION_WITH_SEPARATOR,l.maxLookahead,Ve.getProductionDslName(l))})})})},t.prototype.computeLookaheadFunc=function(e,r,n,i,a,o){var s=this;this.TRACE_INIT(""+o+(r===0?"":r),function(){var c=be.buildLookaheadFuncForOptionalProd(r,e,a||s.maxLookahead,s.dynamicTokensEnabled,i,s.lookAheadBuilderForOptional),f=Fe.getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name],n,r);s.setLaFuncCache(f,c)})},t.prototype.lookAheadBuilderForOptional=function(e,r,n){return be.buildSingleAlternativeLookaheadFunction(e,r,n)},t.prototype.lookAheadBuilderForAlternatives=function(e,r,n,i){return be.buildAlternativesLookAheadFunc(e,r,n,i)},t.prototype.getKeyForAutomaticLookahead=function(e,r){var n=this.getLastExplicitRuleShortName();return Fe.getKeyForAutomaticLookahead(n,e,r)},t.prototype.getLaFuncFromCache=function(e){},t.prototype.getLaFuncFromMap=function(e){return this.lookAheadFuncsCache.get(e)},t.prototype.getLaFuncFromObj=function(e){return this.lookAheadFuncsCache[e]},t.prototype.setLaFuncCache=function(e,r){},t.prototype.setLaFuncCacheUsingMap=function(e,r){this.lookAheadFuncsCache.set(e,r)},t.prototype.setLaFuncUsingObj=function(e,r){this.lookAheadFuncsCache[e]=r},t}();Xt.LooksAhead=xs});var Hi=R(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.addNoneTerminalToCst=ke.addTerminalToCst=ke.setNodeLocationFull=ke.setNodeLocationOnlyOffset=void 0;function Cs(t,e){isNaN(t.startOffset)===!0?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffset{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.defineNameProp=Be.functionName=Be.classNameFromInstance=void 0;var Fs=k();function ws(t){return Yi(t.constructor)}Be.classNameFromInstance=ws;var Xi="name";function Yi(t){var e=t.name;return e||"anonymous"}Be.functionName=Yi;function Ds(t,e){var r=Object.getOwnPropertyDescriptor(t,Xi);return Fs.isUndefined(r)||r.configurable?(Object.defineProperty(t,Xi,{enumerable:!1,configurable:!0,writable:!1,value:e}),!0):!1}Be.defineNameProp=Ds});var ea=R(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.validateRedundantMethods=Y.validateMissingCstMethods=Y.validateVisitor=Y.CstVisitorDefinitionError=Y.createBaseVisitorConstructorWithDefaults=Y.createBaseSemanticVisitorConstructor=Y.defaultVisit=void 0;var ve=k(),At=Hr();function $i(t,e){for(var r=ve.keys(t),n=r.length,i=0;i: + `+(""+a.join(` + +`).replace(/\n/g,` + `)))}}};return r.prototype=n,r.prototype.constructor=r,r._RULE_NAMES=e,r}Y.createBaseSemanticVisitorConstructor=Us;function Gs(t,e,r){var n=function(){};At.defineNameProp(n,t+"BaseSemanticsWithDefaults");var i=Object.create(r.prototype);return ve.forEach(e,function(a){i[a]=$i}),n.prototype=i,n.prototype.constructor=n,n}Y.createBaseVisitorConstructorWithDefaults=Gs;var Yr;(function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"})(Yr=Y.CstVisitorDefinitionError||(Y.CstVisitorDefinitionError={}));function Zi(t,e){var r=Qi(t,e),n=Ji(t,e);return r.concat(n)}Y.validateVisitor=Zi;function Qi(t,e){var r=ve.map(e,function(n){if(!ve.isFunction(t[n]))return{msg:"Missing visitor method: <"+n+"> on "+At.functionName(t.constructor)+" CST Visitor.",type:Yr.MISSING_METHOD,methodName:n}});return ve.compact(r)}Y.validateMissingCstMethods=Qi;var Ws=["constructor","visit","validateVisitor"];function Ji(t,e){var r=[];for(var n in t)ve.isFunction(t[n])&&!ve.contains(Ws,n)&&!ve.contains(e,n)&&r.push({msg:"Redundant visitor method: <"+n+"> on "+At.functionName(t.constructor)+` CST Visitor +There is no Grammar Rule corresponding to this method's name. +`,type:Yr.REDUNDANT_METHOD,methodName:n});return r}Y.validateRedundantMethods=Ji});var ra=R($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.TreeBuilder=void 0;var tt=Hi(),K=k(),ta=ea(),Bs=ce(),qs=function(){function t(){}return t.prototype.initTreeBuilder=function(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=K.has(e,"nodeLocationTracking")?e.nodeLocationTracking:Bs.DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=K.NOOP,this.cstFinallyStateUpdate=K.NOOP,this.cstPostTerminal=K.NOOP,this.cstPostNonTerminal=K.NOOP,this.cstPostRule=K.NOOP;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=tt.setNodeLocationFull,this.setNodeLocationFromNode=tt.setNodeLocationFull,this.cstPostRule=K.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=K.NOOP,this.setNodeLocationFromNode=K.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=tt.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=tt.setNodeLocationOnlyOffset,this.cstPostRule=K.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=K.NOOP,this.setNodeLocationFromNode=K.NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=K.NOOP,this.setNodeLocationFromNode=K.NOOP,this.cstPostRule=K.NOOP,this.setInitialNodeLocation=K.NOOP;else throw Error('Invalid config option: "'+e.nodeLocationTracking+'"')},t.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(e){e.location={startOffset:NaN,endOffset:NaN}},t.prototype.setInitialNodeLocationOnlyOffsetRegular=function(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},t.prototype.setInitialNodeLocationFullRecovery=function(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},t.prototype.setInitialNodeLocationFullRegular=function(e){var r=this.LA(1);e.location={startOffset:r.startOffset,startLine:r.startLine,startColumn:r.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},t.prototype.cstInvocationStateUpdate=function(e,r){var n={name:e,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},t.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},t.prototype.cstPostRuleFull=function(e){var r=this.LA(0),n=e.location;n.startOffset<=r.startOffset?(n.endOffset=r.endOffset,n.endLine=r.endLine,n.endColumn=r.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)},t.prototype.cstPostRuleOnlyOffset=function(e){var r=this.LA(0),n=e.location;n.startOffset<=r.startOffset?n.endOffset=r.endOffset:n.startOffset=NaN},t.prototype.cstPostTerminal=function(e,r){var n=this.CST_STACK[this.CST_STACK.length-1];tt.addTerminalToCst(n,r,e),this.setNodeLocationFromToken(n.location,r)},t.prototype.cstPostNonTerminal=function(e,r){var n=this.CST_STACK[this.CST_STACK.length-1];tt.addNoneTerminalToCst(n,r,e),this.setNodeLocationFromNode(n.location,e.location)},t.prototype.getBaseCstVisitorConstructor=function(){if(K.isUndefined(this.baseCstVisitorConstructor)){var e=ta.createBaseSemanticVisitorConstructor(this.className,K.keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor},t.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(K.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var e=ta.createBaseVisitorConstructorWithDefaults(this.className,K.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor},t.prototype.getLastExplicitRuleShortName=function(){var e=this.RULE_STACK;return e[e.length-1]},t.prototype.getPreviousExplicitRuleShortName=function(){var e=this.RULE_STACK;return e[e.length-2]},t.prototype.getLastExplicitRuleOccurrenceIndex=function(){var e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]},t}();$t.TreeBuilder=qs});var ia=R(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.LexerAdapter=void 0;var na=ce(),js=function(){function t(){}return t.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(t.prototype,"input",{get:function(){return this.tokVector},set:function(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length},enumerable:!1,configurable:!0}),t.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):na.END_OF_FILE},t.prototype.LA=function(e){var r=this.currIdx+e;return r<0||this.tokVectorLength<=r?na.END_OF_FILE:this.tokVector[r]},t.prototype.consumeToken=function(){this.currIdx++},t.prototype.exportLexerState=function(){return this.currIdx},t.prototype.importLexerState=function(e){this.currIdx=e},t.prototype.resetLexerState=function(){this.currIdx=-1},t.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},t.prototype.getLexerPosition=function(){return this.exportLexerState()},t}();Zt.LexerAdapter=js});var oa=R(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.RecognizerApi=void 0;var aa=k(),Vs=et(),Xr=ce(),Ks=mt(),zs=jr(),Hs=ne(),Ys=function(){function t(){}return t.prototype.ACTION=function(e){return e.call(this)},t.prototype.consume=function(e,r,n){return this.consumeInternal(r,e,n)},t.prototype.subrule=function(e,r,n){return this.subruleInternal(r,e,n)},t.prototype.option=function(e,r){return this.optionInternal(r,e)},t.prototype.or=function(e,r){return this.orInternal(r,e)},t.prototype.many=function(e,r){return this.manyInternal(e,r)},t.prototype.atLeastOne=function(e,r){return this.atLeastOneInternal(e,r)},t.prototype.CONSUME=function(e,r){return this.consumeInternal(e,0,r)},t.prototype.CONSUME1=function(e,r){return this.consumeInternal(e,1,r)},t.prototype.CONSUME2=function(e,r){return this.consumeInternal(e,2,r)},t.prototype.CONSUME3=function(e,r){return this.consumeInternal(e,3,r)},t.prototype.CONSUME4=function(e,r){return this.consumeInternal(e,4,r)},t.prototype.CONSUME5=function(e,r){return this.consumeInternal(e,5,r)},t.prototype.CONSUME6=function(e,r){return this.consumeInternal(e,6,r)},t.prototype.CONSUME7=function(e,r){return this.consumeInternal(e,7,r)},t.prototype.CONSUME8=function(e,r){return this.consumeInternal(e,8,r)},t.prototype.CONSUME9=function(e,r){return this.consumeInternal(e,9,r)},t.prototype.SUBRULE=function(e,r){return this.subruleInternal(e,0,r)},t.prototype.SUBRULE1=function(e,r){return this.subruleInternal(e,1,r)},t.prototype.SUBRULE2=function(e,r){return this.subruleInternal(e,2,r)},t.prototype.SUBRULE3=function(e,r){return this.subruleInternal(e,3,r)},t.prototype.SUBRULE4=function(e,r){return this.subruleInternal(e,4,r)},t.prototype.SUBRULE5=function(e,r){return this.subruleInternal(e,5,r)},t.prototype.SUBRULE6=function(e,r){return this.subruleInternal(e,6,r)},t.prototype.SUBRULE7=function(e,r){return this.subruleInternal(e,7,r)},t.prototype.SUBRULE8=function(e,r){return this.subruleInternal(e,8,r)},t.prototype.SUBRULE9=function(e,r){return this.subruleInternal(e,9,r)},t.prototype.OPTION=function(e){return this.optionInternal(e,0)},t.prototype.OPTION1=function(e){return this.optionInternal(e,1)},t.prototype.OPTION2=function(e){return this.optionInternal(e,2)},t.prototype.OPTION3=function(e){return this.optionInternal(e,3)},t.prototype.OPTION4=function(e){return this.optionInternal(e,4)},t.prototype.OPTION5=function(e){return this.optionInternal(e,5)},t.prototype.OPTION6=function(e){return this.optionInternal(e,6)},t.prototype.OPTION7=function(e){return this.optionInternal(e,7)},t.prototype.OPTION8=function(e){return this.optionInternal(e,8)},t.prototype.OPTION9=function(e){return this.optionInternal(e,9)},t.prototype.OR=function(e){return this.orInternal(e,0)},t.prototype.OR1=function(e){return this.orInternal(e,1)},t.prototype.OR2=function(e){return this.orInternal(e,2)},t.prototype.OR3=function(e){return this.orInternal(e,3)},t.prototype.OR4=function(e){return this.orInternal(e,4)},t.prototype.OR5=function(e){return this.orInternal(e,5)},t.prototype.OR6=function(e){return this.orInternal(e,6)},t.prototype.OR7=function(e){return this.orInternal(e,7)},t.prototype.OR8=function(e){return this.orInternal(e,8)},t.prototype.OR9=function(e){return this.orInternal(e,9)},t.prototype.MANY=function(e){this.manyInternal(0,e)},t.prototype.MANY1=function(e){this.manyInternal(1,e)},t.prototype.MANY2=function(e){this.manyInternal(2,e)},t.prototype.MANY3=function(e){this.manyInternal(3,e)},t.prototype.MANY4=function(e){this.manyInternal(4,e)},t.prototype.MANY5=function(e){this.manyInternal(5,e)},t.prototype.MANY6=function(e){this.manyInternal(6,e)},t.prototype.MANY7=function(e){this.manyInternal(7,e)},t.prototype.MANY8=function(e){this.manyInternal(8,e)},t.prototype.MANY9=function(e){this.manyInternal(9,e)},t.prototype.MANY_SEP=function(e){this.manySepFirstInternal(0,e)},t.prototype.MANY_SEP1=function(e){this.manySepFirstInternal(1,e)},t.prototype.MANY_SEP2=function(e){this.manySepFirstInternal(2,e)},t.prototype.MANY_SEP3=function(e){this.manySepFirstInternal(3,e)},t.prototype.MANY_SEP4=function(e){this.manySepFirstInternal(4,e)},t.prototype.MANY_SEP5=function(e){this.manySepFirstInternal(5,e)},t.prototype.MANY_SEP6=function(e){this.manySepFirstInternal(6,e)},t.prototype.MANY_SEP7=function(e){this.manySepFirstInternal(7,e)},t.prototype.MANY_SEP8=function(e){this.manySepFirstInternal(8,e)},t.prototype.MANY_SEP9=function(e){this.manySepFirstInternal(9,e)},t.prototype.AT_LEAST_ONE=function(e){this.atLeastOneInternal(0,e)},t.prototype.AT_LEAST_ONE1=function(e){return this.atLeastOneInternal(1,e)},t.prototype.AT_LEAST_ONE2=function(e){this.atLeastOneInternal(2,e)},t.prototype.AT_LEAST_ONE3=function(e){this.atLeastOneInternal(3,e)},t.prototype.AT_LEAST_ONE4=function(e){this.atLeastOneInternal(4,e)},t.prototype.AT_LEAST_ONE5=function(e){this.atLeastOneInternal(5,e)},t.prototype.AT_LEAST_ONE6=function(e){this.atLeastOneInternal(6,e)},t.prototype.AT_LEAST_ONE7=function(e){this.atLeastOneInternal(7,e)},t.prototype.AT_LEAST_ONE8=function(e){this.atLeastOneInternal(8,e)},t.prototype.AT_LEAST_ONE9=function(e){this.atLeastOneInternal(9,e)},t.prototype.AT_LEAST_ONE_SEP=function(e){this.atLeastOneSepFirstInternal(0,e)},t.prototype.AT_LEAST_ONE_SEP1=function(e){this.atLeastOneSepFirstInternal(1,e)},t.prototype.AT_LEAST_ONE_SEP2=function(e){this.atLeastOneSepFirstInternal(2,e)},t.prototype.AT_LEAST_ONE_SEP3=function(e){this.atLeastOneSepFirstInternal(3,e)},t.prototype.AT_LEAST_ONE_SEP4=function(e){this.atLeastOneSepFirstInternal(4,e)},t.prototype.AT_LEAST_ONE_SEP5=function(e){this.atLeastOneSepFirstInternal(5,e)},t.prototype.AT_LEAST_ONE_SEP6=function(e){this.atLeastOneSepFirstInternal(6,e)},t.prototype.AT_LEAST_ONE_SEP7=function(e){this.atLeastOneSepFirstInternal(7,e)},t.prototype.AT_LEAST_ONE_SEP8=function(e){this.atLeastOneSepFirstInternal(8,e)},t.prototype.AT_LEAST_ONE_SEP9=function(e){this.atLeastOneSepFirstInternal(9,e)},t.prototype.RULE=function(e,r,n){if(n===void 0&&(n=Xr.DEFAULT_RULE_CONFIG),aa.contains(this.definedRulesNames,e)){var i=Ks.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),a={message:i,type:Xr.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(a)}this.definedRulesNames.push(e);var o=this.defineRule(e,r,n);return this[e]=o,o},t.prototype.OVERRIDE_RULE=function(e,r,n){n===void 0&&(n=Xr.DEFAULT_RULE_CONFIG);var i=[];i=i.concat(zs.validateRuleIsOverridden(e,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(i);var a=this.defineRule(e,r,n);return this[e]=a,a},t.prototype.BACKTRACK=function(e,r){return function(){this.isBackTrackingStack.push(1);var n=this.saveRecogState();try{return e.apply(this,r),!0}catch(i){if(Vs.isRecognitionException(i))return!1;throw i}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}},t.prototype.getGAstProductions=function(){return this.gastProductionsCache},t.prototype.getSerializedGastProductions=function(){return Hs.serializeGrammar(aa.values(this.gastProductionsCache))},t}();Qt.RecognizerApi=Ys});var la=R(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.RecognizerEngine=void 0;var q=k(),le=Yt(),er=et(),sa=yt(),rt=Tt(),ua=ce(),Xs=zr(),ca=Ue(),Rt=Xe(),$s=Hr(),Zs=function(){function t(){}return t.prototype.initRecognizerEngine=function(e,r){if(this.className=$s.classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Rt.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},q.has(r,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(q.isArray(e)){if(q.isEmpty(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(q.isArray(e))this.tokensMap=q.reduce(e,function(o,s){return o[s.name]=s,o},{});else if(q.has(e,"modes")&&q.every(q.flatten(q.values(e.modes)),Rt.isTokenType)){var n=q.flatten(q.values(e.modes)),i=q.uniq(n);this.tokensMap=q.reduce(i,function(o,s){return o[s.name]=s,o},{})}else if(q.isObject(e))this.tokensMap=q.cloneObj(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=ca.EOF;var a=q.every(q.values(e),function(o){return q.isEmpty(o.categoryMatches)});this.tokenMatcher=a?Rt.tokenStructuredMatcherNoCategories:Rt.tokenStructuredMatcher,Rt.augmentTokenTypes(q.values(this.tokensMap))},t.prototype.defineRule=function(e,r,n){if(this.selfAnalysisDone)throw Error("Grammar rule <"+e+`> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);var i=q.has(n,"resyncEnabled")?n.resyncEnabled:ua.DEFAULT_RULE_CONFIG.resyncEnabled,a=q.has(n,"recoveryValueFunc")?n.recoveryValueFunc:ua.DEFAULT_RULE_CONFIG.recoveryValueFunc,o=this.ruleShortNameIdx<r},t.prototype.orInternal=function(e,r){var n=this.getKeyForAutomaticLookahead(le.OR_IDX,r),i=q.isArray(e)?e:e.DEF,a=this.getLaFuncFromCache(n),o=a.call(this,i);if(o!==void 0){var s=i[o];return s.ALT.call(this)}this.raiseNoAltException(r,e.ERR_MSG)},t.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var e=this.LA(1),r=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new er.NotAllInputParsedException(r,e))}},t.prototype.subruleInternal=function(e,r,n){var i;try{var a=n!==void 0?n.ARGS:void 0;return i=e.call(this,r,a),this.cstPostNonTerminal(i,n!==void 0&&n.LABEL!==void 0?n.LABEL:e.ruleName),i}catch(o){this.subruleInternalError(o,n,e.ruleName)}},t.prototype.subruleInternalError=function(e,r,n){throw er.isRecognitionException(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,r!==void 0&&r.LABEL!==void 0?r.LABEL:n),delete e.partialCstResult),e},t.prototype.consumeInternal=function(e,r,n){var i;try{var a=this.LA(1);this.tokenMatcher(a,e)===!0?(this.consumeToken(),i=a):this.consumeInternalError(e,a,n)}catch(o){i=this.consumeInternalRecovery(e,r,o)}return this.cstPostTerminal(n!==void 0&&n.LABEL!==void 0?n.LABEL:e.name,i),i},t.prototype.consumeInternalError=function(e,r,n){var i,a=this.LA(0);throw n!==void 0&&n.ERR_MSG?i=n.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:r,previous:a,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new er.MismatchedTokenException(i,r,a))},t.prototype.consumeInternalRecovery=function(e,r,n){if(this.recoveryEnabled&&n.name==="MismatchedTokenException"&&!this.isBackTracking()){var i=this.getFollowsForInRuleRecovery(e,r);try{return this.tryInRuleRecovery(e,i)}catch(a){throw a.name===Xs.IN_RULE_RECOVERY_EXCEPTION?n:a}}else throw n},t.prototype.saveRecogState=function(){var e=this.errors,r=q.cloneArr(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:r,CST_STACK:this.CST_STACK}},t.prototype.reloadRecogState=function(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK},t.prototype.ruleInvocationStateUpdate=function(e,r,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(r,e)},t.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},t.prototype.getCurrRuleFullName=function(){var e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]},t.prototype.shortRuleNameToFullName=function(e){return this.shortRuleNameToFull[e]},t.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),ca.EOF)},t.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},t}();Jt.RecognizerEngine=Zs});var pa=R(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.ErrorHandler=void 0;var $r=et(),Zr=k(),fa=yt(),Qs=ce(),Js=function(){function t(){}return t.prototype.initErrorHandler=function(e){this._errors=[],this.errorMessageProvider=Zr.has(e,"errorMessageProvider")?e.errorMessageProvider:Qs.DEFAULT_PARSER_CONFIG.errorMessageProvider},t.prototype.SAVE_ERROR=function(e){if($r.isRecognitionException(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Zr.cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(t.prototype,"errors",{get:function(){return Zr.cloneArr(this._errors)},set:function(e){this._errors=e},enumerable:!1,configurable:!0}),t.prototype.raiseEarlyExitException=function(e,r,n){for(var i=this.getCurrRuleFullName(),a=this.getGAstProductions()[i],o=fa.getLookaheadPathsForOptionalProd(e,a,r,this.maxLookahead),s=o[0],c=[],f=1;f<=this.maxLookahead;f++)c.push(this.LA(f));var p=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:s,actual:c,previous:this.LA(0),customUserDescription:n,ruleName:i});throw this.SAVE_ERROR(new $r.EarlyExitException(p,this.LA(1),this.LA(0)))},t.prototype.raiseNoAltException=function(e,r){for(var n=this.getCurrRuleFullName(),i=this.getGAstProductions()[n],a=fa.getLookaheadPathsForOr(e,i,this.maxLookahead),o=[],s=1;s<=this.maxLookahead;s++)o.push(this.LA(s));var c=this.LA(0),f=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:a,actual:o,previous:c,customUserDescription:r,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new $r.NoViableAltException(f,this.LA(1),c))},t}();tr.ErrorHandler=Js});var va=R(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.ContentAssist=void 0;var ha=Tt(),da=k(),eu=function(){function t(){}return t.prototype.initContentAssist=function(){},t.prototype.computeContentAssist=function(e,r){var n=this.gastProductionsCache[e];if(da.isUndefined(n))throw Error("Rule ->"+e+"<- does not exist in this grammar.");return ha.nextPossibleTokensAfter([n],r,this.tokenMatcher,this.maxLookahead)},t.prototype.getNextPossibleTokenTypes=function(e){var r=da.first(e.ruleStack),n=this.getGAstProductions(),i=n[r],a=new ha.NextAfterTokenWalker(i,e).startWalking();return a},t}();rr.ContentAssist=eu});var Ra=R(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.GastRecorder=void 0;var oe=k(),Pe=ne(),tu=ft(),ma=Xe(),Ea=Ue(),ru=ce(),nu=Yt(),ir={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(ir);var Ta=!0,ya=Math.pow(2,nu.BITS_FOR_OCCURRENCE_IDX)-1,_a=Ea.createToken({name:"RECORDING_PHASE_TOKEN",pattern:tu.Lexer.NA});ma.augmentTokenTypes([_a]);var ga=Ea.createTokenInstance(_a,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(ga);var iu={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},ou=function(){function t(){}return t.prototype.initGastRecorder=function(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1},t.prototype.enableRecording=function(){var e=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var r=function(i){var a=i>0?i:"";e["CONSUME"+a]=function(o,s){return this.consumeInternalRecord(o,i,s)},e["SUBRULE"+a]=function(o,s){return this.subruleInternalRecord(o,i,s)},e["OPTION"+a]=function(o){return this.optionInternalRecord(o,i)},e["OR"+a]=function(o){return this.orInternalRecord(o,i)},e["MANY"+a]=function(o){this.manyInternalRecord(i,o)},e["MANY_SEP"+a]=function(o){this.manySepFirstInternalRecord(i,o)},e["AT_LEAST_ONE"+a]=function(o){this.atLeastOneInternalRecord(i,o)},e["AT_LEAST_ONE_SEP"+a]=function(o){this.atLeastOneSepFirstInternalRecord(i,o)}},n=0;n<10;n++)r(n);e.consume=function(i,a,o){return this.consumeInternalRecord(a,i,o)},e.subrule=function(i,a,o){return this.subruleInternalRecord(a,i,o)},e.option=function(i,a){return this.optionInternalRecord(a,i)},e.or=function(i,a){return this.orInternalRecord(a,i)},e.many=function(i,a){this.manyInternalRecord(i,a)},e.atLeastOne=function(i,a){this.atLeastOneInternalRecord(i,a)},e.ACTION=e.ACTION_RECORD,e.BACKTRACK=e.BACKTRACK_RECORD,e.LA=e.LA_RECORD})},t.prototype.disableRecording=function(){var e=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var r=0;r<10;r++){var n=r>0?r:"";delete e["CONSUME"+n],delete e["SUBRULE"+n],delete e["OPTION"+n],delete e["OR"+n],delete e["MANY"+n],delete e["MANY_SEP"+n],delete e["AT_LEAST_ONE"+n],delete e["AT_LEAST_ONE_SEP"+n]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})},t.prototype.ACTION_RECORD=function(e){},t.prototype.BACKTRACK_RECORD=function(e,r){return function(){return!0}},t.prototype.LA_RECORD=function(e){return ru.END_OF_FILE},t.prototype.topLevelRuleRecord=function(e,r){try{var n=new Pe.Rule({definition:[],name:e});return n.name=e,this.recordingProdStack.push(n),r.call(this),this.recordingProdStack.pop(),n}catch(i){if(i.KNOWN_RECORDER_ERROR!==!0)try{i.message=i.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch(a){throw i}throw i}},t.prototype.optionInternalRecord=function(e,r){return Ot.call(this,Pe.Option,e,r)},t.prototype.atLeastOneInternalRecord=function(e,r){Ot.call(this,Pe.RepetitionMandatory,r,e)},t.prototype.atLeastOneSepFirstInternalRecord=function(e,r){Ot.call(this,Pe.RepetitionMandatoryWithSeparator,r,e,Ta)},t.prototype.manyInternalRecord=function(e,r){Ot.call(this,Pe.Repetition,r,e)},t.prototype.manySepFirstInternalRecord=function(e,r){Ot.call(this,Pe.RepetitionWithSeparator,r,e,Ta)},t.prototype.orInternalRecord=function(e,r){return au.call(this,e,r)},t.prototype.subruleInternalRecord=function(e,r,n){if(ar(r),!e||oe.has(e,"ruleName")===!1){var i=new Error(" argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(e)+">")+(` + inside top level rule: <`+this.recordingProdStack[0].name+">"));throw i.KNOWN_RECORDER_ERROR=!0,i}var a=oe.peek(this.recordingProdStack),o=e.ruleName,s=new Pe.NonTerminal({idx:r,nonTerminalName:o,referencedRule:void 0});return a.definition.push(s),this.outputCst?iu:ir},t.prototype.consumeInternalRecord=function(e,r,n){if(ar(r),!ma.hasShortKeyProperty(e)){var i=new Error(" argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(e)+">")+(` + inside top level rule: <`+this.recordingProdStack[0].name+">"));throw i.KNOWN_RECORDER_ERROR=!0,i}var a=oe.peek(this.recordingProdStack),o=new Pe.Terminal({idx:r,terminalType:e});return a.definition.push(o),ga},t}();nr.GastRecorder=ou;function Ot(t,e,r,n){n===void 0&&(n=!1),ar(r);var i=oe.peek(this.recordingProdStack),a=oe.isFunction(e)?e:e.DEF,o=new t({definition:[],idx:r});return n&&(o.separator=e.SEP),oe.has(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),a.call(this),i.definition.push(o),this.recordingProdStack.pop(),ir}function au(t,e){var r=this;ar(e);var n=oe.peek(this.recordingProdStack),i=oe.isArray(t)===!1,a=i===!1?t:t.DEF,o=new Pe.Alternation({definition:[],idx:e,ignoreAmbiguities:i&&t.IGNORE_AMBIGUITIES===!0});oe.has(t,"MAX_LOOKAHEAD")&&(o.maxLookahead=t.MAX_LOOKAHEAD);var s=oe.some(a,function(c){return oe.isFunction(c.GATE)});return o.hasPredicates=s,n.definition.push(o),oe.forEach(a,function(c){var f=new Pe.Alternative({definition:[]});o.definition.push(f),oe.has(c,"IGNORE_AMBIGUITIES")?f.ignoreAmbiguities=c.IGNORE_AMBIGUITIES:oe.has(c,"GATE")&&(f.ignoreAmbiguities=!0),r.recordingProdStack.push(f),c.ALT.call(r),r.recordingProdStack.pop()}),ir}function Aa(t){return t===0?"":""+t}function ar(t){if(t<0||t>ya){var e=new Error("Invalid DSL Method idx value: <"+t+`> + `+("Idx value must be a none negative value smaller than "+(ya+1)));throw e.KNOWN_RECORDER_ERROR=!0,e}}});var Na=R(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.PerformanceTracer=void 0;var Oa=k(),su=ce(),uu=function(){function t(){}return t.prototype.initPerformanceTracer=function(e){if(Oa.has(e,"traceInitPerf")){var r=e.traceInitPerf,n=typeof r=="number";this.traceInitMaxIdent=n?r:Infinity,this.traceInitPerf=n?r>0:r}else this.traceInitMaxIdent=0,this.traceInitPerf=su.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},t.prototype.TRACE_INIT=function(e,r){if(this.traceInitPerf===!0){this.traceInitIndent++;var n=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <"+e+">");var i=Oa.timer(r),a=i.time,o=i.value,s=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,o}else return r()},t}();or.PerformanceTracer=uu});var Ia=R(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.applyMixins=void 0;function cu(t,e){e.forEach(function(r){var n=r.prototype;Object.getOwnPropertyNames(n).forEach(function(i){if(i!=="constructor"){var a=Object.getOwnPropertyDescriptor(n,i);a&&(a.get||a.set)?Object.defineProperty(t.prototype,i,a):t.prototype[i]=r.prototype[i]}})})}sr.applyMixins=cu});var ce=R(U=>{"use strict";var ka=U&&U.__extends||function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(n[a]=i[a])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(U,"__esModule",{value:!0});U.EmbeddedActionsParser=U.CstParser=U.Parser=U.EMPTY_ALT=U.ParserDefinitionErrorType=U.DEFAULT_RULE_CONFIG=U.DEFAULT_PARSER_CONFIG=U.END_OF_FILE=void 0;var ee=k(),lu=pi(),Pa=Ue(),Sa=mt(),xa=Ui(),fu=zr(),pu=zi(),hu=ra(),du=ia(),vu=oa(),mu=la(),Eu=pa(),Tu=va(),yu=Ra(),_u=Na(),gu=Ia();U.END_OF_FILE=Pa.createTokenInstance(Pa.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(U.END_OF_FILE);U.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:Sa.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1});U.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var Au;(function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(Au=U.ParserDefinitionErrorType||(U.ParserDefinitionErrorType={}));function Ru(t){return t===void 0&&(t=void 0),function(){return t}}U.EMPTY_ALT=Ru;var ur=function(){function t(e,r){this.definitionErrors=[],this.selfAnalysisDone=!1;var n=this;if(n.initErrorHandler(r),n.initLexerAdapter(),n.initLooksAhead(r),n.initRecognizerEngine(e,r),n.initRecoverable(r),n.initTreeBuilder(r),n.initContentAssist(),n.initGastRecorder(r),n.initPerformanceTracer(r),ee.has(r,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=ee.has(r,"skipValidations")?r.skipValidations:U.DEFAULT_PARSER_CONFIG.skipValidations}return t.performSelfAnalysis=function(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")},t.prototype.performSelfAnalysis=function(){var e=this;this.TRACE_INIT("performSelfAnalysis",function(){var r;e.selfAnalysisDone=!0;var n=e.className;e.TRACE_INIT("toFastProps",function(){ee.toFastProperties(e)}),e.TRACE_INIT("Grammar Recording",function(){try{e.enableRecording(),ee.forEach(e.definedRulesNames,function(a){var o=e[a],s=o.originalGrammarAction,c=void 0;e.TRACE_INIT(a+" Rule",function(){c=e.topLevelRuleRecord(a,s)}),e.gastProductionsCache[a]=c})}finally{e.disableRecording()}});var i=[];if(e.TRACE_INIT("Grammar Resolving",function(){i=xa.resolveGrammar({rules:ee.values(e.gastProductionsCache)}),e.definitionErrors=e.definitionErrors.concat(i)}),e.TRACE_INIT("Grammar Validations",function(){if(ee.isEmpty(i)&&e.skipValidations===!1){var a=xa.validateGrammar({rules:ee.values(e.gastProductionsCache),maxLookahead:e.maxLookahead,tokenTypes:ee.values(e.tokensMap),errMsgProvider:Sa.defaultGrammarValidatorErrorProvider,grammarName:n});e.definitionErrors=e.definitionErrors.concat(a)}}),ee.isEmpty(e.definitionErrors)&&(e.recoveryEnabled&&e.TRACE_INIT("computeAllProdsFollows",function(){var a=lu.computeAllProdsFollows(ee.values(e.gastProductionsCache));e.resyncFollows=a}),e.TRACE_INIT("ComputeLookaheadFunctions",function(){e.preComputeLookaheadFunctions(ee.values(e.gastProductionsCache))})),!t.DEFER_DEFINITION_ERRORS_HANDLING&&!ee.isEmpty(e.definitionErrors))throw r=ee.map(e.definitionErrors,function(a){return a.message}),new Error(`Parser Definition Errors detected: + `+r.join(` +------------------------------- +`))})},t.DEFER_DEFINITION_ERRORS_HANDLING=!1,t}();U.Parser=ur;gu.applyMixins(ur,[fu.Recoverable,pu.LooksAhead,hu.TreeBuilder,du.LexerAdapter,mu.RecognizerEngine,vu.RecognizerApi,Eu.ErrorHandler,Tu.ContentAssist,yu.GastRecorder,_u.PerformanceTracer]);var Ou=function(t){ka(e,t);function e(r,n){n===void 0&&(n=U.DEFAULT_PARSER_CONFIG);var i=this,a=ee.cloneObj(n);return a.outputCst=!0,i=t.call(this,r,a)||this,i}return e}(ur);U.CstParser=Ou;var Nu=function(t){ka(e,t);function e(r,n){n===void 0&&(n=U.DEFAULT_PARSER_CONFIG);var i=this,a=ee.cloneObj(n);return a.outputCst=!1,i=t.call(this,r,a)||this,i}return e}(ur);U.EmbeddedActionsParser=Nu});var La=R(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.createSyntaxDiagramsCode=void 0;var Ca=Er();function Iu(t,e){var r=e===void 0?{}:e,n=r.resourceBase,i=n===void 0?"https://unpkg.com/chevrotain@"+Ca.VERSION+"/diagrams/":n,a=r.css,o=a===void 0?"https://unpkg.com/chevrotain@"+Ca.VERSION+"/diagrams/diagrams.css":a,s=` + + + + + +`,c=` + +`,f=` + + + + +`,p=` +
+`,l=` + +`,m=` + +`;return s+c+f+p+l+m}cr.createSyntaxDiagramsCode=Iu});var Fa=R(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.Parser=E.createSyntaxDiagramsCode=E.clearCache=E.GAstVisitor=E.serializeProduction=E.serializeGrammar=E.Terminal=E.Rule=E.RepetitionWithSeparator=E.RepetitionMandatoryWithSeparator=E.RepetitionMandatory=E.Repetition=E.Option=E.NonTerminal=E.Alternative=E.Alternation=E.defaultLexerErrorProvider=E.NoViableAltException=E.NotAllInputParsedException=E.MismatchedTokenException=E.isRecognitionException=E.EarlyExitException=E.defaultParserErrorProvider=E.tokenName=E.tokenMatcher=E.tokenLabel=E.EOF=E.createTokenInstance=E.createToken=E.LexerDefinitionErrorType=E.Lexer=E.EMPTY_ALT=E.ParserDefinitionErrorType=E.EmbeddedActionsParser=E.CstParser=E.VERSION=void 0;var ku=Er();Object.defineProperty(E,"VERSION",{enumerable:!0,get:function(){return ku.VERSION}});var lr=ce();Object.defineProperty(E,"CstParser",{enumerable:!0,get:function(){return lr.CstParser}});Object.defineProperty(E,"EmbeddedActionsParser",{enumerable:!0,get:function(){return lr.EmbeddedActionsParser}});Object.defineProperty(E,"ParserDefinitionErrorType",{enumerable:!0,get:function(){return lr.ParserDefinitionErrorType}});Object.defineProperty(E,"EMPTY_ALT",{enumerable:!0,get:function(){return lr.EMPTY_ALT}});var Ma=ft();Object.defineProperty(E,"Lexer",{enumerable:!0,get:function(){return Ma.Lexer}});Object.defineProperty(E,"LexerDefinitionErrorType",{enumerable:!0,get:function(){return Ma.LexerDefinitionErrorType}});var nt=Ue();Object.defineProperty(E,"createToken",{enumerable:!0,get:function(){return nt.createToken}});Object.defineProperty(E,"createTokenInstance",{enumerable:!0,get:function(){return nt.createTokenInstance}});Object.defineProperty(E,"EOF",{enumerable:!0,get:function(){return nt.EOF}});Object.defineProperty(E,"tokenLabel",{enumerable:!0,get:function(){return nt.tokenLabel}});Object.defineProperty(E,"tokenMatcher",{enumerable:!0,get:function(){return nt.tokenMatcher}});Object.defineProperty(E,"tokenName",{enumerable:!0,get:function(){return nt.tokenName}});var Pu=mt();Object.defineProperty(E,"defaultParserErrorProvider",{enumerable:!0,get:function(){return Pu.defaultParserErrorProvider}});var Nt=et();Object.defineProperty(E,"EarlyExitException",{enumerable:!0,get:function(){return Nt.EarlyExitException}});Object.defineProperty(E,"isRecognitionException",{enumerable:!0,get:function(){return Nt.isRecognitionException}});Object.defineProperty(E,"MismatchedTokenException",{enumerable:!0,get:function(){return Nt.MismatchedTokenException}});Object.defineProperty(E,"NotAllInputParsedException",{enumerable:!0,get:function(){return Nt.NotAllInputParsedException}});Object.defineProperty(E,"NoViableAltException",{enumerable:!0,get:function(){return Nt.NoViableAltException}});var Su=kr();Object.defineProperty(E,"defaultLexerErrorProvider",{enumerable:!0,get:function(){return Su.defaultLexerErrorProvider}});var Se=ne();Object.defineProperty(E,"Alternation",{enumerable:!0,get:function(){return Se.Alternation}});Object.defineProperty(E,"Alternative",{enumerable:!0,get:function(){return Se.Alternative}});Object.defineProperty(E,"NonTerminal",{enumerable:!0,get:function(){return Se.NonTerminal}});Object.defineProperty(E,"Option",{enumerable:!0,get:function(){return Se.Option}});Object.defineProperty(E,"Repetition",{enumerable:!0,get:function(){return Se.Repetition}});Object.defineProperty(E,"RepetitionMandatory",{enumerable:!0,get:function(){return Se.RepetitionMandatory}});Object.defineProperty(E,"RepetitionMandatoryWithSeparator",{enumerable:!0,get:function(){return Se.RepetitionMandatoryWithSeparator}});Object.defineProperty(E,"RepetitionWithSeparator",{enumerable:!0,get:function(){return Se.RepetitionWithSeparator}});Object.defineProperty(E,"Rule",{enumerable:!0,get:function(){return Se.Rule}});Object.defineProperty(E,"Terminal",{enumerable:!0,get:function(){return Se.Terminal}});var ba=ne();Object.defineProperty(E,"serializeGrammar",{enumerable:!0,get:function(){return ba.serializeGrammar}});Object.defineProperty(E,"serializeProduction",{enumerable:!0,get:function(){return ba.serializeProduction}});var xu=$e();Object.defineProperty(E,"GAstVisitor",{enumerable:!0,get:function(){return xu.GAstVisitor}});function Cu(){console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. + It performs no action other than printing this message. + Please avoid using it as it will be completely removed in the future`)}E.clearCache=Cu;var Lu=La();Object.defineProperty(E,"createSyntaxDiagramsCode",{enumerable:!0,get:function(){return Lu.createSyntaxDiagramsCode}});var Mu=function(){function t(){throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. +See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`)}return t}();E.Parser=Mu});export default Fa(); diff --git a/renderer/jsm/libs/draco/README.md b/renderer/jsm/libs/draco/README.md new file mode 100644 index 0000000..6dfa1d3 --- /dev/null +++ b/renderer/jsm/libs/draco/README.md @@ -0,0 +1,32 @@ +# Draco 3D Data Compression + +Draco is an open-source library for compressing and decompressing 3D geometric meshes and point clouds. It is intended to improve the storage and transmission of 3D graphics. + +[Website](https://google.github.io/draco/) | [GitHub](https://github.com/google/draco) + +## Contents + +This folder contains three utilities: + +* `draco_decoder.js` — Emscripten-compiled decoder, compatible with any modern browser. +* `draco_decoder.wasm` — WebAssembly decoder, compatible with newer browsers and devices. +* `draco_wasm_wrapper.js` — JavaScript wrapper for the WASM decoder. + +Each file is provided in two variations: + +* **Default:** Latest stable builds, tracking the project's [master branch](https://github.com/google/draco). +* **glTF:** Builds targeted by the [glTF mesh compression extension](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression), tracking the [corresponding Draco branch](https://github.com/google/draco/tree/gltf_2.0_draco_extension). + +Either variation may be used with `THREE.DRACOLoader`: + +```js +var dracoLoader = new THREE.DRACOLoader(); +dracoLoader.setDecoderPath('path/to/decoders/'); +dracoLoader.setDecoderConfig({type: 'js'}); // (Optional) Override detection of WASM support. +``` + +Further [documentation on GitHub](https://github.com/google/draco/tree/master/javascript/example#static-loading-javascript-decoder). + +## License + +[Apache License 2.0](https://github.com/google/draco/blob/master/LICENSE) diff --git a/renderer/jsm/libs/draco/draco_decoder.js b/renderer/jsm/libs/draco/draco_decoder.js new file mode 100644 index 0000000..1aa9ed1 --- /dev/null +++ b/renderer/jsm/libs/draco/draco_decoder.js @@ -0,0 +1,52 @@ + +var DracoDecoderModule = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(DracoDecoderModule) { + DracoDecoderModule = DracoDecoderModule || {}; + +var Module=typeof DracoDecoderModule!=="undefined"?DracoDecoderModule:{};var isRuntimeInitialized=false;var isModuleParsed=false;Module["onRuntimeInitialized"]=function(){isRuntimeInitialized=true;if(isModuleParsed){if(typeof Module["onModuleLoaded"]==="function"){Module["onModuleLoaded"](Module)}}};Module["onModuleParsed"]=function(){isModuleParsed=true;if(isRuntimeInitialized){if(typeof Module["onModuleLoaded"]==="function"){Module["onModuleLoaded"](Module)}}};function isVersionSupported(versionString){if(typeof versionString!=="string")return false;const version=versionString.split(".");if(version.length<2||version.length>3)return false;if(version[0]==1&&version[1]>=0&&version[1]<=3)return true;if(version[0]!=0||version[1]>10)return false;return true}Module["isVersionSupported"]=isVersionSupported;var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_HAS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_HAS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_NODE=ENVIRONMENT_HAS_NODE&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){scriptDirectory=__dirname+"/";read_=function shell_read(filename,binary){var ret=tryParseAsDataURI(filename);if(ret){return binary?ret:ret.toString()}if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){var data=tryParseAsDataURI(f);if(data){return intArrayToString(data)}return read(f)}}readBinary=function readBinary(f){var data;data=tryParseAsDataURI(f);if(data){return data}if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText}catch(err){var data=tryParseAsDataURI(url);if(data){return intArrayToString(data)}throw err}};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}catch(err){var data=tryParseAsDataURI(url);if(data){return data}throw err}}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}var data=tryParseAsDataURI(url);if(data){onload(data.buffer);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function dynamicAlloc(size){var ret=HEAP32[DYNAMICTOP_PTR>>2];var end=ret+size+15&-16;if(end>_emscripten_get_heap_size()){abort()}HEAP32[DYNAMICTOP_PTR>>2]=end;return ret}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=parseInt(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}function convertJsFunctionToWasm(func,sig){return func}function addFunctionWasm(func,sig){var table=wasmTable;var ret=table.length;try{table.grow(1)}catch(err){if(!err instanceof RangeError){throw err}throw"Unable to grow wasm table. Use a higher value for RESERVED_FUNCTION_POINTERS or set ALLOW_TABLE_GROWTH."}try{table.set(ret,func)}catch(err){if(!err instanceof TypeError){throw err}assert(typeof sig!=="undefined","Missing signature argument to addFunction");var wrapped=convertJsFunctionToWasm(func,sig);table.set(ret,wrapped)}return ret}function removeFunctionWasm(index){}var funcWrappers={};function dynCall(sig,ptr,args){if(args&&args.length){return Module["dynCall_"+sig].apply(null,[ptr].concat(args))}else{return Module["dynCall_"+sig].call(null,ptr)}}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];var WebAssembly={Memory:function(opts){return{buffer:new ArrayBuffer(opts["initial"]*65536),grow:function(amount){var ret=__growWasmMemory(amount);return ret}}},Table:function(opts){var ret=new Array(opts["initial"]);ret.grow=function(by){if(ret.length>=381+0){abort("Unable to grow wasm table. Use a higher value for RESERVED_FUNCTION_POINTERS or set ALLOW_TABLE_GROWTH.")}ret.push(null)};ret.set=function(i,func){ret[i]=func};ret.get=function(i){return ret[i]};return ret},Module:function(binary){return{}},Instance:function(module,info){var decodeBase64=typeof atob==="function"?atob:function(input){var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=enc1<<2|enc2>>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!==64){output=output+String.fromCharCode(chr2)}if(enc4!==64){output=output+String.fromCharCode(chr3)}}while(i>2]=0;q[c>>2]=0;q[c+4>>2]=0;d=dm(b);if(d>>>0<4294967280){a:{b:{if(d>>>0>=11){f=d+16&-16;e=Mm(f);q[c+8>>2]=f|-2147483648;q[c>>2]=e;q[c+4>>2]=d;break b}o[c+11|0]=d;e=c;if(!d){break a}}Cn(e,b,d)}o[d+e|0]=0;a=ga(a,c);if(o[c+11|0]<=-1){An(q[c>>2])}T=c+16|0;return(a|0)!=0}Pm();F()}function ga(a,b){var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0;a=q[a+4>>2];if(a){h=r[b+11|0];i=h<<24>>24<0;h=i?q[b+4>>2]:h;l=i?q[b>>2]:b;while(1){b=a+16|0;g=r[a+27|0];i=g<<24>>24<0;j=i?q[a+20>>2]:g;m=j>>>0>>0;a:{b:{c:{d:{e:{f:{g=m?j:h;if(g){k=i?q[b>>2]:b;n=cm(l,k,g);if(n){break f}}if(h>>>0>>0){break a}if(!g){break d}k=i?q[b>>2]:b;break e}if((n|0)<=-1){break a}}b=cm(k,l,g);if(b){break c}}if(m){break b}return 1}if((b|0)<=-1){break b}return 1}a=a+4|0}a=q[a>>2];if(a){continue}break}}return 0}function ha(a,b){var p=0,r=0,s=0,t=0;p=T-16|0;T=p;q[p+12>>2]=0;q[p+8>>2]=0;q[p>>2]=0;q[p+4>>2]=0;r=dm(b);if(r>>>0<4294967280){a:{b:{if(r>>>0>=11){t=r+16&-16;s=Mm(t);q[p+8>>2]=t|-2147483648;q[p>>2]=s;q[p+4>>2]=r;break b}o[p+11|0]=r;s=p;if(!r){break a}}Cn(s,b,r)}o[r+s|0]=0;Vk(a,p,p+12|0);a=q[p+12>>2];if(o[p+11|0]<=-1){An(q[p>>2])}T=p+16|0;return a}Pm();F()}function ia(a,b,u){var v=0,w=0,x=0,y=0;v=T-32|0;T=v;q[v+24>>2]=0;q[v+16>>2]=0;q[v+20>>2]=0;w=dm(b);if(w>>>0<4294967280){a:{b:{if(w>>>0>=11){y=w+16&-16;x=Mm(y);q[v+24>>2]=y|-2147483648;q[v+16>>2]=x;q[v+20>>2]=w;break b}o[v+27|0]=w;x=v+16|0;if(!w){break a}}Cn(x,b,w)}o[w+x|0]=0;q[v+8>>2]=0;q[v>>2]=0;q[v+4>>2]=0;Wk(a,v+16|0,v);a=q[u>>2];if(a){q[u+4>>2]=a;An(a);q[u+8>>2]=0;q[u>>2]=0;q[u+4>>2]=0}q[u>>2]=q[v>>2];q[u+4>>2]=q[v+4>>2];q[u+8>>2]=q[v+8>>2];if(o[v+27|0]<=-1){An(q[v+16>>2])}T=v+32|0;return}Pm();F()}function ja(a,b){var u=0,z=0,A=0,B=0,C=0;u=T-32|0;T=u;q[u+24>>2]=0;q[u+28>>2]=0;q[u+16>>2]=0;q[u+8>>2]=0;q[u+12>>2]=0;z=dm(b);if(z>>>0<4294967280){a:{b:{if(z>>>0>=11){B=z+16&-16;A=Mm(B);q[u+16>>2]=B|-2147483648;q[u+8>>2]=A;q[u+12>>2]=z;break b}o[u+19|0]=z;A=u+8|0;if(!z){break a}}Cn(A,b,z)}o[z+A|0]=0;Xk(a,u+8|0,u+24|0);C=v[u+24>>3];if(o[u+19|0]<=-1){An(q[u+8>>2])}T=u+32|0;return C}Pm();F()}function ka(a,b,D){var E=0,G=0,H=0,I=0;E=T-16|0;T=E;q[E+8>>2]=0;q[E>>2]=0;q[E+4>>2]=0;G=dm(D);if(G>>>0<4294967280){a:{b:{if(G>>>0>=11){I=G+16&-16;H=Mm(I);q[E+8>>2]=I|-2147483648;q[E>>2]=H;q[E+4>>2]=G;break b}o[E+11|0]=G;H=E;if(!G){break a}}Cn(H,D,G)}o[G+H|0]=0;a=a+16|0;D=0;c:{if(!Yk(b,E,a)){break c}D=q[a>>2];if(o[a+11|0]<=-1){break c}D=a}if(o[E+11|0]<=-1){An(q[E>>2])}T=E+16|0;return D}Pm();F()}function la(a,b,D){var F=0,J=0,K=0,L=0;a:{if(q[a+12>>2]==(b|0)){break a}F=q[a>>2];K=a+4|0;J=q[K>>2];if((F|0)!=(J|0)){while(1){L=J+ -12|0;if(o[J+ -1|0]<=-1){An(q[L>>2])}J=L;if((J|0)!=(F|0)){continue}break}}q[a+12>>2]=b;q[K>>2]=F;J=q[b>>2];K=b+4|0;if((J|0)==(K|0)){break a}L=a+8|0;while(1){b=J+16|0;b:{if(q[L>>2]!=(F|0)){Rm(F,b);b=a+4|0;q[b>>2]=q[b>>2]+12;break b}ma(a,b)}F=q[J+4>>2];c:{if(!F){b=q[J+8>>2];if(q[b>>2]==(J|0)){break c}J=J+8|0;while(1){F=q[J>>2];J=F+8|0;b=q[F+8>>2];if((F|0)!=q[b>>2]){continue}break}break c}while(1){b=F;F=q[F>>2];if(F){continue}break}}if((b|0)==(K|0)){break a}F=q[a+4>>2];J=b;continue}}F=0;d:{if((D|0)<0){break d}b=q[a+4>>2];a=q[a>>2];if((b-a|0)/12>>>0<=D>>>0){break d}F=a+w(D,12)|0;if(o[F+11|0]>-1){break d}F=q[F>>2]}return F}function ma(a,b){var D=0,M=0,N=0,O=0,P=0;a:{b:{c:{N=q[a>>2];P=(q[a+4>>2]-N|0)/12|0;D=P+1|0;if(D>>>0<357913942){N=(q[a+8>>2]-N|0)/12|0;O=N<<1;D=N>>>0<178956970?O>>>0>>0?D:O:357913941;M=0;d:{if(!D){break d}if(D>>>0>=357913942){break c}M=Mm(w(D,12))}N=M+w(D,12)|0;b=Rm(M+w(P,12)|0,b);P=b+12|0;D=q[a+4>>2];M=q[a>>2];if((D|0)==(M|0)){break b}while(1){D=D+ -12|0;O=q[D+4>>2];b=b+ -12|0;q[b>>2]=q[D>>2];q[b+4>>2]=O;O=D+8|0;q[b+8>>2]=q[O>>2];q[D>>2]=0;q[D+4>>2]=0;q[O>>2]=0;if((D|0)!=(M|0)){continue}break}M=q[a+4>>2];D=q[a>>2];break a}bn();F()}ab(1040);F()}D=M}q[a>>2]=b;q[a+8>>2]=N;q[a+4>>2]=P;if((D|0)!=(M|0)){while(1){a=M+ -12|0;if(o[M+ -1|0]<=-1){An(q[a>>2])}M=a;if((a|0)!=(D|0)){continue}break}}if(D){An(D)}}function na(a){var b=0;ck(a);b=a+16|0;q[b>>2]=0;q[b+4>>2]=0;q[a+24>>2]=0;q[a+28>>2]=0;q[a+12>>2]=b;q[a+32>>2]=0;q[a+36>>2]=0;return a}function oa(a){var Q=0;Q=T-32|0;T=Q;hh(Q+8|0,a);a=q[Q+24>>2];if(o[Q+23|0]<=-1){An(q[Q+12>>2])}T=Q+32|0;return a}function pa(a,R,S){var U=0;U=T-16|0;T=U;ih(U,a,R,S);q[a+24>>2]=q[U>>2];Tm(a+28|0,U|4);a=a+24|0;if(o[U+15|0]<=-1){An(q[U+4>>2])}T=U+16|0;return a}function qa(a,R,S){var V=0;V=T-16|0;T=V;jh(V,a,R,S);q[a+24>>2]=q[V>>2];Tm(a+28|0,V|4);a=a+24|0;if(o[V+15|0]<=-1){An(q[V+4>>2])}T=V+16|0;return a}function ra(a,R){var S=0,W=0,X=0,Y=0;S=T-32|0;T=S;q[S+24>>2]=0;q[S+16>>2]=0;q[S+20>>2]=0;W=dm(R);if(W>>>0<4294967280){a:{b:{if(W>>>0>=11){Y=W+16&-16;X=Mm(Y);q[S+24>>2]=Y|-2147483648;q[S+16>>2]=X;q[S+20>>2]=W;break b}o[S+27|0]=W;X=S+16|0;if(!W){break a}}Cn(X,R,W)}o[W+X|0]=0;q[S+8>>2]=67108864;q[S>>2]=0;q[S+4>>2]=0;o[S+4|0]=0;q[S>>2]=1701667182;W=q[a+4>>2];R=-1;c:{if(!W){break c}W=Pk(W,S,S+16|0);R=-1;if(!W){break c}R=el(a,q[W+24>>2])}if(o[S+11|0]<=-1){An(q[S>>2])}if(o[S+27|0]<=-1){An(q[S+16>>2])}T=S+32|0;return R}Pm();F()}function sa(a,R,Z){var _=0,$=0,aa=0,ba=0;_=T-32|0;T=_;q[_+24>>2]=0;q[_+16>>2]=0;q[_+20>>2]=0;a:{ba=dm(R);if(ba>>>0<4294967280){b:{c:{if(ba>>>0>=11){$=ba+16&-16;aa=Mm($);q[_+24>>2]=$|-2147483648;q[_+16>>2]=aa;q[_+20>>2]=ba;break c}o[_+27|0]=ba;aa=_+16|0;if(!ba){break b}}Cn(aa,R,ba)}o[aa+ba|0]=0;q[_+8>>2]=0;q[_>>2]=0;q[_+4>>2]=0;$=dm(Z);if($>>>0>=4294967280){break a}d:{e:{if($>>>0>=11){R=$+16&-16;aa=Mm(R);q[_+8>>2]=R|-2147483648;q[_>>2]=aa;q[_+4>>2]=$;break e}o[_+11|0]=$;aa=_;if(!$){break d}}Cn(aa,Z,$)}o[$+aa|0]=0;Z=q[a+4>>2];R=-1;f:{if(!Z){break f}Z=Pk(Z,_+16|0,_);R=-1;if(!Z){break f}R=el(a,q[Z+24>>2])}a=R;if(o[_+11|0]<=-1){An(q[_>>2])}if(o[_+27|0]<=-1){An(q[_+16>>2])}T=_+32|0;return a}Pm();F()}Pm();F()}function ta(a,o,R){var Z=0,ca=0,da=0;Z=T-16|0;T=Z;ca=q[a+96>>2];q[Z+8>>2]=0;q[Z>>2]=0;q[Z+4>>2]=0;a=Mm(12);q[Z>>2]=a;q[Z+4>>2]=a;da=a+12|0;q[Z+8>>2]=da;ca=Cn(a,ca+w(o,12)|0,12)+12|0;q[Z+4>>2]=ca;o=q[R>>2];if(o){q[R+4>>2]=o;An(o);q[R+8>>2]=0;q[R>>2]=0;q[R+4>>2]=0}q[R>>2]=a;q[R+8>>2]=da;q[R+4>>2]=ca;T=Z+16|0;return 1}function ua(a,o){var R=0,ea=0;R=T-96|0;T=R;Dn(R+16|0,0,76);q[R+92>>2]=-1;q[R+8>>2]=0;q[R>>2]=0;q[R+4>>2]=0;a:{if(va(R+16|0,a,R)){a=q[o>>2];if(a){q[o+4>>2]=a;An(a);q[o+8>>2]=0;q[o>>2]=0;q[o+4>>2]=0}q[o>>2]=q[R>>2];q[o+4>>2]=q[R+4>>2];q[o+8>>2]=q[R+8>>2];q[R+8>>2]=0;q[R>>2]=0;q[R+4>>2]=0;ea=q[R+84>>2];break a}a=q[R>>2];if(!a){break a}q[R+4>>2]=a;An(a)}a=q[R+72>>2];if(a){An(a)}a=q[R+48>>2];if(a){q[R+52>>2]=a;An(a)}a=q[R+36>>2];if(a){q[R+40>>2]=a;An(a)}a=q[R+24>>2];if(a){q[R+28>>2]=a;An(a)}a=q[R+20>>2];q[R+20>>2]=0;if(a){wa(R+16|4,a)}T=R+96|0;return ea}function va(a,o,fa){var ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0;ja=T-16|0;T=ja;a:{if(!xa(a,o)){break a}ia=1;ha=q[o+96>>2];oa=o+100|0;ga=q[oa>>2];if((ha|0)==(ga|0)){break a}pa=a+12|0;qa=a+24|0;ra=a+36|0;na=fa+8|0;la=fa+4|0;while(1){if(!(q[q[a+56>>2]+(ma>>>3&536870908)>>2]>>>(ma&31)&1)){ia=w(ma,3);Jk(a,0,ia);sa=q[pa>>2];ka=q[a+8>>2];Jk(a,1,ia+1|0);ha=q[qa>>2];ga=q[a+20>>2];Jk(a,2,ia+2|0);ia=ha-ga>>2;ha=sa-ka|0;ga=ha>>2;ka=ia>>>0>ga>>>0;ka=q[ra>>2]-q[a+32>>2]>>2>>>0>(ka?ia:ga)>>>0?2:ka?1:ha?0:-1;b:{if(q[a+68>>2]<1){break b}ga=q[a+76>>2];q[ja+12>>2]=ga;ha=q[la>>2];c:{if(ha>>>0>2]){q[ha>>2]=ga;q[la>>2]=ha+4;break c}ya(fa,ja+12|0)}ga=ja;ia=q[((ka<<2)+a|0)+44>>2];ha=-1;d:{if((ia|0)<0){break d}ha=(ia>>>0)/3|0;ha=q[(q[q[a>>2]+96>>2]+w(ha,12)|0)+(ia-w(ha,3)<<2)>>2]}q[ga+8>>2]=ha;ga=q[la>>2];e:{if(ga>>>0>2]){q[ga>>2]=ha;q[la>>2]=ga+4;break e}ya(fa,ja+8|0)}ga=q[a+72>>2]+2|0;q[a+72>>2]=ga;if(!(ga&1)){break b}q[ja+4>>2]=ha;ga=q[la>>2];f:{if(ga>>>0>2]){q[ga>>2]=ha;q[la>>2]=ga+4;break f}ya(fa,ja+4|0)}q[a+72>>2]=q[a+72>>2]+1}za(a,ka,fa);ha=q[o+96>>2];ga=q[oa>>2]}ia=1;ma=ma+1|0;if(ma>>>0<(ga-ha|0)/12>>>0){continue}break}}T=ja+16|0;return ia}function wa(a,o){if(o){a=q[o+76>>2];if(a){q[o+80>>2]=a;An(a)}a=q[o- -64>>2];if(a){q[o+68>>2]=a;An(a)}a=q[o+48>>2];if(a){q[o+52>>2]=a;An(a)}a=q[o+24>>2];if(a){q[o+28>>2]=a;An(a)}a=q[o+12>>2];if(a){q[o+16>>2]=a;An(a)}a=q[o>>2];if(a){q[o+4>>2]=a;An(a)}An(o)}}function xa(a,fa){var ta=0,ua=0,va=0;ta=T-16|0;T=ta;q[a+68>>2]=0;q[a+72>>2]=0;q[a>>2]=fa;Ik(ta+8|0,fa);ua=q[ta+8>>2];q[ta+8>>2]=0;va=q[a+4>>2];q[a+4>>2]=ua;a:{if(!va){q[ta+8>>2]=0;break a}ua=a+4|0;wa(ua,va);va=q[ta+8>>2];q[ta+8>>2]=0;if(va){wa(ta+8|0,va)}ua=q[ua>>2]}if(ua){ua=q[fa+100>>2];fa=q[fa+96>>2];o[ta+7|0]=0;bb(a+56|0,(ua-fa|0)/12|0,ta+7|0);a=1}else{a=0}T=ta+16|0;return a}function ya(a,o){var T=0,fa=0,wa=0,xa=0,ya=0,za=0;a:{wa=q[a>>2];ya=q[a+4>>2]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;break e}ya(Aa,Da+12|0)}Ca=a;Ba=-1;f:{if((o|0)==-1){break f}Fa=((o>>>0)%3|0?-1:2)+o|0;Ba=-1;if((Fa|0)<0){break f}Ba=(Fa>>>0)/3|0;Ba=q[(q[q[a>>2]+96>>2]+w(Ba,12)|0)+(Fa-w(Ba,3)<<2)>>2]}q[Ca+76>>2]=Ba;q[Da+12>>2]=Ba;Ca=q[Ea>>2];if(Ca>>>0>2]){q[Ca>>2]=Ba;q[Ea>>2]=Ca+4;break b}ya(Aa,Da+12|0);break b}Ba=(o|0)<0?-1:q[(q[q[a>>2]+96>>2]+w(Fa,12)|0)+((o>>>0)%3<<2)>>2];q[a+76>>2]=Ba;q[Da+12>>2]=Ba;Ca=q[Ea>>2];g:{if(Ca>>>0>2]){q[Ca>>2]=Ba;q[Ea>>2]=Ca+4;break g}ya(Aa,Da+12|0)}if(Ha&1){Ba=-1;if((o|0)==-1){break a}if(o-w(Fa,3)){o=o+ -1|0;break b}o=o+2|0;break b}Ba=-1;if((o|0)==-1){break a}Ba=o+1|0;o=(Ba>>>0)%3|0?Ba:o+ -2|0}Ba=-1;if((o|0)==-1){break a}Ba=q[q[q[a+4>>2]+12>>2]+(o<<2)>>2]}Ha=Ha+1|0;if((Ha|0)<(Ia|0)){continue}break}}T=Da+16|0}function Aa(a,o,Aa){var Ja=0,Ka=0,La=0;a:{if(t[a+80>>2]>65535){break a}Ka=q[a+96>>2];a=q[a+100>>2]-Ka|0;La=(a|0)/12|0;if((w(La,6)|0)!=(o|0)){break a}if(!a){return 1}a=0;while(1){o=w(a,6)+Aa|0;Ja=w(a,12)+Ka|0;p[o>>1]=q[Ja>>2];p[o+2>>1]=q[Ja+4>>2];p[o+4>>1]=q[Ja+8>>2];Ja=1;a=a+1|0;if(a>>>0>>0){continue}break}}return Ja}function Ba(a,o,Aa){var Ma=0,Na=0,Oa=0;Na=q[a+96>>2];a=q[a+100>>2]-Na|0;Oa=(a|0)/12|0;if((a|0)==(o|0)){if(!o){return 1}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|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 0:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(r[Aa|0]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa/x(255)):Xa;Aa=Aa+1|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 1:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(p[Aa>>1]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa/x(32767)):Xa;Aa=Aa+2|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 2:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(s[Aa>>1]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa/x(65535)):Xa;Aa=Aa+2|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 3:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(q[Aa>>2]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa*x(4.656612873077393e-10)):Xa;Aa=Aa+4|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 4:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(t[Aa>>2]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa*x(2.3283064365386963e-10)):Xa;Aa=Aa+4|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 5:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(+t[Aa>>2]+4294967296*+q[Aa+4>>2]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa*x(1.0842021724855044e-19)):Xa;Aa=Aa+8|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 6:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;Ya=r[a+32|0];while(1){Xa=x(+t[Aa>>2]+4294967296*+t[Aa+4>>2]);u[(Wa<<2)+Ua>>2]=Ya?x(Xa*x(5.421010862427522e-20)):Xa;Aa=Aa+8|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 7:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;while(1){q[(Wa<<2)+Ua>>2]=q[Aa>>2];Aa=Aa+4|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 8:Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;while(1){u[(Wa<<2)+Ua>>2]=v[Aa>>3];Aa=Aa+8|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}break a;case 9:break c}}Za=1;Va=o[a+24|0];if(((Va|0)>(Pa|0)?Pa:Va)<<24>>24>=1){Va=q[q[a>>2]>>2];Aa=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],Aa,0)|0;Aa=Va+Aa|0;while(1){u[(Wa<<2)+Ua>>2]=r[Aa|0]?x(1):x(0);Aa=Aa+1|0;Wa=Wa+1|0;Va=o[a+24|0];if((Wa|0)<((Va|0)>(Pa|0)?Pa:Va)<<24>>24){continue}break}}if((Va|0)>=(Pa|0)){break b}Dn((Va<<2)+Ua|0,0,Pa-Va<<2)}return Za}Dn((Va<<2)+Ua|0,0,Pa-Va<<2);return 1}function Ea(a,Aa,Pa){var Ua=0,_a=0,$a=0,ab=0,bb=0,cb=0,db=0,eb=0;Ua=T-16|0;T=Ua;bb=q[a+80>>2];cb=o[Aa+24|0];a=q[259];q[Ua+8>>2]=q[258];q[Ua+12>>2]=a;a=q[257];q[Ua>>2]=q[256];q[Ua+4>>2]=a;a=w(bb,cb);$a=q[Pa>>2];_a=q[Pa+4>>2]-$a>>2;a:{if(a>>>0>_a>>>0){Fa(Pa,a-_a|0);break a}if(a>>>0>=_a>>>0){break a}q[Pa+4>>2]=$a+(a<<2)}b:{if(!bb){a=1;break b}$a=0;db=Aa+68|0;eb=(cb|0)<1;while(1){a=ab;_a=Aa;if(!r[_a+84|0]){a=q[q[db>>2]+(ab<<2)>>2]}if(!Da(_a,a,o[Aa+24|0],Ua)){a=0;break b}if(!eb){_a=q[Pa>>2];a=0;while(1){q[_a+($a<<2)>>2]=q[(a<<2)+Ua>>2];$a=$a+1|0;a=a+1|0;if((cb|0)!=(a|0)){continue}break}}a=1;ab=ab+1|0;if((bb|0)!=(ab|0)){continue}break}}T=Ua+16|0;return a}function Fa(a,o){var Aa=0,Pa=0,fb=0,gb=0,hb=0,ib=0,jb=0,kb=0,lb=0;Pa=q[a+8>>2];fb=a+4|0;Aa=q[fb>>2];if(Pa-Aa>>2>>>0>=o>>>0){a=o<<2;kb=fb,lb=Dn(Aa,0,a)+a|0,q[kb>>2]=lb;return}a:{fb=q[a>>2];hb=Aa-fb|0;Aa=hb>>2;gb=Aa+o|0;if(gb>>>0<1073741824){jb=Aa<<2;Pa=Pa-fb|0;Aa=Pa>>1;Pa=Pa>>2>>>0<536870911?Aa>>>0>>0?gb:Aa:1073741823;Aa=0;b:{if(!Pa){break b}if(Pa>>>0>=1073741824){break a}ib=Mm(Pa<<2);Aa=ib}Dn(jb+Aa|0,0,o<<2);o=Aa+(gb<<2)|0;gb=Aa+(Pa<<2)|0;if((hb|0)>=1){Cn(ib,fb,hb)}q[a>>2]=Aa;q[a+8>>2]=gb;q[a+4>>2]=o;if(fb){An(fb)}return}bn();F()}ab(1040);F()}function Ga(a,mb,nb){var ob=0,pb=0,qb=0,rb=0,sb=0,tb=0,ub=0,vb=0;pb=T-16|0;T=pb;sb=q[a+80>>2];rb=o[mb+24|0];qb=w(sb,rb);a:{a=q[mb+28>>2];b:{if(!(!r[mb+84|0]|((a|0)!=2?(a|0)!=1:0))){rb=q[mb+48>>2];mb=q[q[mb>>2]>>2];q[pb+8>>2]=0;q[pb>>2]=0;q[pb+4>>2]=0;a=0;if(qb){if((qb|0)<=-1){break a}a=Mm(qb);q[pb>>2]=a;ob=a+qb|0;q[pb+8>>2]=ob;Cn(a,mb+rb|0,qb);q[pb+4>>2]=ob}mb=q[nb>>2];if(mb){q[nb+4>>2]=mb;An(mb);q[nb+8>>2]=0;q[nb>>2]=0;q[nb+4>>2]=0}q[nb>>2]=a;q[nb+8>>2]=ob;q[nb+4>>2]=ob;ob=1;break b}q[pb+8>>2]=0;q[pb>>2]=0;q[pb+4>>2]=0;if(rb){if((rb|0)<=-1){break a}ob=Mm(rb);q[pb>>2]=ob;q[pb+4>>2]=ob;q[pb+8>>2]=ob+rb;a=rb;while(1){o[ob|0]=0;ob=q[pb+4>>2]+1|0;q[pb+4>>2]=ob;a=a+ -1|0;if(a){continue}break}}ob=q[nb>>2];a=q[nb+4>>2]-ob|0;c:{if(qb>>>0>a>>>0){Ha(nb,qb-a|0);break c}if(qb>>>0>=a>>>0){break c}q[nb+4>>2]=ob+qb}d:{if(!sb){ob=1;break d}a=0;tb=mb+68|0;ub=(rb|0)<1;qb=0;while(1){ob=qb;vb=mb;if(!r[mb+84|0]){ob=q[q[tb>>2]+(qb<<2)>>2]}if(!Ia(vb,ob,o[mb+24|0],q[pb>>2])){ob=0;break d}ob=0;if(!ub){while(1){o[q[nb>>2]+a|0]=r[q[pb>>2]+ob|0];a=a+1|0;ob=ob+1|0;if((rb|0)!=(ob|0)){continue}break}}ob=1;qb=qb+1|0;if((sb|0)!=(qb|0)){continue}break}}a=q[pb>>2];if(!a){break b}q[pb+4>>2]=a;An(a)}T=pb+16|0;return ob}bn();F()}function Ha(a,mb){var nb=0,wb=0,xb=0,yb=0,zb=0,Ab=0;a:{wb=q[a+8>>2];xb=a+4|0;nb=q[xb>>2];b:{if(wb-nb>>>0>=mb>>>0){while(1){o[nb|0]=0;nb=q[xb>>2]+1|0;q[xb>>2]=nb;mb=mb+ -1|0;if(mb){continue}break b}}yb=q[a>>2];zb=nb-yb|0;nb=zb+mb|0;if((nb|0)<=-1){break a}xb=0;wb=wb-yb|0;Ab=wb<<1;wb=wb>>>0<1073741823?Ab>>>0>>0?nb:Ab:2147483647;if(wb){xb=Mm(wb)}nb=xb+zb|0;Dn(nb,0,mb);wb=wb+xb|0;while(1){nb=nb+1|0;mb=mb+ -1|0;if(mb){continue}break}if((zb|0)>=1){Cn(xb,yb,zb)}q[a>>2]=xb;q[a+8>>2]=wb;q[a+4>>2]=nb;if(!yb){break b}An(yb)}return}bn();F()}function Ia(a,mb,Bb,Cb){var Db=0,Eb=0,Fb=0,Gb=0,Hb=x(0),Ib=0;a:{b:{if(!Cb){break b}Db=q[a+28>>2]+ -1|0;if(Db>>>0>10){break b}c:{d:{e:{switch(Db-1|0){default:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=r[mb|0];mb=mb+1|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 0:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=r[mb|0];mb=mb+1|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 1:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=r[mb|0];mb=mb+2|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 2:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=r[mb|0];mb=mb+2|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 3:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=q[mb>>2];mb=mb+4|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 4:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=q[mb>>2];mb=mb+4|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 5:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=q[mb>>2];mb=mb+8|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 6:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24>=1){Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){o[Cb+Eb|0]=q[mb>>2];mb=mb+8|0;Eb=Eb+1|0;Db=o[a+24|0];if((Eb|0)<((Db|0)>(Bb|0)?Bb:Db)<<24>>24){continue}break}}if((Db|0)>=(Bb|0)){break b}break a;case 7:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24<1){break c}Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){Db=Cb+Eb|0;Hb=u[mb>>2];f:{if(x(y(Hb))(Bb|0)?Bb:Db)<<24>>24){continue}break}break c;case 8:Fb=1;Db=o[a+24|0];if(((Db|0)>(Bb|0)?Bb:Db)<<24>>24<1){break d}Db=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Db+mb|0;while(1){Db=Cb+Eb|0;Ib=v[mb>>3];g:{if(y(Ib)<2147483648){Gb=~~Ib;break g}Gb=-2147483648}o[Db|0]=Gb;mb=mb+8|0;Eb=Eb+1|0;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b;while(1){o[Cb|0]=0;Cb=q[Jb+4>>2]+1|0;q[Jb+4>>2]=Cb;a=a+ -1|0;if(a){continue}break}}Cb=q[Bb>>2];a=q[Bb+4>>2]-Cb|0;c:{if(Kb>>>0>a>>>0){Ha(Bb,Kb-a|0);break c}if(Kb>>>0>=a>>>0){break c}q[Bb+4>>2]=Cb+Kb}d:{if(!Mb){Cb=1;break d}a=0;Nb=mb+68|0;Ob=(Lb|0)<1;Kb=0;while(1){Cb=Kb;Pb=mb;if(!r[mb+84|0]){Cb=q[q[Nb>>2]+(Kb<<2)>>2]}if(!Ka(Pb,Cb,o[mb+24|0],q[Jb>>2])){Cb=0;break d}Cb=0;if(!Ob){while(1){o[q[Bb>>2]+a|0]=r[q[Jb>>2]+Cb|0];a=a+1|0;Cb=Cb+1|0;if((Lb|0)!=(Cb|0)){continue}break}}Cb=1;Kb=Kb+1|0;if((Mb|0)!=(Kb|0)){continue}break}}a=q[Jb>>2];if(!a){break b}q[Jb+4>>2]=a;An(a)}T=Jb+16|0;return Cb}bn();F()}function Ka(a,mb,Bb,Qb){var Rb=0,Sb=0,Tb=0,Ub=0,Vb=x(0),Wb=0;a:{b:{if(!Qb){break b}Rb=q[a+28>>2]+ -1|0;if(Rb>>>0>10){break b}c:{d:{e:{switch(Rb-1|0){default:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=r[mb|0];mb=mb+1|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 0:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=r[mb|0];mb=mb+1|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 1:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=r[mb|0];mb=mb+2|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 2:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=r[mb|0];mb=mb+2|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 3:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=q[mb>>2];mb=mb+4|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 4:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=q[mb>>2];mb=mb+4|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 5:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=q[mb>>2];mb=mb+8|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 6:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=q[mb>>2];mb=mb+8|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}break a;case 7:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24<1){break c}Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){Rb=Qb+Sb|0;Vb=u[mb>>2];f:{if(Vb=x(0)){Ub=~~Vb>>>0;break f}Ub=0}o[Rb|0]=Ub;mb=mb+4|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}break c;case 8:Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24<1){break d}Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){Rb=Qb+Sb|0;Wb=v[mb>>3];g:{if(Wb<4294967296&Wb>=0){Ub=~~Wb>>>0;break g}Ub=0}o[Rb|0]=Ub;mb=mb+8|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}break d;case 9:break e}}Tb=1;Rb=o[a+24|0];if(((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24>=1){Rb=q[q[a>>2]>>2];mb=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],mb,0)|0;mb=Rb+mb|0;while(1){o[Qb+Sb|0]=r[mb|0];mb=mb+1|0;Sb=Sb+1|0;Rb=o[a+24|0];if((Sb|0)<((Rb|0)>(Bb|0)?Bb:Rb)<<24>>24){continue}break}}if((Rb|0)>=(Bb|0)){break b}Dn(Qb+Rb|0,0,Bb-Rb|0);break b}if((Rb|0)>=(Bb|0)){break b}break a}if((Rb|0)>=(Bb|0)){break b}break a}return Tb}Dn(Qb+Rb|0,0,Bb-Rb|0);return 1}function La(a,mb,Bb){var Qb=0,Xb=0,Yb=0,Zb=0,_b=0,$b=0,ac=0,bc=0,cc=0;Qb=T-16|0;T=Qb;ac=q[a+80>>2];_b=o[mb+24|0];a=w(ac,_b);a:{Xb=q[mb+28>>2];b:{if(!(!r[mb+84|0]|((Xb|0)!=4?(Xb|0)!=3:0))){$b=q[mb+48>>2];Xb=q[q[mb>>2]>>2];q[Qb+8>>2]=0;q[Qb>>2]=0;q[Qb+4>>2]=0;mb=0;a=a<<1;if(a){if((a|0)<=-1){break a}Yb=Mm(a);q[Qb>>2]=Yb;Zb=(a>>1<<1)+Yb|0;q[Qb+8>>2]=Zb;mb=Cn(Yb,Xb+$b|0,a)+a|0;q[Qb+4>>2]=mb}a=q[Bb>>2];if(a){q[Bb+4>>2]=a;An(a);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c=Mm(Bb<<1);mb=gc}Dn(hc+mb|0,0,o<<1);o=mb+(ec<<1)|0;ec=mb+(Bb<<1)|0;if((fc|0)>=1){Cn(gc,dc,fc)}q[a>>2]=mb;q[a+8>>2]=ec;q[a+4>>2]=o;if(dc){An(dc)}return}bn();F()}ab(1040);F()}function Na(a,kc,lc,mc){var nc=0,oc=0,pc=0,qc=0,rc=x(0),sc=0;a:{b:{if(!mc){break b}nc=q[a+28>>2]+ -1|0;if(nc>>>0>10){break b}c:{d:{e:{switch(nc-1|0){default:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=o[kc|0];kc=kc+1|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 0:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=r[kc|0];kc=kc+1|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 1:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=s[kc>>1];kc=kc+2|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 2:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=s[kc>>1];kc=kc+2|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 3:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=q[kc>>2];kc=kc+4|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 4:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=q[kc>>2];kc=kc+4|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 5:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=q[kc>>2];kc=kc+8|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 6:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=q[kc>>2];kc=kc+8|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}break a;case 7:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24<1){break c}nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){nc=(oc<<1)+mc|0;rc=u[kc>>2];f:{if(x(y(rc))>1]=qc;kc=kc+4|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}break c;case 8:pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24<1){break d}nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){nc=(oc<<1)+mc|0;sc=v[kc>>3];g:{if(y(sc)<2147483648){qc=~~sc;break g}qc=-2147483648}p[nc>>1]=qc;kc=kc+8|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}break d;case 9:break e}}pc=1;nc=o[a+24|0];if(((nc|0)>(lc|0)?lc:nc)<<24>>24>=1){nc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=nc+kc|0;while(1){p[(oc<<1)+mc>>1]=r[kc|0];kc=kc+1|0;oc=oc+1|0;nc=o[a+24|0];if((oc|0)<((nc|0)>(lc|0)?lc:nc)<<24>>24){continue}break}}if((nc|0)>=(lc|0)){break b}Dn((nc<<1)+mc|0,0,lc-nc<<1);break b}if((nc|0)>=(lc|0)){break b}break a}if((nc|0)>=(lc|0)){break b}break a}return pc}Dn((nc<<1)+mc|0,0,lc-nc<<1);return 1}function Oa(a,kc,lc){var mc=0,tc=0,uc=0,vc=0,wc=0,xc=0,yc=0,zc=0,Ac=0;mc=T-16|0;T=mc;yc=q[a+80>>2];wc=o[kc+24|0];a=w(yc,wc);a:{tc=q[kc+28>>2];b:{if(!(!r[kc+84|0]|((tc|0)!=4?(tc|0)!=3:0))){xc=q[kc+48>>2];tc=q[q[kc>>2]>>2];q[mc+8>>2]=0;q[mc>>2]=0;q[mc+4>>2]=0;kc=0;a=a<<1;if(a){if((a|0)<=-1){break a}uc=Mm(a);q[mc>>2]=uc;vc=(a>>1<<1)+uc|0;q[mc+8>>2]=vc;kc=Cn(uc,tc+xc|0,a)+a|0;q[mc+4>>2]=kc}a=q[lc>>2];if(a){q[lc+4>>2]=a;An(a);q[lc+8>>2]=0;q[lc>>2]=0;q[lc+4>>2]=0}q[lc>>2]=uc;q[lc+8>>2]=vc;q[lc+4>>2]=kc;a=1;break b}q[mc+8>>2]=0;q[mc>>2]=0;q[mc+4>>2]=0;if(wc){if((wc|0)<=-1){break a}tc=wc<<1;uc=Mm(tc);q[mc>>2]=uc;vc=tc+uc|0;q[mc+8>>2]=vc;Dn(uc,0,tc);q[mc+4>>2]=vc}uc=q[lc>>2];tc=q[lc+4>>2]-uc>>1;c:{if(a>>>0>tc>>>0){Ma(lc,a-tc|0);break c}if(a>>>0>=tc>>>0){break c}q[lc+4>>2]=uc+(a<<1)}d:{if(!yc){a=1;break d}uc=0;vc=kc+68|0;zc=(wc|0)<1;while(1){a=xc;tc=kc;if(!r[kc+84|0]){a=q[q[vc>>2]+(xc<<2)>>2]}if(!Pa(tc,a,o[kc+24|0],q[mc>>2])){a=0;break d}if(!zc){tc=q[lc>>2];a=0;Ac=q[mc>>2];while(1){p[tc+(uc<<1)>>1]=s[Ac+(a<<1)>>1];uc=uc+1|0;a=a+1|0;if((wc|0)!=(a|0)){continue}break}}a=1;xc=xc+1|0;if((yc|0)!=(xc|0)){continue}break}}kc=q[mc>>2];if(!kc){break b}q[mc+4>>2]=kc;An(kc)}T=mc+16|0;return a}bn();F()}function Pa(a,kc,lc,Bc){var Cc=0,Dc=0,Ec=0,Fc=0,Gc=x(0),Hc=0;a:{b:{if(!Bc){break b}Cc=q[a+28>>2]+ -1|0;if(Cc>>>0>10){break b}c:{d:{e:{switch(Cc-1|0){default:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=o[kc|0];kc=kc+1|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 0:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=r[kc|0];kc=kc+1|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 1:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=s[kc>>1];kc=kc+2|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 2:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=s[kc>>1];kc=kc+2|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 3:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=q[kc>>2];kc=kc+4|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 4:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=q[kc>>2];kc=kc+4|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 5:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=q[kc>>2];kc=kc+8|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 6:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=q[kc>>2];kc=kc+8|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}}if((Cc|0)>=(lc|0)){break b}break a;case 7:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24<1){break c}Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){Cc=(Dc<<1)+Bc|0;Gc=u[kc>>2];f:{if(Gc=x(0)){Fc=~~Gc>>>0;break f}Fc=0}p[Cc>>1]=Fc;kc=kc+4|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}break c;case 8:Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24<1){break d}Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){Cc=(Dc<<1)+Bc|0;Hc=v[kc>>3];g:{if(Hc<4294967296&Hc>=0){Fc=~~Hc>>>0;break g}Fc=0}p[Cc>>1]=Fc;kc=kc+8|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<24>>24){continue}break}break d;case 9:break e}}Ec=1;Cc=o[a+24|0];if(((Cc|0)>(lc|0)?lc:Cc)<<24>>24>=1){Cc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Cc+kc|0;while(1){p[(Dc<<1)+Bc>>1]=r[kc|0];kc=kc+1|0;Dc=Dc+1|0;Cc=o[a+24|0];if((Dc|0)<((Cc|0)>(lc|0)?lc:Cc)<<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Mc;Jc=kc;if(!r[kc+84|0]){a=q[q[Lc>>2]+(Mc<<2)>>2]}if(!Ra(Jc,a,o[kc+24|0],q[Bc>>2])){a=0;break e}if(!Oc){Jc=q[lc>>2];a=0;Pc=q[Bc>>2];while(1){q[Jc+(Ic<<2)>>2]=q[Pc+(a<<2)>>2];Ic=Ic+1|0;a=a+1|0;if((Kc|0)!=(a|0)){continue}break}}a=1;Mc=Mc+1|0;if((Nc|0)!=(Mc|0)){continue}break}}kc=q[Bc>>2];if(!kc){break b}q[Bc+4>>2]=kc;An(kc)}T=Bc+16|0;return a}bn();F()}function Ra(a,kc,lc,Qc){var Rc=0,Sc=0,Tc=0,Uc=0,Vc=x(0),Wc=0;a:{b:{if(!Qc){break b}Rc=q[a+28>>2]+ -1|0;if(Rc>>>0>10){break b}c:{d:{e:{switch(Rc-1|0){default:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=o[kc|0];kc=kc+1|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 0:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=r[kc|0];kc=kc+1|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 1:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=p[kc>>1];kc=kc+2|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 2:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=s[kc>>1];kc=kc+2|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 3:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=q[kc>>2];kc=kc+4|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 4:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=q[kc>>2];kc=kc+4|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 5:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=q[kc>>2];kc=kc+8|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 6:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=q[kc>>2];kc=kc+8|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}break a;case 7:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24<1){break c}Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){Rc=(Sc<<2)+Qc|0;Vc=u[kc>>2];f:{if(x(y(Vc))>2]=Uc;kc=kc+4|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}break c;case 8:Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24<1){break d}Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){Rc=(Sc<<2)+Qc|0;Wc=v[kc>>3];g:{if(y(Wc)<2147483648){Uc=~~Wc;break g}Uc=-2147483648}q[Rc>>2]=Uc;kc=kc+8|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}break d;case 9:break e}}Tc=1;Rc=o[a+24|0];if(((Rc|0)>(lc|0)?lc:Rc)<<24>>24>=1){Rc=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=Rc+kc|0;while(1){q[(Sc<<2)+Qc>>2]=r[kc|0];kc=kc+1|0;Sc=Sc+1|0;Rc=o[a+24|0];if((Sc|0)<((Rc|0)>(lc|0)?lc:Rc)<<24>>24){continue}break}}if((Rc|0)>=(lc|0)){break b}Dn((Rc<<2)+Qc|0,0,lc-Rc<<2);break b}if((Rc|0)>=(lc|0)){break b}break a}if((Rc|0)>=(lc|0)){break b}break a}return Tc}Dn((Rc<<2)+Qc|0,0,lc-Rc<<2);return 1}function Sa(a,kc,lc){var Qc=0,Xc=0,Yc=0,Zc=0,_c=0,$c=0,ad=0,bd=0,cd=0;Qc=T-16|0;T=Qc;ad=q[a+80>>2];Zc=o[kc+24|0];Yc=w(ad,Zc);a:{a=q[kc+28>>2];b:{if(!(!r[kc+84|0]|((a|0)!=6?(a|0)!=5:0))){$c=q[kc+48>>2];Zc=q[q[kc>>2]>>2];q[Qc+8>>2]=0;q[Qc>>2]=0;q[Qc+4>>2]=0;a=0;kc=Yc<<2;c:{if(!kc){break c}a=kc>>2;if(a>>>0>=1073741824){break a}Xc=Mm(kc);q[Qc>>2]=Xc;q[Qc+4>>2]=Xc;_c=(a<<2)+Xc|0;q[Qc+8>>2]=_c;if((kc|0)<1){a=Xc;break c}a=Cn(Xc,Zc+$c|0,kc)+kc|0;q[Qc+4>>2]=a}kc=q[lc>>2];if(kc){q[lc+4>>2]=kc;An(kc);q[lc+8>>2]=0;q[lc>>2]=0;q[lc+4>>2]=0}q[lc>>2]=Xc;q[lc+8>>2]=_c;q[lc+4>>2]=a;a=1;break b}q[Qc+8>>2]=0;q[Qc>>2]=0;q[Qc+4>>2]=0;if(Zc){if((Zc|0)<=-1){break a}a=Zc<<2;Xc=Mm(a);q[Qc>>2]=Xc;_c=a+Xc|0;q[Qc+8>>2]=_c;Dn(Xc,0,a);q[Qc+4>>2]=_c}Xc=q[lc>>2];a=q[lc+4>>2]-Xc>>2;d:{if(Yc>>>0>a>>>0){Fa(lc,Yc-a|0);break d}if(Yc>>>0>=a>>>0){break d}q[lc+4>>2]=Xc+(Yc<<2)}e:{if(!ad){a=1;break e}Xc=0;_c=kc+68|0;bd=(Zc|0)<1;while(1){a=$c;Yc=kc;if(!r[kc+84|0]){a=q[q[_c>>2]+($c<<2)>>2]}if(!Ta(Yc,a,o[kc+24|0],q[Qc>>2])){a=0;break e}if(!bd){Yc=q[lc>>2];a=0;cd=q[Qc>>2];while(1){q[Yc+(Xc<<2)>>2]=q[cd+(a<<2)>>2];Xc=Xc+1|0;a=a+1|0;if((Zc|0)!=(a|0)){continue}break}}a=1;$c=$c+1|0;if((ad|0)!=($c|0)){continue}break}}kc=q[Qc>>2];if(!kc){break b}q[Qc+4>>2]=kc;An(kc)}T=Qc+16|0;return a}bn();F()}function Ta(a,kc,lc,dd){var ed=0,fd=0,gd=0,hd=0,id=x(0),jd=0;a:{b:{if(!dd){break b}ed=q[a+28>>2]+ -1|0;if(ed>>>0>10){break b}c:{d:{e:{switch(ed-1|0){default:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=o[kc|0];kc=kc+1|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 0:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=r[kc|0];kc=kc+1|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 1:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=p[kc>>1];kc=kc+2|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 2:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=s[kc>>1];kc=kc+2|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 3:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=q[kc>>2];kc=kc+4|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 4:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=q[kc>>2];kc=kc+4|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 5:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=q[kc>>2];kc=kc+8|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 6:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=q[kc>>2];kc=kc+8|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}break a;case 7:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24<1){break c}ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){ed=(fd<<2)+dd|0;id=u[kc>>2];f:{if(id=x(0)){hd=~~id>>>0;break f}hd=0}q[ed>>2]=hd;kc=kc+4|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}break c;case 8:gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24<1){break d}ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){ed=(fd<<2)+dd|0;jd=v[kc>>3];g:{if(jd<4294967296&jd>=0){hd=~~jd>>>0;break g}hd=0}q[ed>>2]=hd;kc=kc+8|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}break d;case 9:break e}}gd=1;ed=o[a+24|0];if(((ed|0)>(lc|0)?lc:ed)<<24>>24>=1){ed=q[q[a>>2]>>2];kc=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],kc,0)|0;kc=ed+kc|0;while(1){q[(fd<<2)+dd>>2]=r[kc|0];kc=kc+1|0;fd=fd+1|0;ed=o[a+24|0];if((fd|0)<((ed|0)>(lc|0)?lc:ed)<<24>>24){continue}break}}if((ed|0)>=(lc|0)){break b}Dn((ed<<2)+dd|0,0,lc-ed<<2);break b}if((ed|0)>=(lc|0)){break b}break a}if((ed|0)>=(lc|0)){break b}break a}return gd}Dn((ed<<2)+dd|0,0,lc-ed<<2);return 1}function Ua(a,kc,lc,dd,kd){var ld=0,md=0,nd=0,od=0,pd=0,qd=0,rd=0;md=T-16|0;T=md;lc=lc+ -1|0;a:{if(lc>>>0>8){break a}b:{switch(lc-1|0){default:ld=Va(a,kc,dd,kd);break a;case 1:ld=Wa(a,kc,dd,kd);break a;case 3:ld=Xa(a,kc,dd,kd);break a;case 0:ld=Ya(a,kc,dd,kd);break a;case 2:ld=Za(a,kc,dd,kd);break a;case 4:ld=_a(a,kc,dd,kd);break a;case 5:case 6:break a;case 7:break b}}nd=q[a+80>>2];od=o[kc+24|0];pd=od<<2;if((w(nd,pd)|0)!=(dd|0)){break a}a=0;lc=q[259];q[md+8>>2]=q[258];q[md+12>>2]=lc;lc=q[257];q[md>>2]=q[256];q[md+4>>2]=lc;if(!nd){ld=1;break a}qd=kc+68|0;rd=(od|0)<1;lc=0;while(1){dd=lc;ld=kc;if(!r[kc+84|0]){dd=q[q[qd>>2]+(lc<<2)>>2]}if(!Da(ld,dd,o[kc+24|0],md)){ld=0;break a}if(!rd){Cn((a<<2)+kd|0,md,pd);a=a+od|0}ld=1;lc=lc+1|0;if((nd|0)!=(lc|0)){continue}break}}T=md+16|0;return ld}function Va(a,kc,lc,dd){var kd=0,sd=0,td=0,ud=0,vd=0,wd=0,xd=0;sd=T-16|0;T=sd;a:{vd=q[a+80>>2];td=o[kc+24|0];b:{if((w(vd,td)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=1)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);kd=1;break b}q[sd+8>>2]=0;q[sd>>2]=0;q[sd+4>>2]=0;if(td){if((td|0)<=-1){break a}kd=Mm(td);q[sd>>2]=kd;q[sd+4>>2]=kd;q[sd+8>>2]=kd+td;lc=td;while(1){o[kd|0]=0;kd=q[sd+4>>2]+1|0;q[sd+4>>2]=kd;lc=lc+ -1|0;if(lc){continue}break}}c:{if(!vd){kd=1;break c}lc=0;wd=kc+68|0;xd=(td|0)<1;while(1){a=ud;kd=kc;if(!r[kd+84|0]){a=q[q[wd>>2]+(ud<<2)>>2]}if(!Ia(kd,a,o[kc+24|0],q[sd>>2])){kd=0;break c}if(!xd){kd=0;a=q[sd>>2];while(1){o[lc+dd|0]=r[a+kd|0];lc=lc+1|0;kd=kd+1|0;if((td|0)!=(kd|0)){continue}break}}kd=1;ud=ud+1|0;if((vd|0)!=(ud|0)){continue}break}}a=q[sd>>2];if(!a){break b}q[sd+4>>2]=a;An(a)}T=sd+16|0;return kd}bn();F()}function Wa(a,kc,lc,dd){var yd=0,zd=0,Ad=0,Bd=0,Cd=0,Dd=0,Ed=0,Fd=0,Gd=0;yd=T-16|0;T=yd;a:{Cd=q[a+80>>2];Ad=o[kc+24|0];a=Ad<<1;b:{if((w(Cd,a)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=3)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);zd=1;break b}lc=0;q[yd+8>>2]=0;q[yd>>2]=0;q[yd+4>>2]=0;if(Ad){if((Ad|0)<=-1){break a}lc=Mm(a);q[yd>>2]=lc;q[yd+8>>2]=(Ad<<1)+lc;Fd=yd,Gd=Dn(lc,0,a)+a|0,q[Fd+4>>2]=Gd}c:{if(!Cd){zd=1;break c}lc=0;Dd=kc+68|0;Ed=(Ad|0)<1;while(1){a=Bd;zd=kc;if(!r[kc+84|0]){a=q[q[Dd>>2]+(Bd<<2)>>2]}d:{if(!Na(zd,a,o[kc+24|0],q[yd>>2])){zd=0;break d}if(!Ed){zd=0;a=q[yd>>2];while(1){p[(lc<<1)+dd>>1]=s[a+(zd<<1)>>1];lc=lc+1|0;zd=zd+1|0;if((Ad|0)!=(zd|0)){continue}break}}zd=1;Bd=Bd+1|0;if((Cd|0)!=(Bd|0)){continue}}break}lc=q[yd>>2]}if(!lc){break b}q[yd+4>>2]=lc;An(lc)}T=yd+16|0;return zd}bn();F()}function Xa(a,kc,lc,dd){var Hd=0,Id=0,Jd=0,Kd=0,Ld=0,Md=0,Nd=0,Od=0,Pd=0;Hd=T-16|0;T=Hd;a:{Ld=q[a+80>>2];Jd=o[kc+24|0];a=Jd<<2;b:{if((w(Ld,a)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=5)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);Id=1;break b}lc=0;q[Hd+8>>2]=0;q[Hd>>2]=0;q[Hd+4>>2]=0;if(Jd){if((Jd|0)<=-1){break a}lc=Mm(a);q[Hd>>2]=lc;q[Hd+8>>2]=(Jd<<2)+lc;Od=Hd,Pd=Dn(lc,0,a)+a|0,q[Od+4>>2]=Pd}c:{if(!Ld){Id=1;break c}lc=0;Md=kc+68|0;Nd=(Jd|0)<1;while(1){a=Kd;Id=kc;if(!r[kc+84|0]){a=q[q[Md>>2]+(Kd<<2)>>2]}d:{if(!Ra(Id,a,o[kc+24|0],q[Hd>>2])){Id=0;break d}if(!Nd){Id=0;a=q[Hd>>2];while(1){q[(lc<<2)+dd>>2]=q[a+(Id<<2)>>2];lc=lc+1|0;Id=Id+1|0;if((Jd|0)!=(Id|0)){continue}break}}Id=1;Kd=Kd+1|0;if((Ld|0)!=(Kd|0)){continue}}break}lc=q[Hd>>2]}if(!lc){break b}q[Hd+4>>2]=lc;An(lc)}T=Hd+16|0;return Id}bn();F()}function Ya(a,kc,lc,dd){var Qd=0,Rd=0,Sd=0,Td=0,Ud=0,Vd=0,Wd=0;Rd=T-16|0;T=Rd;a:{Ud=q[a+80>>2];Sd=o[kc+24|0];b:{if((w(Ud,Sd)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=2)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);Qd=1;break b}q[Rd+8>>2]=0;q[Rd>>2]=0;q[Rd+4>>2]=0;if(Sd){if((Sd|0)<=-1){break a}Qd=Mm(Sd);q[Rd>>2]=Qd;q[Rd+4>>2]=Qd;q[Rd+8>>2]=Qd+Sd;lc=Sd;while(1){o[Qd|0]=0;Qd=q[Rd+4>>2]+1|0;q[Rd+4>>2]=Qd;lc=lc+ -1|0;if(lc){continue}break}}c:{if(!Ud){Qd=1;break c}lc=0;Vd=kc+68|0;Wd=(Sd|0)<1;while(1){a=Td;Qd=kc;if(!r[Qd+84|0]){a=q[q[Vd>>2]+(Td<<2)>>2]}if(!Ka(Qd,a,o[kc+24|0],q[Rd>>2])){Qd=0;break c}if(!Wd){Qd=0;a=q[Rd>>2];while(1){o[lc+dd|0]=r[a+Qd|0];lc=lc+1|0;Qd=Qd+1|0;if((Sd|0)!=(Qd|0)){continue}break}}Qd=1;Td=Td+1|0;if((Ud|0)!=(Td|0)){continue}break}}a=q[Rd>>2];if(!a){break b}q[Rd+4>>2]=a;An(a)}T=Rd+16|0;return Qd}bn();F()}function Za(a,kc,lc,dd){var Xd=0,Yd=0,Zd=0,_d=0,$d=0,ae=0,be=0,ce=0,de=0;Xd=T-16|0;T=Xd;a:{$d=q[a+80>>2];Zd=o[kc+24|0];a=Zd<<1;b:{if((w($d,a)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=4)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);Yd=1;break b}lc=0;q[Xd+8>>2]=0;q[Xd>>2]=0;q[Xd+4>>2]=0;if(Zd){if((Zd|0)<=-1){break a}lc=Mm(a);q[Xd>>2]=lc;q[Xd+8>>2]=(Zd<<1)+lc;ce=Xd,de=Dn(lc,0,a)+a|0,q[ce+4>>2]=de}c:{if(!$d){Yd=1;break c}lc=0;ae=kc+68|0;be=(Zd|0)<1;while(1){a=_d;Yd=kc;if(!r[kc+84|0]){a=q[q[ae>>2]+(_d<<2)>>2]}d:{if(!Pa(Yd,a,o[kc+24|0],q[Xd>>2])){Yd=0;break d}if(!be){Yd=0;a=q[Xd>>2];while(1){p[(lc<<1)+dd>>1]=s[a+(Yd<<1)>>1];lc=lc+1|0;Yd=Yd+1|0;if((Zd|0)!=(Yd|0)){continue}break}}Yd=1;_d=_d+1|0;if(($d|0)!=(_d|0)){continue}}break}lc=q[Xd>>2]}if(!lc){break b}q[Xd+4>>2]=lc;An(lc)}T=Xd+16|0;return Yd}bn();F()}function _a(a,kc,lc,dd){var ee=0,fe=0,ge=0,he=0,ie=0,je=0,ke=0,le=0,me=0;ee=T-16|0;T=ee;a:{ie=q[a+80>>2];ge=o[kc+24|0];a=ge<<2;b:{if((w(ie,a)|0)!=(lc|0)){break b}if(!(!r[kc+84|0]|q[kc+28>>2]!=6)){Cn(dd,q[q[kc>>2]>>2]+q[kc+48>>2]|0,lc);fe=1;break b}lc=0;q[ee+8>>2]=0;q[ee>>2]=0;q[ee+4>>2]=0;if(ge){if((ge|0)<=-1){break a}lc=Mm(a);q[ee>>2]=lc;q[ee+8>>2]=(ge<<2)+lc;le=ee,me=Dn(lc,0,a)+a|0,q[le+4>>2]=me}c:{if(!ie){fe=1;break c}lc=0;je=kc+68|0;ke=(ge|0)<1;while(1){a=he;fe=kc;if(!r[kc+84|0]){a=q[q[je>>2]+(he<<2)>>2]}d:{if(!Ta(fe,a,o[kc+24|0],q[ee>>2])){fe=0;break d}if(!ke){fe=0;a=q[ee>>2];while(1){q[(lc<<2)+dd>>2]=q[a+(fe<<2)>>2];lc=lc+1|0;fe=fe+1|0;if((ge|0)!=(fe|0)){continue}break}}fe=1;he=he+1|0;if((ie|0)!=(he|0)){continue}}break}lc=q[ee>>2]}if(!lc){break b}q[ee+4>>2]=lc;An(lc)}T=ee+16|0;return fe}bn();F()}function $a(a,o){var kc=0,lc=0;kc=q[a+4>>2];if(!kc){return 0}o=q[q[q[a+8>>2]+(o<<2)>>2]+60>>2];if((o|0)<0){return 0}a=q[kc+24>>2];kc=q[kc+28>>2];if((a|0)==(kc|0)){return 0}a:{while(1){lc=q[a>>2];if((o|0)==q[lc+24>>2]){break a}a=a+4|0;if((kc|0)!=(a|0)){continue}break}return 0}return lc}function ab(a){var o=0;o=I(8)|0;q[o>>2]=15856;q[o>>2]=15900;Nm(o+4|0,a);q[o>>2]=15948;J(o|0,15980,1);F()}function bb(a,dd,ne){var oe=0,pe=0,qe=0,re=0,se=0;pe=T-16|0;T=pe;q[a+4>>2]=0;a:{b:{if(!dd){break b}qe=q[a+8>>2];oe=qe<<5;c:{if(oe>>>0>=dd>>>0){q[a+4>>2]=dd;break c}q[pe+8>>2]=0;q[pe>>2]=0;q[pe+4>>2]=0;if((dd|0)<=-1){break a}se=pe;if(oe>>>0<=1073741822){re=dd+31&-32;oe=qe<<6;re=oe>>>0>>0?re:oe}else{re=2147483647}cb(se,re);re=q[a>>2];q[a>>2]=q[pe>>2];q[pe>>2]=re;qe=q[a+4>>2];q[a+4>>2]=dd;q[pe+4>>2]=qe;oe=a+8|0;qe=q[oe>>2];q[oe>>2]=q[pe+8>>2];q[pe+8>>2]=qe;if(!re){break c}An(re)}oe=dd>>>5;qe=oe<<2;a=q[a>>2];if(r[ne|0]){a=Dn(a,255,qe);dd=dd&31;if(!dd){break b}a=a+(oe<<2)|0;q[a>>2]=q[a>>2]|-1>>>32-dd;break b}a=Dn(a,0,qe);dd=dd&31;if(!dd){break b}a=a+(oe<<2)|0;q[a>>2]=q[a>>2]&(-1>>>32-dd^-1)}T=pe+16|0;return}bn();F()}function cb(a,dd){var ne=0,te=0;ne=T-32|0;T=ne;a:{b:{if(q[a+8>>2]<<5>>>0>=dd>>>0){break b}q[ne+24>>2]=0;q[ne+16>>2]=0;q[ne+20>>2]=0;if((dd|0)<=-1){break a}dd=(dd+ -1>>>5)+1|0;te=Mm(dd<<2);q[ne+24>>2]=dd;q[ne+20>>2]=0;q[ne+16>>2]=te;dd=q[a>>2];q[ne+12>>2]=0;q[ne+8>>2]=dd;te=q[a+4>>2];q[ne+4>>2]=te&31;q[ne>>2]=dd+(te>>>3&536870908);db(ne+16|0,ne+8|0,ne);dd=q[a>>2];q[a>>2]=q[ne+16>>2];q[ne+16>>2]=dd;te=q[a+4>>2];q[a+4>>2]=q[ne+20>>2];q[ne+20>>2]=te;a=a+8|0;te=q[a>>2];q[a>>2]=q[ne+24>>2];q[ne+24>>2]=te;if(!dd){break b}An(dd)}T=ne+32|0;return}bn();F()}function db(a,dd,ue){var ve=0,we=0,xe=0,ye=0,ze=0,Ae=0;xe=T-32|0;T=xe;ze=q[ue+4>>2];ve=q[dd+4>>2];Ae=q[ue>>2];ye=q[dd>>2];dd=(ze-ve|0)+(Ae-ye<<3)|0;ue=q[a+4>>2];we=dd+ue|0;q[a+4>>2]=we;a:{if(!(!ue|(we+ -1^ue+ -1)>>>0>31)){a=q[a>>2];break a}a=q[a>>2];if(we>>>0<=32){q[a>>2]=0;break a}q[(we+ -1>>>3&536870908)+a>>2]=0}a=(ue>>>3&536870908)+a|0;ue=ue&31;b:{if((ue|0)==(ve|0)){c:{if((dd|0)<1){break c}d:{if(!ve){ue=0;break d}we=32-ve|0;ue=(dd|0)<(we|0)?dd:we;we=-1<>>we-ue;q[a>>2]=q[a>>2]&(we^-1)|we&q[ye>>2];dd=dd-ue|0;ve=ue+ve|0;ue=ve&31;a=(ve>>>3&536870908)+a|0;ye=ye+4|0}ve=(dd|0)/32|0;we=ve<<2;a=En(a,ye,we)+we|0;ve=dd-(ve<<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ge&-1>>>Fe-Ee^-1);Fe=q[De>>2]&-1>>>32-Ce;q[dd>>2]=Ge|Fe<>2]=ue;De=dd+(De>>>3&536870908)|0;q[Be>>2]=De;dd=Ce-Ee|0;if((dd|0)<1){break a}q[De>>2]=q[De>>2]&(-1>>>32-dd^-1)|Fe>>>Ee;q[Be+4>>2]=dd;ue=dd}dd=q[Be>>2];q[a+4>>2]=ue;q[a>>2]=dd}function fb(a){a=a|0;return q[a>>2]}function gb(a){a=a|0;return!q[a>>2]|0}function hb(a){a=a|0;var dd=0;dd=a+4|0;if(o[a+15|0]<=-1){dd=q[dd>>2]}return dd|0}function ib(a){a=a|0;if(a){if(o[a+15|0]<=-1){An(q[a+4>>2])}An(a)}}function jb(){var a=0;a=Mm(12);q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;return a|0}function kb(ue,Be){ue=ue|0;Be=Be|0;return s[q[ue>>2]+(Be<<1)>>1]}function lb(ue){ue=ue|0;return q[ue+4>>2]-q[ue>>2]>>1}function mb(ue){ue=ue|0;var Be=0;if(ue){Be=q[ue>>2];if(Be){q[ue+4>>2]=Be;An(Be)}An(ue)}}function nb(){return al(Mm(84))|0}function ob(ue){ue=ue|0;return q[ue+12>>2]-q[ue+8>>2]>>2}function pb(ue){ue=ue|0;return q[ue+80>>2]}function qb(ue){ue=ue|0;if(ue){n[q[q[ue>>2]+4>>2]](ue)}}function rb(ue,Ke){ue=ue|0;Ke=Ke|0;return r[q[ue>>2]+Ke|0]}function sb(ue){ue=ue|0;return q[ue+4>>2]-q[ue>>2]|0}function tb(ue,Ke){ue=ue|0;Ke=Ke|0;return q[q[ue>>2]+(Ke<<2)>>2]}function ub(ue){ue=ue|0;return q[ue+4>>2]-q[ue>>2]>>2}function vb(){var ue=0;ue=Mm(8);q[ue+4>>2]=-1;q[ue>>2]=1116;return ue|0}function wb(Ke,Le){Ke=Ke|0;Le=Le|0;return n[q[q[Ke>>2]+12>>2]](Ke,Le)|0}function xb(Ke){Ke=Ke|0;return q[Ke+4>>2]}function yb(){return rd(Mm(96))|0}function zb(Ke){Ke=Ke|0;return q[Ke+88>>2]}function Ab(Ke){Ke=Ke|0;return q[Ke+56>>2]}function Bb(Ke){Ke=Ke|0;return q[Ke+28>>2]}function Cb(q){q=q|0;return o[q+24|0]}function Db(q){q=q|0;return r[q+32|0]}function Eb(Ke){Ke=Ke|0;return q[Ke+40>>2]}function Fb(Ke){Ke=Ke|0;return q[Ke+48>>2]}function Gb(Ke){Ke=Ke|0;return q[Ke+60>>2]}function Hb(Ke){Ke=Ke|0;var Le=0,Me=0;if(Ke){Le=Ke+88|0;Me=q[Le>>2];q[Le>>2]=0;if(Me){Le=q[Me+8>>2];if(Le){q[Me+12>>2]=Le;An(Le)}An(Me)}Me=q[Ke+68>>2];if(Me){q[Ke+72>>2]=Me;An(Me)}Le=Ke- -64|0;Me=q[Le>>2];q[Le>>2]=0;if(Me){Le=q[Me>>2];if(Le){q[Me+4>>2]=Le;An(Le)}An(Me)}An(Ke)}}function Ib(){var Ke=0;Ke=Mm(40);q[Ke>>2]=-1;Uj(Ke+8|0);return Ke|0}function Jb(Ne){Ne=Ne|0;var Oe=0;if(Ne){Oe=q[Ne+8>>2];if(Oe){q[Ne+12>>2]=Oe;An(Oe)}An(Ne)}}function Kb(){var Ne=0;Ne=Mm(24);q[Ne+4>>2]=-1;q[Ne>>2]=1232;q[Ne+8>>2]=0;q[Ne+12>>2]=0;q[Ne+16>>2]=0;q[Ne+20>>2]=0;return Ne|0}function Lb(Pe,Qe){Pe=Pe|0;Qe=Qe|0;return x(u[q[Pe+8>>2]+(Qe<<2)>>2])}function Mb(q){q=q|0;return x(u[q+20>>2])}function Nb(Pe,Qe){Pe=Pe|0;Qe=Qe|0;return o[q[Pe>>2]+Qe|0]}function Ob(){var Pe=0;Pe=Mm(28);q[Pe>>2]=0;q[Pe+4>>2]=0;q[Pe+24>>2]=0;q[Pe+16>>2]=0;q[Pe+20>>2]=0;q[Pe+8>>2]=0;q[Pe+12>>2]=0;return Pe|0}function Pb(q,Qe,Re){q=q|0;Qe=Qe|0;Re=Re|0;return fa(Qe,Re)|0}function Qb(q,Qe,Re){q=q|0;Qe=Qe|0;Re=Re|0;return ha(Qe,Re)|0}function Rb(q,Qe,Re,Se){q=q|0;Qe=Qe|0;Re=Re|0;Se=Se|0;ia(Qe,Re,Se)}function Sb(q,Qe,Re){q=q|0;Qe=Qe|0;Re=Re|0;return+ja(Qe,Re)}function Tb(q,Qe,Re){q=q|0;Qe=Qe|0;Re=Re|0;return ka(q,Qe,Re)|0}function Ub(Qe,Re){Qe=Qe|0;Re=Re|0;return q[Re+8>>2]}function Vb(q,Qe,Re){q=q|0;Qe=Qe|0;Re=Re|0;return la(q,Qe,Re)|0}function Wb(Qe){Qe=Qe|0;var Re=0,Se=0,Te=0,Ue=0,Ve=0;if(Qe){if(o[Qe+27|0]<=-1){An(q[Qe+16>>2])}Se=q[Qe>>2];if(Se){Re=Se;Ve=Qe+4|0;Te=q[Ve>>2];Ue=Re;a:{if((Te|0)==(Re|0)){break a}while(1){Re=Te+ -12|0;if(o[Te+ -1|0]<=-1){An(q[Re>>2])}Te=Re;if((Re|0)!=(Se|0)){continue}break}Ue=q[Qe>>2]}Re=Ue;q[Ve>>2]=Se;An(Re)}An(Qe)}}function Xb(Qe,We){Qe=Qe|0;We=We|0;return p[q[Qe>>2]+(We<<1)>>1]}function Yb(Qe,We){Qe=Qe|0;We=We|0;return x(u[q[Qe>>2]+(We<<2)>>2])}function Zb(){return nd(Mm(64))|0}function _b(q){q=q|0;if(q){An(q)}}function $b(){return Yj(Mm(40))|0}function ac(Qe,We,Xe){Qe=Qe|0;We=We|0;Xe=Xe|0;q[Qe+16>>2]=0;q[Qe+20>>2]=0;q[Qe>>2]=We;q[Qe+8>>2]=Xe;q[Qe+12>>2]=0}function bc(){return na(Mm(40))|0}function cc(q,Qe){q=q|0;Qe=Qe|0;return oa(Qe)|0}function dc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return pa(q,Qe,We)|0}function ec(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return qa(q,Qe,We)|0}function fc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return bl(Qe,We)|0}function gc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return ra(Qe,We)|0}function hc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return sa(Qe,We,Xe)|0}function ic(Qe,We,Xe){Qe=Qe|0;We=We|0;Xe=Xe|0;return q[q[We+8>>2]+(Xe<<2)>>2]}function jc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return dl(Qe,We)|0}function kc(Qe,We){Qe=Qe|0;We=We|0;return q[We+4>>2]}function lc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return $a(Qe,We)|0}function mc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return ta(Qe,We,Xe)|0}function nc(q,Qe,We){q=q|0;Qe=Qe|0;We=We|0;return ua(Qe,We)|0}function oc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Aa(Qe,We,Xe)|0}function pc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Ba(Qe,We,Xe)|0}function qc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Ca(Qe,We,Xe)|0}function rc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Ea(Qe,We,Xe)|0}function sc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Qa(Qe,We,Xe)|0}function tc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Ga(Qe,We,Xe)|0}function uc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Ja(Qe,We,Xe)|0}function vc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return La(Qe,We,Xe)|0}function wc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Oa(Qe,We,Xe)|0}function xc(q,Qe,We,Xe){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;return Sa(Qe,We,Xe)|0}function yc(q,Qe,We,Xe,Ye,Ze){q=q|0;Qe=Qe|0;We=We|0;Xe=Xe|0;Ye=Ye|0;Ze=Ze|0;return Ua(Qe,We,Xe,Ye,Ze)|0}function zc(q,Qe){q=q|0;Qe=Qe|0;kh(q,Qe)}function Ac(Qe){Qe=Qe|0;if(Qe){if(o[Qe+39|0]<=-1){An(q[Qe+28>>2])}Bc(Qe+12|0,q[Qe+16>>2]);Cc(Qe,q[Qe+4>>2]);An(Qe)}}function Bc(Qe,We){if(We){Bc(Qe,q[We>>2]);Bc(Qe,q[We+4>>2]);Cc(We+20|0,q[We+24>>2]);An(We)}}function Cc(Qe,We){if(We){Cc(Qe,q[We>>2]);Cc(Qe,q[We+4>>2]);if(o[We+39|0]<=-1){An(q[We+28>>2])}if(o[We+27|0]<=-1){An(q[We+16>>2])}An(We)}}function Dc(){return vk(Mm(108))|0}function Ec(Qe){Qe=Qe|0;return(q[Qe+100>>2]-q[Qe+96>>2]|0)/12|0}function Fc(){var Qe=0,We=0,Xe=0;We=Mm(24);Xe=We+4|0;Qe=Xe;q[Qe>>2]=0;q[Qe+4>>2]=0;Qe=We+16|0;q[Qe>>2]=0;q[Qe+4>>2]=0;q[We>>2]=Xe;q[We+12>>2]=Qe;return We|0}function Gc(Ye){Ye=Ye|0;if(Ye){Hc(Ye+12|0,q[Ye+16>>2]);Ic(Ye,q[Ye+4>>2]);An(Ye)}}function Hc(Ye,Ze){var _e=0;if(Ze){Hc(Ye,q[Ze>>2]);Hc(Ye,q[Ze+4>>2]);_e=Ze+28|0;Ye=q[_e>>2];q[_e>>2]=0;if(Ye){Hc(Ye+12|0,q[Ye+16>>2]);Ic(Ye,q[Ye+4>>2]);An(Ye)}if(o[Ze+27|0]<=-1){An(q[Ze+16>>2])}An(Ze)}}function Ic(Ye,Ze){if(Ze){Ic(Ye,q[Ze>>2]);Ic(Ye,q[Ze+4>>2]);Ye=q[Ze+28>>2];if(Ye){q[Ze+32>>2]=Ye;An(Ye)}if(o[Ze+27|0]<=-1){An(q[Ze+16>>2])}An(Ze)}}function Jc(){return 0}function Kc(){return-1}function Lc(){return-2}function Mc(){return-3}function Nc(){return-4}function Oc(){return-5}function Pc(){return 1}function Qc(){return 2}function Rc(){return 3}function Sc(){return 4}function Tc(){return 5}function Uc(){return 6}function Vc(){return 7}function Wc(){return 8}function Xc(){return 9}function Yc(){return 10}function Zc(){return 11}function _c(){return 12}function $c(Ye,Ze){Ye=Ye|0;Ze=Ze|0;var $e=0;Ze=q[Ze+88>>2];if(!(!Ze|q[Ze>>2]!=2)){$e=Ye;Ye=q[Ze+8>>2];q[$e+4>>2]=r[Ye|0]|r[Ye+1|0]<<8|(r[Ye+2|0]<<16|r[Ye+3|0]<<24);$e=1}return $e|0}function ad(Ye,Ze){Ye=Ye|0;Ze=Ze|0;var af=0,bf=0;q[Ze>>2]=2;af=q[Ze+8>>2];bf=q[Ze+12>>2]-af|0;if(bf>>>0<=4294967291){Ze=Ze+8|0;Xj(Ze,bf+4|0);af=q[Ze>>2]}Ze=af+bf|0;Ye=r[Ye+4|0]|r[Ye+5|0]<<8|(r[Ye+6|0]<<16|r[Ye+7|0]<<24);o[Ze|0]=Ye;o[Ze+1|0]=Ye>>>8;o[Ze+2|0]=Ye>>>16;o[Ze+3|0]=Ye>>>24}function bd(q){q=q|0;return q|0}function cd(q){q=q|0;An(q)}function dd(q){q=q|0;return 2}function ed(Ye,Ze){Ye=Ye|0;Ze=Ze|0;var cf=0,df=0,ef=0,ff=0,gf=0,hf=0;ef=q[Ze+88>>2];if(!(!ef|q[ef>>2]!=1)){ff=ef+8|0;ef=q[ff>>2];cf=ef;q[Ye+4>>2]=r[cf|0]|r[cf+1|0]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(Ze)}return Ye|0}function jd(Ye){Ye=Ye|0;var pf=0;q[Ye>>2]=1232;pf=q[Ye+8>>2];if(pf){q[Ye+12>>2]=pf;An(pf)}An(Ye)}function kd(q){q=q|0;return 1}function ld(Ye,xf){var yf=0;yf=Mm(40);q[yf>>2]=-1;Uj(yf+8|0);n[q[q[Ye>>2]+16>>2]](Ye,yf);Ye=q[xf+88>>2];q[xf+88>>2]=yf;if(Ye){xf=q[Ye+8>>2];if(xf){q[Ye+12>>2]=xf;An(xf)}An(Ye)}return 1}function md(Ye,xf,zf){var Af=0,Bf=0,Cf=0,Df=0,Ef=0,Ff=0;Cf=q[Ye+8>>2];Af=q[Ye+4>>2];if(Cf-Af>>2>>>0>=xf>>>0){while(1){q[Af>>2]=q[zf>>2];Af=Af+4|0;xf=xf+ -1|0;if(xf){continue}break}q[Ye+4>>2]=Af;return}a:{Df=q[Ye>>2];Ef=Af-Df|0;Ff=Ef>>2;Af=Ff+xf|0;if(Af>>>0<1073741824){Cf=Cf-Df|0;Bf=Cf>>1;Af=Cf>>2>>>0<536870911?Bf>>>0>>0?Af:Bf:1073741823;Bf=0;b:{if(!Af){break b}if(Af>>>0>=1073741824){break a}Bf=Mm(Af<<2)}Cf=Bf+(Af<<2)|0;Af=Bf+(Ff<<2)|0;while(1){q[Af>>2]=q[zf>>2];Af=Af+4|0;xf=xf+ -1|0;if(xf){continue}break}if((Ef|0)>=1){Cn(Bf,Df,Ef)}q[Ye>>2]=Bf;q[Ye+8>>2]=Cf;q[Ye+4>>2]=Af;if(Df){An(Df)}return}bn();F()}ab(1308);F()}function nd(Ye){q[Ye+8>>2]=0;q[Ye+12>>2]=0;q[Ye>>2]=0;q[Ye+40>>2]=0;q[Ye+44>>2]=0;q[Ye+28>>2]=9;o[Ye+24|0]=1;q[Ye+56>>2]=-1;q[Ye+60>>2]=0;q[Ye+16>>2]=0;q[Ye+20>>2]=0;q[Ye+48>>2]=0;q[Ye+52>>2]=0;return Ye}function od(Ye,xf,zf,Gf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<<16|r[Tf+3|0]<<24);q[cg+92>>2]=eg;q[xf+16>>2]=dg;q[xf+20>>2]=$f;break b}if(!zd(1,cg+92|0,xf)){break a}eg=q[cg+92>>2]}if(!eg){break a}$f=q[Ye+4>>2];Tf=q[Ye+8>>2]-$f>>2;c:{if(eg>>>0>Tf>>>0){Fa(Ye+4|0,eg-Tf|0);break c}if(eg>>>0>=Tf>>>0){break c}q[Ye+8>>2]=$f+(eg<<2)}lg=Ye+16|0;mg=q[Ye+32>>2];ng=Ye+20|0;while(1){gg=q[xf+8>>2];dg=q[xf+16>>2];bg=q[xf+12>>2];$f=bg;Tf=q[xf+20>>2];if(($f|0)<(Tf|0)?1:($f|0)<=(Tf|0)?gg>>>0>dg>>>0?0:1:0){ag=0;break a}ig=q[xf>>2];og=r[ig+dg|0];$f=Tf;fg=dg+1|0;if(fg>>>0<1){$f=$f+1|0}ag=xf;q[xf+16>>2]=fg;q[xf+20>>2]=$f;if((bg|0)<($f|0)?1:(bg|0)<=($f|0)?gg>>>0>fg>>>0?0:1:0){ag=0;break a}fg=r[fg+ig|0];$f=Tf;hg=dg+2|0;if(hg>>>0<2){$f=$f+1|0}q[xf+16>>2]=hg;q[ag+20>>2]=$f;if((bg|0)<($f|0)?1:(bg|0)<=($f|0)?gg>>>0>hg>>>0?0:1:0){ag=0;break a}hg=r[hg+ig|0];$f=Tf;jg=dg+3|0;if(jg>>>0<3){$f=$f+1|0}q[xf+16>>2]=jg;q[ag+20>>2]=$f;if((bg|0)<($f|0)?1:(bg|0)<=($f|0)?gg>>>0>jg>>>0?0:1:0){ag=0;break a}bg=r[jg+ig|0];$f=Tf;Tf=dg+4|0;if(Tf>>>0<4){$f=$f+1|0}q[xf+16>>2]=Tf;q[ag+20>>2]=$f;if(og>>>0>4){ag=0;break a}if((fg+ -1&255)>>>0>10){ag=0;break a}dg=nd(cg+24|0);Tf=w(bk(fg),hg);od(dg,og,hg<<24>>24,fg,(bg|0)!=0,Tf,Tf>>31);d:{Tf=s[q[Ye+28>>2]+36>>1];e:{if((Tf<<24|Tf<<8&16711680)>>>16>>>0<=258){ag=q[xf+12>>2];$f=q[xf+20>>2];bg=q[xf+16>>2];Tf=bg+2|0;if(Tf>>>0<2){$f=$f+1|0}gg=Tf;Tf=$f;if((ag|0)<(Tf|0)?1:(ag|0)<=(Tf|0)?t[xf+8>>2]>=gg>>>0?0:1:0){break d}$f=bg+q[xf>>2]|0;$f=r[$f|0]|r[$f+1|0]<<8;q[xf+16>>2]=gg;q[xf+20>>2]=Tf;q[cg+20>>2]=$f;break e}zd(1,cg+20|0,xf);$f=q[cg+20>>2]}q[cg+84>>2]=$f;Tf=Mm(96);sd(Tf,dg);q[cg+16>>2]=Tf;Tf=fl(mg,cg+16|0);ag=q[cg+16>>2];q[cg+16>>2]=0;if(ag){Hb(ag)}bg=Tf<<2;q[q[bg+q[mg+8>>2]>>2]+60>>2]=$f;q[q[Ye+4>>2]+(kg<<2)>>2]=Tf;$f=q[Ye+16>>2];ag=q[ng>>2]-$f>>2;f:{if((Tf|0)<(ag|0)){break f}q[cg+12>>2]=-1;Tf=Tf+1|0;if(Tf>>>0>ag>>>0){Ad(lg,Tf-ag|0,cg+12|0);$f=q[lg>>2];break f}if(Tf>>>0>=ag>>>0){break f}q[ng>>2]=(Tf<<2)+$f}q[$f+bg>>2]=kg;ag=1;kg=kg+1|0;if((kg|0)!=(eg|0)){continue}break a}break}ag=0}T=cg+96|0;return ag|0}function zd(Ye,xf,pg){var qg=0,rg=0,sg=0,tg=0;a:{if(Ye>>>0>5){break a}sg=q[pg+16>>2];qg=q[pg+12>>2];rg=q[pg+20>>2];if((qg|0)<(rg|0)?1:(qg|0)<=(rg|0)?t[pg+8>>2]>sg>>>0?0:1:0){break a}qg=r[sg+q[pg>>2]|0];sg=sg+1|0;if(sg>>>0<1){rg=rg+1|0}q[pg+16>>2]=sg;q[pg+20>>2]=rg;rg=xf;if(qg&128){if(!zd(Ye+1|0,xf,pg)){break a}Ye=q[xf>>2]<<7;q[xf>>2]=Ye;qg=Ye|qg&127}q[rg>>2]=qg;tg=1}return tg}function Ad(Ye,xf,pg){var ug=0,vg=0,wg=0,xg=0,yg=0,zg=0;wg=q[Ye+8>>2];ug=q[Ye+4>>2];if(wg-ug>>2>>>0>=xf>>>0){while(1){q[ug>>2]=q[pg>>2];ug=ug+4|0;xf=xf+ -1|0;if(xf){continue}break}q[Ye+4>>2]=ug;return}a:{xg=q[Ye>>2];yg=ug-xg|0;zg=yg>>2;ug=zg+xf|0;if(ug>>>0<1073741824){wg=wg-xg|0;vg=wg>>1;ug=wg>>2>>>0<536870911?vg>>>0>>0?ug:vg:1073741823;vg=0;b:{if(!ug){break b}if(ug>>>0>=1073741824){break a}vg=Mm(ug<<2)}wg=vg+(ug<<2)|0;ug=vg+(zg<<2)|0;while(1){q[ug>>2]=q[pg>>2];ug=ug+4|0;xf=xf+ -1|0;if(xf){continue}break}if((yg|0)>=1){Cn(vg,xg,yg)}q[Ye>>2]=vg;q[Ye+8>>2]=wg;q[Ye+4>>2]=ug;if(xg){An(xg)}return}bn();F()}ab(1520);F()}function Bd(Ye){Ye=Ye|0;var xf=0;q[Ye>>2]=1384;xf=q[Ye+16>>2];if(xf){q[Ye+20>>2]=xf;An(xf)}xf=q[Ye+4>>2];if(xf){q[Ye+8>>2]=xf;An(xf)}return Ye|0}function Cd(q){q=q|0;F()}function Dd(Ye,pg){Ye=Ye|0;pg=pg|0;var Ag=0;a:{if(!n[q[q[Ye>>2]+36>>2]](Ye,pg)){break a}if(!n[q[q[Ye>>2]+40>>2]](Ye,pg)){break a}Ag=n[q[q[Ye>>2]+44>>2]](Ye)|0}return Ag|0}function Ed(Ye,pg){Ye=Ye|0;pg=pg|0;return q[q[Ye+4>>2]+(pg<<2)>>2]}function Fd(Ye){Ye=Ye|0;return q[Ye+8>>2]-q[Ye+4>>2]>>2}function Gd(q,Ye){q=q|0;Ye=Ye|0;return 0}function Hd(q,Ye){q=q|0;Ye=Ye|0;return 1}function Id(Ye){wd(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break h;case 3:Bg=Wd(Cg,Gg);pg=Ud(Bg,pg,Ye);Vd(Bg);if(pg){break i}break h;case 4:Bg=Wd(Cg,Gg);pg=Xd(Bg,pg,Ye);Vd(Bg);if(pg){break i}break h;case 5:break j}}Bg=Wd(Cg,Gg);pg=Yd(Bg,pg,Ye);Vd(Bg);if(!pg){break h}}Dg=1}pg=q[Ye+16>>2];if(pg){q[Ye+20>>2]=pg;An(pg)}pg=q[Ye>>2];if(!pg){break c}q[Ye+4>>2]=pg;An(pg)}Ye=q[Cg+688>>2];if(!Ye){break b}q[Cg+692>>2]=Ye;An(Ye)}T=Cg+704|0;return Dg|0}bn();F()}function Kd(Ye,pg){var Rg=0,Sg=0,Tg=0,Ug=0,Vg=0;a:{b:{c:{Tg=q[Ye>>2];Ug=q[Ye+4>>2]-Tg>>2;Rg=Ug+1|0;if(Rg>>>0<1073741824){Tg=q[Ye+8>>2]-Tg|0;Vg=Tg>>1;Rg=Tg>>2>>>0<536870911?Vg>>>0>>0?Rg:Vg:1073741823;if(Rg){if(Rg>>>0>=1073741824){break c}Sg=Mm(Rg<<2)}Tg=q[pg>>2];q[pg>>2]=0;pg=(Ug<<2)+Sg|0;q[pg>>2]=Tg;Tg=(Rg<<2)+Sg|0;Ug=pg+4|0;Rg=q[Ye+4>>2];Sg=q[Ye>>2];if((Rg|0)==(Sg|0)){break b}while(1){Rg=Rg+ -4|0;Vg=q[Rg>>2];q[Rg>>2]=0;pg=pg+ -4|0;q[pg>>2]=Vg;if((Rg|0)!=(Sg|0)){continue}break}Sg=q[Ye+4>>2];Rg=q[Ye>>2];break a}bn();F()}ab(1780);F()}Rg=Sg}q[Ye>>2]=pg;q[Ye+8>>2]=Tg;q[Ye+4>>2]=Ug;if((Rg|0)!=(Sg|0)){while(1){Sg=Sg+ -4|0;Ye=q[Sg>>2];q[Sg>>2]=0;if(Ye){Hb(Ye)}if((Rg|0)!=(Sg|0)){continue}break}}if(Rg){An(Rg)}}function Ld(Ye,pg){var Wg=0,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bh=fh+8|0;if(bh>>>0<8){eh=eh+1|0}if((ch|0)<(eh|0)?1:(ch|0)<=(eh|0)?t[pg+8>>2]>=bh>>>0?0:1:0){break a}bh=dh+q[pg>>2]|0;ch=r[bh|0]|r[bh+1|0]<<8|(r[bh+2|0]<<16|r[bh+3|0]<<24);q[Ye+4>>2]=ch;dh=q[pg+20>>2];eh=q[pg+16>>2]+4|0;if(eh>>>0<4){dh=dh+1|0}q[pg+16>>2]=eh;q[pg+20>>2]=dh;if(!ch){gh=1;break a}q[Ye+8>>2]=0;if(!$g(Ye+16|0,pg)){break a}if(!$g(Ye+36|0,pg)){break a}if(!$g(Ye+56|0,pg)){break a}if(!$g(Ye+76|0,pg)){break a}return Zd(Ye,q[Ye+4>>2],ah)}return gh}function Nd(Ye){var pg=0,$g=0,ah=0,hh=0,ih=0;ah=q[Ye+132>>2];if(ah){ih=Ye+136|0;pg=q[ih>>2];$g=ah;a:{if((ah|0)==(pg|0)){break a}while(1){$g=pg+ -12|0;hh=q[$g>>2];if(hh){q[pg+ -8>>2]=hh;An(hh)}pg=$g;if((pg|0)!=(ah|0)){continue}break}$g=q[Ye+132>>2]}q[ih>>2]=ah;An($g)}ah=q[Ye+120>>2];if(ah){ih=Ye+124|0;pg=q[ih>>2];$g=ah;b:{if((ah|0)==(pg|0)){break b}while(1){$g=pg+ -12|0;hh=q[$g>>2];if(hh){q[pg+ -8>>2]=hh;An(hh)}pg=$g;if((pg|0)!=(ah|0)){continue}break}$g=q[Ye+120>>2]}q[ih>>2]=ah;An($g)}pg=q[Ye+108>>2];if(pg){q[Ye+112>>2]=pg;An(pg)}pg=q[Ye+96>>2];if(pg){q[Ye+100>>2]=pg;An(pg)}_g(Ye+76|0);_g(Ye+56|0);_g(Ye+36|0);_g(Ye+16|0)}function Od(Ye,jh){var kh=0,lh=0,mh=0,nh=0;mh=T-16|0;T=mh;q[Ye+12>>2]=jh;q[Ye+8>>2]=0;q[Ye>>2]=0;q[Ye+4>>2]=0;Zg(Ye+16|0);Zg(Ye+36|0);Zg(Ye+56|0);Zg(Ye+76|0);q[Ye+104>>2]=0;q[Ye+96>>2]=0;q[Ye+100>>2]=0;a:{b:{c:{if(jh){if(jh>>>0>=1073741824){break c}kh=jh<<2;lh=Mm(kh);q[Ye+96>>2]=lh;q[Ye+100>>2]=lh;q[Ye+104>>2]=lh+kh;Dn(lh,0,kh);kh=jh;while(1){lh=lh+4|0;kh=kh+ -1|0;if(kh){continue}break}q[Ye+100>>2]=lh}q[Ye+108>>2]=0;q[Ye+112>>2]=0;q[Ye+116>>2]=0;if(jh){if(jh>>>0>=1073741824){break b}kh=jh<<2;lh=Mm(kh);q[Ye+108>>2]=lh;q[Ye+112>>2]=lh;q[Ye+116>>2]=lh+kh;Dn(lh,0,kh);kh=jh;while(1){lh=lh+4|0;kh=kh+ -1|0;if(kh){continue}break}q[Ye+112>>2]=lh}q[mh+8>>2]=0;q[mh>>2]=0;q[mh+4>>2]=0;if(jh){if(jh>>>0>=1073741824){break a}kh=jh<<2;lh=Mm(kh);q[mh>>2]=lh;q[mh+4>>2]=lh;q[mh+8>>2]=lh+kh;Dn(lh,0,kh);kh=jh;while(1){lh=lh+4|0;kh=kh+ -1|0;if(kh){continue}break}q[mh+4>>2]=lh}nh=jh<<5|1;_d(Ye+120|0,nh,mh);kh=q[mh>>2];if(kh){q[mh+4>>2]=kh;An(kh)}q[mh+8>>2]=0;q[mh>>2]=0;q[mh+4>>2]=0;if(jh){if(jh>>>0>=1073741824){break a}kh=jh<<2;lh=Mm(kh);q[mh>>2]=lh;q[mh+4>>2]=lh;q[mh+8>>2]=lh+kh;Dn(lh,0,kh);while(1){lh=lh+4|0;jh=jh+ -1|0;if(jh){continue}break}q[mh+4>>2]=lh}_d(Ye+132|0,nh,mh);jh=q[mh>>2];if(jh){q[mh+4>>2]=jh;An(jh)}T=mh+16|0;return Ye}bn();F()}bn();F()}bn();F()}function Pd(Ye,jh,oh){var ph=0,qh=0,rh=0,sh=0,th=0,uh=0;qh=q[jh+12>>2];a:{rh=q[jh+20>>2];sh=q[jh+16>>2];ph=sh+4|0;if(ph>>>0<4){rh=rh+1|0}if((qh|0)<(rh|0)?1:(qh|0)<=(rh|0)?t[jh+8>>2]>=ph>>>0?0:1:0){break a}ph=sh+q[jh>>2]|0;ph=r[ph|0]|r[ph+1|0]<<8|(r[ph+2|0]<<16|r[ph+3|0]<<24);q[Ye>>2]=ph;qh=q[jh+20>>2];sh=qh;th=q[jh+16>>2];rh=th+4|0;if(rh>>>0<4){qh=qh+1|0}q[jh+16>>2]=rh;q[jh+20>>2]=qh;if(ph>>>0>32){break a}qh=q[jh+12>>2];ph=th+8|0;if(ph>>>0<8){sh=sh+1|0}if((qh|0)<(sh|0)?1:(qh|0)<=(sh|0)?t[jh+8>>2]>=ph>>>0?0:1:0){break a}ph=rh+q[jh>>2]|0;qh=r[ph|0]|r[ph+1|0]<<8|(r[ph+2|0]<<16|r[ph+3|0]<<24);q[Ye+4>>2]=qh;rh=q[jh+20>>2];sh=q[jh+16>>2]+4|0;if(sh>>>0<4){rh=rh+1|0}q[jh+16>>2]=sh;q[jh+20>>2]=rh;if(!qh){uh=1;break a}q[Ye+8>>2]=0;if(!$g(Ye+16|0,jh)){break a}if(!$g(Ye+36|0,jh)){break a}if(!$g(Ye+56|0,jh)){break a}if(!$g(Ye+76|0,jh)){break a}return $d(Ye,q[Ye+4>>2],oh)}return uh}function Qd(Ye,jh,oh){var vh=0,wh=0,xh=0,yh=0,zh=0,Ah=0;wh=q[jh+12>>2];a:{xh=q[jh+20>>2];yh=q[jh+16>>2];vh=yh+4|0;if(vh>>>0<4){xh=xh+1|0}if((wh|0)<(xh|0)?1:(wh|0)<=(xh|0)?t[jh+8>>2]>=vh>>>0?0:1:0){break a}vh=yh+q[jh>>2]|0;vh=r[vh|0]|r[vh+1|0]<<8|(r[vh+2|0]<<16|r[vh+3|0]<<24);q[Ye>>2]=vh;wh=q[jh+20>>2];yh=wh;zh=q[jh+16>>2];xh=zh+4|0;if(xh>>>0<4){wh=wh+1|0}q[jh+16>>2]=xh;q[jh+20>>2]=wh;if(vh>>>0>32){break a}wh=q[jh+12>>2];vh=zh+8|0;if(vh>>>0<8){yh=yh+1|0}if((wh|0)<(yh|0)?1:(wh|0)<=(yh|0)?t[jh+8>>2]>=vh>>>0?0:1:0){break a}vh=xh+q[jh>>2]|0;wh=r[vh|0]|r[vh+1|0]<<8|(r[vh+2|0]<<16|r[vh+3|0]<<24);q[Ye+4>>2]=wh;xh=q[jh+20>>2];yh=q[jh+16>>2]+4|0;if(yh>>>0<4){xh=xh+1|0}q[jh+16>>2]=yh;q[jh+20>>2]=xh;if(!wh){Ah=1;break a}q[Ye+8>>2]=0;if(!bh(Ye+16|0,jh)){break a}if(!$g(Ye+32|0,jh)){break a}if(!$g(Ye+52|0,jh)){break a}if(!$g(Ye+72|0,jh)){break a}return ae(Ye,q[Ye+4>>2],oh)}return Ah}function Rd(Ye){var jh=0,oh=0,Bh=0,Ch=0,Dh=0;Bh=q[Ye+128>>2];if(Bh){Dh=Ye+132|0;jh=q[Dh>>2];oh=Bh;a:{if((Bh|0)==(jh|0)){break a}while(1){oh=jh+ -12|0;Ch=q[oh>>2];if(Ch){q[jh+ -8>>2]=Ch;An(Ch)}jh=oh;if((jh|0)!=(Bh|0)){continue}break}oh=q[Ye+128>>2]}q[Dh>>2]=Bh;An(oh)}Bh=q[Ye+116>>2];if(Bh){Dh=Ye+120|0;jh=q[Dh>>2];oh=Bh;b:{if((Bh|0)==(jh|0)){break b}while(1){oh=jh+ -12|0;Ch=q[oh>>2];if(Ch){q[jh+ -8>>2]=Ch;An(Ch)}jh=oh;if((jh|0)!=(Bh|0)){continue}break}oh=q[Ye+116>>2]}q[Dh>>2]=Bh;An(oh)}jh=q[Ye+104>>2];if(jh){q[Ye+108>>2]=jh;An(jh)}jh=q[Ye+92>>2];if(jh){q[Ye+96>>2]=jh;An(jh)}_g(Ye+72|0);_g(Ye+52|0);_g(Ye+32|0)}function Sd(Ye,Eh){var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h|0)==(Eh|0)){break a}while(1){Jh=Eh+ -12|0;Xh=q[Jh>>2];if(Xh){q[Eh+ -8>>2]=Xh;An(Xh)}Eh=Jh;if((Eh|0)!=(Wh|0)){continue}break}Jh=q[Ye+640>>2]}q[Yh>>2]=Wh;An(Jh)}Wh=q[Ye+628>>2];if(Wh){Yh=Ye+632|0;Eh=q[Yh>>2];Jh=Wh;b:{if((Wh|0)==(Eh|0)){break b}while(1){Jh=Eh+ -12|0;Xh=q[Jh>>2];if(Xh){q[Eh+ -8>>2]=Xh;An(Xh)}Eh=Jh;if((Eh|0)!=(Wh|0)){continue}break}Jh=q[Ye+628>>2]}q[Yh>>2]=Wh;An(Jh)}Eh=q[Ye+616>>2];if(Eh){q[Ye+620>>2]=Eh;An(Eh)}Eh=q[Ye+604>>2];if(Eh){q[Ye+608>>2]=Eh;An(Eh)}_g(Ye+584|0);_g(Ye+564|0);_g(Ye+544|0)}function Wd(Ye,Zh){var _h=0,$h=0,ai=0,bi=0;ai=T-16|0;T=ai;q[Ye+12>>2]=Zh;q[Ye+8>>2]=0;q[Ye>>2]=0;q[Ye+4>>2]=0;de(Ye+16|0);ah(Ye+528|0);Zg(Ye+544|0);Zg(Ye+564|0);Zg(Ye+584|0);q[Ye+612>>2]=0;q[Ye+604>>2]=0;q[Ye+608>>2]=0;a:{b:{c:{if(Zh){if(Zh>>>0>=1073741824){break c}_h=Zh<<2;$h=Mm(_h);q[Ye+604>>2]=$h;q[Ye+608>>2]=$h;q[Ye+612>>2]=$h+_h;Dn($h,0,_h);_h=Zh;while(1){$h=$h+4|0;_h=_h+ -1|0;if(_h){continue}break}q[Ye+608>>2]=$h}q[Ye+616>>2]=0;q[Ye+620>>2]=0;q[Ye+624>>2]=0;if(Zh){if(Zh>>>0>=1073741824){break b}_h=Zh<<2;$h=Mm(_h);q[Ye+616>>2]=$h;q[Ye+620>>2]=$h;q[Ye+624>>2]=$h+_h;Dn($h,0,_h);_h=Zh;while(1){$h=$h+4|0;_h=_h+ -1|0;if(_h){continue}break}q[Ye+620>>2]=$h}q[ai+8>>2]=0;q[ai>>2]=0;q[ai+4>>2]=0;if(Zh){if(Zh>>>0>=1073741824){break a}_h=Zh<<2;$h=Mm(_h);q[ai>>2]=$h;q[ai+4>>2]=$h;q[ai+8>>2]=$h+_h;Dn($h,0,_h);_h=Zh;while(1){$h=$h+4|0;_h=_h+ -1|0;if(_h){continue}break}q[ai+4>>2]=$h}bi=Zh<<5|1;_d(Ye+628|0,bi,ai);_h=q[ai>>2];if(_h){q[ai+4>>2]=_h;An(_h)}q[ai+8>>2]=0;q[ai>>2]=0;q[ai+4>>2]=0;if(Zh){if(Zh>>>0>=1073741824){break a}_h=Zh<<2;$h=Mm(_h);q[ai>>2]=$h;q[ai+4>>2]=$h;q[ai+8>>2]=$h+_h;Dn($h,0,_h);while(1){$h=$h+4|0;Zh=Zh+ -1|0;if(Zh){continue}break}q[ai+4>>2]=$h}_d(Ye+640|0,bi,ai);Zh=q[ai>>2];if(Zh){q[ai+4>>2]=Zh;An(Zh)}T=ai+16|0;return Ye}bn();F()}bn();F()}bn();F()}function Xd(Ye,Zh,ci){var di=0,ei=0,fi=0,gi=0,hi=0,ii=0;ei=q[Zh+12>>2];a:{fi=q[Zh+20>>2];gi=q[Zh+16>>2];di=gi+4|0;if(di>>>0<4){fi=fi+1|0}if((ei|0)<(fi|0)?1:(ei|0)<=(fi|0)?t[Zh+8>>2]>=di>>>0?0:1:0){break a}di=gi+q[Zh>>2]|0;di=r[di|0]|r[di+1|0]<<8|(r[di+2|0]<<16|r[di+3|0]<<24);q[Ye>>2]=di;ei=q[Zh+20>>2];gi=ei;hi=q[Zh+16>>2];fi=hi+4|0;if(fi>>>0<4){ei=ei+1|0}q[Zh+16>>2]=fi;q[Zh+20>>2]=ei;if(di>>>0>32){break a}ei=q[Zh+12>>2];di=hi+8|0;if(di>>>0<8){gi=gi+1|0}if((ei|0)<(gi|0)?1:(ei|0)<=(gi|0)?t[Zh+8>>2]>=di>>>0?0:1:0){break a}di=fi+q[Zh>>2]|0;ei=r[di|0]|r[di+1|0]<<8|(r[di+2|0]<<16|r[di+3|0]<<24);q[Ye+4>>2]=ei;fi=q[Zh+20>>2];gi=q[Zh+16>>2]+4|0;if(gi>>>0<4){fi=fi+1|0}q[Zh+16>>2]=gi;q[Zh+20>>2]=fi;if(!ei){ii=1;break a}q[Ye+8>>2]=0;di=0;while(1){if(!bh(((di<<4)+Ye|0)+16|0,Zh)){break a}di=di+1|0;if((di|0)!=32){continue}break}if(!bh(Ye+528|0,Zh)){break a}if(!$g(Ye+544|0,Zh)){break a}if(!$g(Ye+564|0,Zh)){break a}if(!$g(Ye+584|0,Zh)){break a}return ee(Ye,q[Ye+4>>2],ci)}return ii}function Yd(Ye,Zh,ci){var ji=0,ki=0,li=0,mi=0,ni=0,oi=0;ki=q[Zh+12>>2];a:{li=q[Zh+20>>2];mi=q[Zh+16>>2];ji=mi+4|0;if(ji>>>0<4){li=li+1|0}if((ki|0)<(li|0)?1:(ki|0)<=(li|0)?t[Zh+8>>2]>=ji>>>0?0:1:0){break a}ji=mi+q[Zh>>2]|0;ji=r[ji|0]|r[ji+1|0]<<8|(r[ji+2|0]<<16|r[ji+3|0]<<24);q[Ye>>2]=ji;ki=q[Zh+20>>2];mi=ki;ni=q[Zh+16>>2];li=ni+4|0;if(li>>>0<4){ki=ki+1|0}q[Zh+16>>2]=li;q[Zh+20>>2]=ki;if(ji>>>0>32){break a}ki=q[Zh+12>>2];ji=ni+8|0;if(ji>>>0<8){mi=mi+1|0}if((ki|0)<(mi|0)?1:(ki|0)<=(mi|0)?t[Zh+8>>2]>=ji>>>0?0:1:0){break a}ji=li+q[Zh>>2]|0;ki=r[ji|0]|r[ji+1|0]<<8|(r[ji+2|0]<<16|r[ji+3|0]<<24);q[Ye+4>>2]=ki;li=q[Zh+20>>2];mi=q[Zh+16>>2]+4|0;if(mi>>>0<4){li=li+1|0}q[Zh+16>>2]=mi;q[Zh+20>>2]=li;if(!ki){oi=1;break a}q[Ye+8>>2]=0;ji=0;while(1){if(!bh(((ji<<4)+Ye|0)+16|0,Zh)){break a}ji=ji+1|0;if((ji|0)!=32){continue}break}if(!bh(Ye+528|0,Zh)){break a}if(!$g(Ye+544|0,Zh)){break a}if(!$g(Ye+564|0,Zh)){break a}if(!$g(Ye+584|0,Zh)){break a}return fe(Ye,q[Ye+4>>2],ci)}return oi}function Zd(Ye,Zh,ci){var pi=0,qi=0,ri=0,si=0,ti=0,ui=0,vi=0,wi=0,xi=0,yi=0,zi=0,Ai=0,Bi=0,Ci=0,Di=0,Ei=0,Fi=0,Gi=0,Hi=0,Ii=0,Ji=0,Ki=0,Li=0,Mi=0,Ni=0,Oi=0;si=T-32|0;T=si;qi=q[Ye+12>>2];q[si+16>>2]=0;q[si+8>>2]=0;q[si+12>>2]=0;a:{if(qi){if(qi>>>0>=1073741824){break a}pi=qi<<2;ri=Mm(pi);q[si+8>>2]=ri;q[si+12>>2]=ri;q[si+16>>2]=pi+ri;ui=Dn(ri,0,pi);pi=qi;while(1){ui=ui+4|0;pi=pi+ -1|0;if(pi){continue}break}q[si+12>>2]=ui}ti=q[Ye+120>>2];pi=q[ti>>2];if(pi){q[ti+4>>2]=pi;An(pi);q[ti+8>>2]=0;q[ti>>2]=0;q[ti+4>>2]=0;qi=q[Ye+12>>2];ui=q[si+12>>2];ri=q[si+8>>2]}q[ti>>2]=ri;q[ti+4>>2]=ui;q[ti+8>>2]=q[si+16>>2];ui=0;q[si+16>>2]=0;q[si+8>>2]=0;q[si+12>>2]=0;pi=0;b:{if(qi){if(qi>>>0>=1073741824){break b}ri=qi<<2;pi=Mm(ri);q[si+8>>2]=pi;q[si+12>>2]=pi;q[si+16>>2]=pi+ri;ui=Dn(pi,0,ri);while(1){ui=ui+4|0;qi=qi+ -1|0;if(qi){continue}break}q[si+12>>2]=ui}ti=q[Ye+132>>2];ri=q[ti>>2];if(ri){q[ti+4>>2]=ri;An(ri);q[ti+8>>2]=0;q[ti>>2]=0;q[ti+4>>2]=0;ui=q[si+12>>2];pi=q[si+8>>2]}q[ti>>2]=pi;q[ti+4>>2]=ui;q[ti+8>>2]=q[si+16>>2];qi=si+24|0;q[qi>>2]=0;q[qi+4>>2]=0;ri=si+16|0;q[ri>>2]=0;q[ri+4>>2]=0;q[si+8>>2]=0;q[si+12>>2]=0;re(si+8|0);ti=q[si+12>>2];pi=0;c:{if((ti|0)==q[ri>>2]){break c}ri=q[qi>>2]+q[si+28>>2]|0;pi=(ri>>>0)/341|0;pi=q[ti+(pi<<2)>>2]+w(ri-w(pi,341)|0,12)|0}q[pi+4>>2]=0;q[pi+8>>2]=0;q[pi>>2]=Zh;pi=1;ri=q[si+28>>2];qi=ri+1|0;q[si+28>>2]=qi;d:{if(qi>>>0>>0){break d}Li=Ye+132|0;Ki=Ye+120|0;Gi=ci+20|0;Mi=Ye+108|0;Ni=Ye+96|0;Hi=Ye+48|0;Ii=Ye+28|0;Oi=Ye+80|0;while(1){pi=q[si+12>>2];vi=q[si+24>>2];wi=qi+ -1|0;ti=vi+wi|0;ri=(ti>>>0)/341|0;ri=q[pi+(ri<<2)>>2]+w(ti-w(ri,341)|0,12)|0;Ai=q[ri+8>>2];ti=q[ri+4>>2];zi=q[ri>>2];q[si+28>>2]=wi;ri=q[si+16>>2];pi=ri-pi|0;if(((pi?w(pi>>2,341)+ -1|0:0)-(qi+vi|0)|0)+1>>>0>=682){An(q[ri+ -4>>2]);q[si+16>>2]=q[si+16>>2]+ -4}pi=0;if(zi>>>0>Zh>>>0){break d}ri=q[Ki>>2];Bi=w(Ai,12);Ei=Bi+q[Li>>2]|0;ui=ml(Ye,Ei,ti);if(ui>>>0>=t[Ye+12>>2]){break d}Fi=ri+Bi|0;e:{f:{Ci=ui<<2;ti=q[Ye>>2]-q[Ci+q[Ei>>2]>>2]|0;if(!ti){if(!zi){break f}xi=0;while(1){ti=0;qi=q[ci+16>>2];g:{if((qi|0)==q[Gi>>2]){break g}while(1){qi=w(ti,20)+qi|0;ri=q[Fi>>2]+(q[qi+4>>2]<<2)|0;yi=q[qi>>2];ui=q[qi+12>>2];h:{if(ui>>>0>3){break h}pi=q[ci+12>>2];vi=qi+16|0;if(!q[vi>>2]){ri=pi;break h}wi=qi+12|0;qi=0;while(1){pi=Cn(pi,(qi<<2)+ri|0,ui);ui=q[wi>>2];pi=pi+ui|0;qi=qi+1|0;if(qi>>>0>2]){continue}break}ri=q[ci+12>>2]}qi=q[ci+28>>2];qi=r[yi+84|0]?qi:q[q[yi+68>>2]+(qi<<2)>>2];if(qi>>>0>=t[yi+80>>2]){break g}pi=q[yi+40>>2];Cn(q[q[yi>>2]>>2]+w(pi,qi)|0,ri,pi);ti=ti+1|0;qi=q[ci+16>>2];if(ti>>>0<(q[Gi>>2]-qi|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;xi=xi+1|0;if((zi|0)!=(xi|0)){continue}break}break f}i:{j:{k:{l:{if(zi>>>0<=2){ri=q[Mi>>2];q[ri>>2]=ui;pi=1;qi=q[Ye+12>>2];if(qi>>>0>1){break l}break i}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}pi=q[Ki>>2];xi=Ai+1|0;yi=w(xi,12);ri=pi+yi|0;if((ri|0)!=(Fi|0)){hd(ri,q[Fi>>2],q[Fi+4>>2]);pi=q[Ki>>2]}pi=Ci+q[pi+yi>>2]|0;q[pi>>2]=q[pi>>2]+(1<>2];ti=32-wi|0;m:{if((vi|0)<=(ti|0)){ti=q[Ii>>2];if((ti|0)==q[Ye+20>>2]){pi=0;break m}pi=q[ti>>2];ri=vi+wi|0;q[Ye+32>>2]=ri;pi=pi<>>32-vi;if((ri|0)!=32){break m}q[Ye+32>>2]=0;q[Ii>>2]=ti+4;break m}qi=q[Ii>>2];pi=qi+4|0;if((pi|0)==q[Ye+20>>2]){pi=0;break m}ri=q[qi>>2];q[Ii>>2]=pi;pi=vi-ti|0;q[Ye+32>>2]=pi;pi=q[qi+4>>2]>>>32-pi|ri<>>32-vi}ri=(zi>>>1)-pi|0;pi=zi-ri|0;n:{if((pi|0)==(ri|0)){pi=ri;break n}vi=q[Ye+88>>2];if((vi|0)==q[Oi>>2]){break k}wi=q[vi>>2];qi=q[Ye+92>>2];ti=qi+1|0;q[Ye+92>>2]=ti;qi=wi&-2147483648>>>qi;o:{if((ti|0)==32){q[Ye+92>>2]=0;q[Ye+88>>2]=vi+4;if(qi){break o}break k}if(!qi){break k}}}ti=pi;pi=ri;break j}while(1){ui=(qi+ -1|0)==(ui|0)?0:ui+1|0;q[ri+(pi<<2)>>2]=ui;pi=pi+1|0;qi=q[Ye+12>>2];if(pi>>>0>>0){continue}break}break i}ti=ri}vi=q[Li>>2];wi=vi+Bi|0;qi=q[wi>>2];ri=qi+Ci|0;q[ri>>2]=q[ri>>2]+1;hd(vi+yi|0,qi,q[wi+4>>2]);if(pi){ri=q[si+28>>2]+q[si+24>>2]|0;vi=q[si+16>>2];qi=q[si+12>>2];wi=vi-qi|0;if((ri|0)==((wi?w(wi>>2,341)+ -1|0:0)|0)){re(si+8|0);qi=q[si+12>>2];vi=q[si+16>>2];ri=q[si+24>>2]+q[si+28>>2]|0}if((qi|0)==(vi|0)){ri=0}else{Ei=qi;qi=(ri>>>0)/341|0;ri=q[Ei+(qi<<2)>>2]+w(ri-w(qi,341)|0,12)|0}q[ri+8>>2]=Ai;q[ri+4>>2]=ui;q[ri>>2]=pi;q[si+28>>2]=q[si+28>>2]+1}if(!ti){break f}pi=q[si+28>>2]+q[si+24>>2]|0;ri=q[si+16>>2];qi=q[si+12>>2];wi=ri-qi|0;if((pi|0)==((wi?w(wi>>2,341)+ -1|0:0)|0)){re(si+8|0);ri=q[si+16>>2];qi=q[si+12>>2];pi=q[si+24>>2]+q[si+28>>2]|0}if((qi|0)==(ri|0)){pi=0}else{ri=(pi>>>0)/341|0;pi=q[(ri<<2)+qi>>2]+w(pi-w(ri,341)|0,12)|0}q[pi+8>>2]=xi;q[pi+4>>2]=ui;q[pi>>2]=ti;qi=q[si+28>>2]+1|0;q[si+28>>2]=qi;break e}if(!zi){break f}Ai=0;while(1){if(qi){ui=q[Ni>>2];xi=q[Mi>>2];vi=q[Fi>>2];wi=q[Ei>>2];qi=0;while(1){Bi=xi+(qi<<2)|0;q[ui+(q[Bi>>2]<<2)>>2]=0;pi=q[Bi>>2]<<2;Di=q[Ye>>2]-q[pi+wi>>2]|0;p:{if(!Di){break p}Ji=pi+ui|0;Ci=q[Ye+52>>2];ti=32-Ci|0;if((Di|0)<=(ti|0)){ri=q[Hi>>2];if((ri|0)==q[Ye+40>>2]){q[Ji>>2]=0;break p}q[Ji>>2]=q[ri>>2]<>>32-Di;pi=Di+q[Ye+52>>2]|0;q[Ye+52>>2]=pi;if((pi|0)!=32){break p}q[Ye+52>>2]=0;q[Hi>>2]=ri+4;break p}yi=q[Hi>>2];pi=yi+4|0;if((pi|0)==q[Ye+40>>2]){q[Ji>>2]=0;break p}ri=q[yi>>2];q[Hi>>2]=pi;pi=Di-ti|0;q[Ye+52>>2]=pi;q[Ji>>2]=q[yi+4>>2]>>>32-pi|ri<>>32-Di}ri=q[Bi>>2]<<2;pi=ri+ui|0;q[pi>>2]=q[pi>>2]|q[ri+vi>>2];qi=qi+1|0;if(qi>>>0>2]){continue}break}}ti=0;qi=q[ci+16>>2];q:{if((qi|0)==q[Gi>>2]){break q}while(1){qi=w(ti,20)+qi|0;ri=q[Ni>>2]+(q[qi+4>>2]<<2)|0;xi=q[qi>>2];ui=q[qi+12>>2];r:{if(ui>>>0>3){break r}pi=q[ci+12>>2];vi=qi+16|0;if(!q[vi>>2]){ri=pi;break r}wi=qi+12|0;qi=0;while(1){pi=Cn(pi,(qi<<2)+ri|0,ui);ui=q[wi>>2];pi=pi+ui|0;qi=qi+1|0;if(qi>>>0>2]){continue}break}ri=q[ci+12>>2]}qi=q[ci+28>>2];qi=r[xi+84|0]?qi:q[q[xi+68>>2]+(qi<<2)>>2];if(qi>>>0>=t[xi+80>>2]){break q}pi=q[xi+40>>2];Cn(q[q[xi>>2]>>2]+w(pi,qi)|0,ri,pi);ti=ti+1|0;qi=q[ci+16>>2];if(ti>>>0<(q[Gi>>2]-qi|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Ai=Ai+1|0;if((Ai|0)==(zi|0)){break f}qi=q[Ye+12>>2];continue}}qi=q[si+28>>2]}if(qi){continue}break}pi=1}se(si+8|0);qi=q[si+12>>2];Ye=q[si+16>>2];s:{if((qi|0)==(Ye|0)){break s}while(1){An(q[qi>>2]);qi=qi+4|0;if((Ye|0)!=(qi|0)){continue}break}Zh=q[si+16>>2];Ye=q[si+12>>2];if((Zh|0)==(Ye|0)){break s}q[si+16>>2]=Zh+(((Zh-Ye|0)+ -4>>>2^-1)<<2)}Ye=q[si+8>>2];if(Ye){An(Ye)}T=si+32|0;return pi}bn();F()}bn();F()}function _d(Ye,Zh,ci){var Pi=0,Qi=0,Ri=0,Si=0,Ti=0,Ui=0,Vi=0,Wi=0;q[Ye>>2]=0;q[Ye+4>>2]=0;q[Ye+8>>2]=0;a:{b:{if(Zh){if(Zh>>>0>=357913942){break b}Qi=w(Zh,12);Pi=Mm(Qi);q[Ye>>2]=Pi;Ri=Ye+4|0;q[Ri>>2]=Pi;q[Ye+8>>2]=Pi+Qi;while(1){q[Pi>>2]=0;q[Pi+4>>2]=0;Qi=Pi+8|0;q[Qi>>2]=0;Si=ci+4|0;Ye=q[Si>>2]-q[ci>>2]|0;c:{if(!Ye){break c}Ti=Ye>>2;if(Ti>>>0>=1073741824){break a}Ye=Mm(Ye);q[Pi>>2]=Ye;Ui=Pi+4|0;q[Ui>>2]=Ye;q[Qi>>2]=Ye+(Ti<<2);Qi=q[ci>>2];Pi=q[Si>>2]-Qi|0;if((Pi|0)<1){break c}Vi=Ui,Wi=Cn(Ye,Qi,Pi)+Pi|0,q[Vi>>2]=Wi}Pi=q[Ri>>2]+12|0;q[Ri>>2]=Pi;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+$i|0;Yi=Yi+1|0;if(Yi>>>0>2]){continue}break}Zi=q[ci+12>>2]}Yi=q[ci+28>>2];Yi=r[bj+84|0]?Yi:q[q[bj+68>>2]+(Yi<<2)>>2];if(Yi>>>0>=t[bj+80>>2]){break q}Xi=q[bj+40>>2];Cn(q[q[bj>>2]>>2]+w(Xi,Yi)|0,Zi,Xi);ej=ej+1|0;Yi=q[ci+16>>2];if(ej>>>0<(q[jj>>2]-Yi|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;cj=cj+1|0;if((cj|0)==(aj|0)){break f}Yi=q[Ye+12>>2];continue}}Yi=q[_i+28>>2]}if(Yi){continue}break}Zi=1}se(_i+8|0);Yi=q[_i+12>>2];Ye=q[_i+16>>2];s:{if((Yi|0)==(Ye|0)){break s}while(1){An(q[Yi>>2]);Yi=Yi+4|0;if((Ye|0)!=(Yi|0)){continue}break}Ye=q[_i+16>>2];Zh=q[_i+12>>2];if((Ye|0)==(Zh|0)){break s}q[_i+16>>2]=Ye+(((Ye-Zh|0)+ -4>>>2^-1)<<2)}Ye=q[_i+8>>2];if(Ye){An(Ye)}T=_i+32|0;return Zi}bn();F()}bn();F()}function ae(Ye,Zh,ci){var vj=0,wj=0,xj=0,yj=0,zj=0,Aj=0,Bj=0,Cj=0,Dj=0,Ej=0,Fj=0,Gj=0,Hj=0,Ij=0,Jj=0,Kj=0,Lj=0,Mj=0,Nj=0,Oj=0,Pj=0,Qj=0,Rj=0,Sj=0,Tj=0,Uj=0,Vj=0;yj=T-32|0;T=yj;vj=q[Ye+12>>2];q[yj+16>>2]=0;q[yj+8>>2]=0;q[yj+12>>2]=0;a:{if(vj){if(vj>>>0>=1073741824){break a}wj=vj<<2;xj=Mm(wj);q[yj+8>>2]=xj;q[yj+12>>2]=xj;q[yj+16>>2]=wj+xj;Aj=Dn(xj,0,wj);wj=vj;while(1){Aj=Aj+4|0;wj=wj+ -1|0;if(wj){continue}break}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Cj=vj+ -1|0;zj=Bj+Cj|0;xj=(zj>>>0)/341|0;xj=q[wj+(xj<<2)>>2]+w(zj-w(xj,341)|0,12)|0;Gj=q[xj+8>>2];zj=q[xj+4>>2];Fj=q[xj>>2];q[yj+28>>2]=Cj;xj=q[yj+16>>2];wj=xj-wj|0;if(((wj?w(wj>>2,341)+ -1|0:0)-(vj+Bj|0)|0)+1>>>0>=682){An(q[xj+ -4>>2]);q[yj+16>>2]=q[yj+16>>2]+ -4}wj=0;if(Fj>>>0>Zh>>>0){break d}xj=q[Oj>>2];Hj=w(Gj,12);Pj=Hj+q[Qj>>2]|0;Aj=ml(Ye,Pj,zj);if(Aj>>>0>=t[Ye+12>>2]){break d}Kj=xj+Hj|0;e:{Ij=Aj<<2;zj=q[Ye>>2]-q[Ij+q[Pj>>2]>>2]|0;if(!zj){if(!Fj){break e}Dj=0;while(1){zj=0;vj=q[ci+16>>2];f:{if((vj|0)==q[Lj>>2]){break f}while(1){vj=w(zj,20)+vj|0;xj=q[Kj>>2]+(q[vj+4>>2]<<2)|0;Ej=q[vj>>2];Aj=q[vj+12>>2];g:{if(Aj>>>0>3){break g}wj=q[ci+12>>2];Bj=vj+16|0;if(!q[Bj>>2]){xj=wj;break g}Cj=vj+12|0;vj=0;while(1){wj=Cn(wj,(vj<<2)+xj|0,Aj);Aj=q[Cj>>2];wj=wj+Aj|0;vj=vj+1|0;if(vj>>>0>2]){continue}break}xj=q[ci+12>>2]}vj=q[ci+28>>2];vj=r[Ej+84|0]?vj:q[q[Ej+68>>2]+(vj<<2)>>2];if(vj>>>0>=t[Ej+80>>2]){break f}wj=q[Ej+40>>2];Cn(q[q[Ej>>2]>>2]+w(wj,vj)|0,xj,wj);zj=zj+1|0;vj=q[ci+16>>2];if(zj>>>0<(q[Lj>>2]-vj|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Dj=Dj+1|0;if((Fj|0)!=(Dj|0)){continue}break}break e}h:{i:{j:{k:{if(Fj>>>0<=2){xj=q[Rj>>2];q[xj>>2]=Aj;wj=1;vj=q[Ye+12>>2];if(vj>>>0>1){break k}break h}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}wj=q[Oj>>2];Dj=Gj+1|0;Ej=w(Dj,12);xj=wj+Ej|0;if((xj|0)!=(Kj|0)){hd(xj,q[Kj>>2],q[Kj+4>>2]);wj=q[Oj>>2]}wj=Ij+q[wj+Ej>>2]|0;q[wj>>2]=q[wj>>2]+(1<>2]=0;eh(Uj,z(Fj)^31,yj+4|0);xj=(Fj>>>1)-q[yj+4>>2]|0;wj=Fj-xj|0;l:{if((wj|0)==(xj|0)){wj=xj;break l}Bj=q[Ye+84>>2];if((Bj|0)==q[Vj>>2]){break j}Cj=q[Bj>>2];vj=q[Ye+88>>2];zj=vj+1|0;q[Ye+88>>2]=zj;vj=Cj&-2147483648>>>vj;m:{if((zj|0)==32){q[Ye+88>>2]=0;q[Ye+84>>2]=Bj+4;if(vj){break m}break j}if(!vj){break j}}}zj=wj;wj=xj;break i}while(1){Aj=(vj+ -1|0)==(Aj|0)?0:Aj+1|0;q[xj+(wj<<2)>>2]=Aj;wj=wj+1|0;vj=q[Ye+12>>2];if(wj>>>0>>0){continue}break}break h}zj=xj}Bj=q[Qj>>2];Cj=Bj+Hj|0;vj=q[Cj>>2];xj=vj+Ij|0;q[xj>>2]=q[xj>>2]+1;hd(Bj+Ej|0,vj,q[Cj+4>>2]);if(wj){xj=q[yj+28>>2]+q[yj+24>>2]|0;Bj=q[yj+16>>2];vj=q[yj+12>>2];Cj=Bj-vj|0;if((xj|0)==((Cj?w(Cj>>2,341)+ -1|0:0)|0)){re(yj+8|0);vj=q[yj+12>>2];Bj=q[yj+16>>2];xj=q[yj+24>>2]+q[yj+28>>2]|0}if((vj|0)==(Bj|0)){xj=0}else{Bj=vj;vj=(xj>>>0)/341|0;xj=q[Bj+(vj<<2)>>2]+w(xj-w(vj,341)|0,12)|0}q[xj+8>>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+16>>2];o:{if((vj|0)==q[Lj>>2]){break o}while(1){vj=w(zj,20)+vj|0;xj=q[Sj>>2]+(q[vj+4>>2]<<2)|0;Dj=q[vj>>2];Aj=q[vj+12>>2];p:{if(Aj>>>0>3){break p}wj=q[ci+12>>2];Bj=vj+16|0;if(!q[Bj>>2]){xj=wj;break p}Cj=vj+12|0;vj=0;while(1){wj=Cn(wj,(vj<<2)+xj|0,Aj);Aj=q[Cj>>2];wj=wj+Aj|0;vj=vj+1|0;if(vj>>>0>2]){continue}break}xj=q[ci+12>>2]}vj=q[ci+28>>2];vj=r[Dj+84|0]?vj:q[q[Dj+68>>2]+(vj<<2)>>2];if(vj>>>0>=t[Dj+80>>2]){break o}wj=q[Dj+40>>2];Cn(q[q[Dj>>2]>>2]+w(wj,vj)|0,xj,wj);zj=zj+1|0;vj=q[ci+16>>2];if(zj>>>0<(q[Lj>>2]-vj|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Gj=Gj+1|0;if((Gj|0)==(Fj|0)){break e}vj=q[Ye+12>>2];continue}}vj=q[yj+28>>2];if(vj){continue}break}wj=1}se(yj+8|0);vj=q[yj+12>>2];Ye=q[yj+16>>2];q:{if((vj|0)==(Ye|0)){break q}while(1){An(q[vj>>2]);vj=vj+4|0;if((Ye|0)!=(vj|0)){continue}break}Zh=q[yj+16>>2];Ye=q[yj+12>>2];if((Zh|0)==(Ye|0)){break q}q[yj+16>>2]=Zh+(((Zh-Ye|0)+ -4>>>2^-1)<<2)}Ye=q[yj+8>>2];if(Ye){An(Ye)}T=yj+32|0;return wj}bn();F()}bn();F()}function be(Ye,Zh,ci){var Wj=0,Xj=0,Yj=0,Zj=0,_j=0,$j=0,ak=0,bk=0,ck=0,dk=0,ek=0,fk=0,gk=0,hk=0,ik=0,jk=0,kk=0,lk=0,mk=0,nk=0,ok=0,pk=0,qk=0,rk=0,sk=0,tk=0,uk=0;Zj=T-32|0;T=Zj;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];Wj=Wj+_j|0;Xj=Xj+1|0;if(Xj>>>0>2]){continue}break}Yj=q[ci+12>>2]}Xj=q[ci+28>>2];Xj=r[ak+84|0]?Xj:q[q[ak+68>>2]+(Xj<<2)>>2];if(Xj>>>0>=t[ak+80>>2]){break f}Wj=q[ak+40>>2];Cn(q[q[ak>>2]>>2]+w(Wj,Xj)|0,Yj,Wj);ck=ck+1|0;Xj=q[ci+16>>2];if(ck>>>0<(q[hk>>2]-Xj|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;bk=bk+1|0;if(($j|0)!=(bk|0)){continue}break}break e}h:{i:{j:{k:{if($j>>>0<=2){Yj=q[mk>>2];q[Yj>>2]=_j;Wj=1;Xj=q[Ye+12>>2];if(Xj>>>0>1){break k}break h}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}Yj=Wj;Wj=Xj+12|0;hd(Yj+Wj|0,q[ek>>2],q[ek+4>>2]);Wj=ak+q[Wj+q[kk>>2]>>2]|0;q[Wj>>2]=q[Wj>>2]+(1<>2]=0;eh(qk,z($j)^31,Zj+4|0);ek=ck+1|0;Wj=($j>>>1)-q[Zj+4>>2]|0;Yj=$j-Wj|0;l:{if((Yj|0)==(Wj|0)){Yj=Wj;break l}$j=q[Ye+84>>2];if(($j|0)==q[rk>>2]){break j}bk=q[$j>>2];dk=q[Ye+88>>2];fk=dk+1|0;q[Ye+88>>2]=fk;bk=bk&-2147483648>>>dk;m:{if((fk|0)==32){q[Ye+88>>2]=0;q[Ye+84>>2]=$j+4;if(bk){break m}break j}if(!bk){break j}}}$j=Yj;Yj=Wj;break i}while(1){_j=(Xj+ -1|0)==(_j|0)?0:_j+1|0;q[Yj+(Wj<<2)>>2]=_j;Wj=Wj+1|0;Xj=q[Ye+12>>2];if(Wj>>>0>>0){continue}break}break h}$j=Wj}bk=ak;Wj=q[lk>>2];Xj=Wj+Xj|0;ak=q[Xj>>2];bk=bk+ak|0;q[bk>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ye|0)){break q}while(1){An(q[Xj>>2]);Xj=Xj+4|0;if((Ye|0)!=(Xj|0)){continue}break}Ye=q[Zj+16>>2];Zh=q[Zj+12>>2];if((Ye|0)==(Zh|0)){break q}q[Zj+16>>2]=Ye+(((Ye-Zh|0)+ -4>>>2^-1)<<2)}Ye=q[Zj+8>>2];if(Ye){An(Ye)}T=Zj+32|0;return Yj}bn();F()}bn();F()}function ce(Ye,Zh,ci){var vk=0,wk=0,xk=0,yk=0,zk=0,Ak=0,Bk=0,Ck=0,Dk=0,Ek=0,Fk=0,Gk=0,Hk=0,Ik=0,Jk=0,Kk=0,Lk=0,Mk=0,Nk=0,Ok=0,Pk=0,Qk=0,Rk=0,Sk=0,Tk=0,Uk=0;yk=T-32|0;T=yk;vk=q[Ye+12>>2];q[yk+16>>2]=0;q[yk+8>>2]=0;q[yk+12>>2]=0;a:{if(vk){if(vk>>>0>=1073741824){break a}wk=vk<<2;xk=Mm(wk);q[yk+8>>2]=xk;q[yk+12>>2]=xk;q[yk+16>>2]=wk+xk;Ak=Dn(xk,0,wk);wk=vk;while(1){Ak=Ak+4|0;wk=wk+ -1|0;if(wk){continue}break}q[yk+12>>2]=Ak}wk=q[Ye+628>>2];zk=q[wk>>2];if(zk){q[wk+4>>2]=zk;An(zk);q[wk+8>>2]=0;q[wk>>2]=0;q[wk+4>>2]=0;vk=q[Ye+12>>2];Ak=q[yk+12>>2];xk=q[yk+8>>2]}q[wk>>2]=xk;q[wk+4>>2]=Ak;q[wk+8>>2]=q[yk+16>>2];Ak=0;q[yk+16>>2]=0;q[yk+8>>2]=0;q[yk+12>>2]=0;wk=0;b:{if(vk){if(vk>>>0>=1073741824){break b}xk=vk<<2;wk=Mm(xk);q[yk+8>>2]=wk;q[yk+12>>2]=wk;q[yk+16>>2]=wk+xk;Ak=Dn(wk,0,xk);while(1){Ak=Ak+4|0;vk=vk+ -1|0;if(vk){continue}break}q[yk+12>>2]=Ak}xk=q[Ye+640>>2];vk=q[xk>>2];if(vk){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(!vk){if(!zk){break f}Gk=0;while(1){Ck=0;vk=q[ci+16>>2];g:{if((vk|0)==q[Jk>>2]){break g}while(1){vk=w(Ck,20)+vk|0;xk=q[Dk>>2]+(q[vk+4>>2]<<2)|0;Bk=q[vk>>2];Ak=q[vk+12>>2];h:{if(Ak>>>0>3){break h}wk=q[ci+12>>2];Fk=vk+16|0;if(!q[Fk>>2]){xk=wk;break h}Ek=vk+12|0;vk=0;while(1){wk=Cn(wk,(vk<<2)+xk|0,Ak);Ak=q[Ek>>2];wk=wk+Ak|0;vk=vk+1|0;if(vk>>>0>2]){continue}break}xk=q[ci+12>>2]}vk=q[ci+28>>2];vk=r[Bk+84|0]?vk:q[q[Bk+68>>2]+(vk<<2)>>2];if(vk>>>0>=t[Bk+80>>2]){break g}wk=vk;vk=q[Bk+40>>2];Cn(q[q[Bk>>2]>>2]+w(wk,vk)|0,xk,vk);Ck=Ck+1|0;vk=q[ci+16>>2];if(Ck>>>0<(q[Jk>>2]-vk|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Gk=Gk+1|0;if((zk|0)!=(Gk|0)){continue}break}break f}i:{j:{k:{l:{if(zk>>>0<=2){xk=q[Nk>>2];q[xk>>2]=Ak;wk=1;vk=q[Ye+12>>2];if(vk>>>0>1){break l}break i}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}xk=q[Lk>>2];Ek=Ck+1|0;Gk=w(Ek,12);wk=xk+Gk|0;if((wk|0)!=(Dk|0)){hd(wk,q[Dk>>2],q[Dk+4>>2]);xk=q[Lk>>2]}xk=Fk+q[xk+Gk>>2]|0;q[xk>>2]=q[xk>>2]+(1<>>1)-wk|0;vk=zk-wk|0;m:{if((vk|0)==(wk|0)){vk=wk;break m}xk=q[Ye+596>>2];if((xk|0)==q[Rk>>2]){break k}zk=q[xk>>2];Dk=q[Ye+600>>2];Hk=Dk+1|0;q[Ye+600>>2]=Hk;zk=zk&-2147483648>>>Dk;n:{if((Hk|0)==32){q[Ye+600>>2]=0;q[Ye+596>>2]=xk+4;if(zk){break n}break k}if(!zk){break k}}}xk=vk;vk=wk;break j}while(1){Ak=(vk+ -1|0)==(Ak|0)?0:Ak+1|0;q[xk+(wk<<2)>>2]=Ak;wk=wk+1|0;vk=q[Ye+12>>2];if(wk>>>0>>0){continue}break}break i}xk=wk}wk=q[Mk>>2];zk=wk+Bk|0;Dk=q[zk>>2];Bk=Dk+Fk|0;q[Bk>>2]=q[Bk>>2]+1;hd(wk+Gk|0,Dk,q[zk+4>>2]);if(vk){Dk=q[yk+28>>2]+q[yk+24>>2]|0;Bk=q[yk+16>>2];wk=q[yk+12>>2];zk=Bk-wk|0;if((Dk|0)==((zk?w(zk>>2,341)+ -1|0:0)|0)){re(yk+8|0);Dk=q[yk+24>>2]+q[yk+28>>2]|0;Bk=q[yk+16>>2];wk=q[yk+12>>2]}zk=0;o:{if((wk|0)==(Bk|0)){break o}zk=wk;wk=(Dk>>>0)/341|0;zk=q[zk+(wk<<2)>>2]+w(Dk-w(wk,341)|0,12)|0}q[zk+8>>2]=Ck;q[zk+4>>2]=Ak;q[zk>>2]=vk;q[yk+28>>2]=q[yk+28>>2]+1}if(!xk){break f}wk=q[yk+28>>2]+q[yk+24>>2]|0;zk=q[yk+16>>2];vk=q[yk+12>>2];Ck=zk-vk|0;if((wk|0)==((Ck?w(Ck>>2,341)+ -1|0:0)|0)){re(yk+8|0);zk=q[yk+16>>2];wk=q[yk+24>>2]+q[yk+28>>2]|0;vk=q[yk+12>>2]}if((vk|0)==(zk|0)){vk=0}else{zk=vk;vk=(wk>>>0)/341|0;vk=q[zk+(vk<<2)>>2]+w(wk-w(vk,341)|0,12)|0}q[vk+8>>2]=Ek;q[vk+4>>2]=Ak;q[vk>>2]=xk;vk=q[yk+28>>2]+1|0;q[yk+28>>2]=vk;break e}if(!zk){break f}Fk=0;while(1){if(vk){Ak=q[Ok>>2];Hk=q[Nk>>2];Sk=q[Dk>>2];Tk=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16>>2];if(Ck>>>0<(q[Jk>>2]-vk|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Fk=Fk+1|0;if((Fk|0)==(zk|0)){break f}vk=q[Ye+12>>2];continue}}vk=q[yk+28>>2]}if(vk){continue}break}wk=1}se(yk+8|0);vk=q[yk+12>>2];Ye=q[yk+16>>2];s:{if((vk|0)==(Ye|0)){break s}while(1){An(q[vk>>2]);vk=vk+4|0;if((Ye|0)!=(vk|0)){continue}break}Ye=q[yk+16>>2];Zh=q[yk+12>>2];if((Ye|0)==(Zh|0)){break s}q[yk+16>>2]=Ye+(((Ye-Zh|0)+ -4>>>2^-1)<<2)}Ye=q[yk+8>>2];if(Ye){An(Ye)}T=yk+32|0;return wk}bn();F()}bn();F()}function de(q){ah(q);ah(q+16|0);ah(q+32|0);ah(q+48|0);ah(q- -64|0);ah(q+80|0);ah(q+96|0);ah(q+112|0);ah(q+128|0);ah(q+144|0);ah(q+160|0);ah(q+176|0);ah(q+192|0);ah(q+208|0);ah(q+224|0);ah(q+240|0);ah(q+256|0);ah(q+272|0);ah(q+288|0);ah(q+304|0);ah(q+320|0);ah(q+336|0);ah(q+352|0);ah(q+368|0);ah(q+384|0);ah(q+400|0);ah(q+416|0);ah(q+432|0);ah(q+448|0);ah(q+464|0);ah(q+480|0);ah(q+496|0)}function ee(Ye,Zh,ci){var Vk=0,Wk=0,Xk=0,Yk=0,Zk=0,_k=0,$k=0,al=0,bl=0,cl=0,dl=0,el=0,fl=0,gl=0,hl=0,il=0,jl=0,kl=0,ll=0,ml=0,nl=0,ol=0,pl=0,ql=0,rl=0,sl=0;Yk=T-32|0;T=Yk;Vk=q[Ye+12>>2];q[Yk+16>>2]=0;q[Yk+8>>2]=0;q[Yk+12>>2]=0;a:{if(Vk){if(Vk>>>0>=1073741824){break a}Wk=Vk<<2;Xk=Mm(Wk);q[Yk+8>>2]=Xk;q[Yk+12>>2]=Xk;q[Yk+16>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0>=t[al+80>>2]){break g}Wk=Vk;Vk=q[al+40>>2];Cn(q[q[al>>2]>>2]+w(Wk,Vk)|0,Xk,Vk);$k=$k+1|0;Vk=q[ci+16>>2];if($k>>>0<(q[gl>>2]-Vk|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;bl=bl+1|0;if((_k|0)!=(bl|0)){continue}break}break f}i:{j:{k:{l:{if(_k>>>0<=2){Xk=q[ll>>2];q[Xk>>2]=Zk;Wk=1;Vk=q[Ye+12>>2];if(Vk>>>0>1){break l}break i}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}Xk=$k+12|0;hd(Xk+Vk|0,q[dl>>2],q[dl+4>>2]);Xk=bl+q[Xk+q[jl>>2]>>2]|0;q[Xk>>2]=q[Xk>>2]+(1<>>1)-Wk|0;Vk=_k-Wk|0;m:{if((Vk|0)==(Wk|0)){Vk=Wk;break m}Xk=q[Ye+596>>2];if((Xk|0)==q[pl>>2]){break k}_k=q[Xk>>2];cl=q[Ye+600>>2];el=cl+1|0;q[Ye+600>>2]=el;_k=_k&-2147483648>>>cl;n:{if((el|0)==32){q[Ye+600>>2]=0;q[Ye+596>>2]=Xk+4;if(_k){break n}break k}if(!_k){break k}}}Xk=Vk;Vk=Wk;break j}while(1){Zk=(Vk+ -1|0)==(Zk|0)?0:Zk+1|0;q[Xk+(Wk<<2)>>2]=Zk;Wk=Wk+1|0;Vk=q[Ye+12>>2];if(Wk>>>0>>0){continue}break}break i}Xk=Wk}Wk=q[kl>>2];_k=Wk+$k|0;$k=q[_k>>2];bl=$k+bl|0;q[bl>>2]=q[bl>>2]+1;hd(Wk+w(dl,12)|0,$k,q[_k+4>>2]);if(Vk){$k=q[Yk+28>>2]+q[Yk+24>>2]|0;bl=q[Yk+16>>2];Wk=q[Yk+12>>2];_k=bl-Wk|0;if(($k|0)==((_k?w(_k>>2,341)+ -1|0:0)|0)){re(Yk+8|0);$k=q[Yk+24>>2]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ol;fl=Xk-fl|0;q[Ye+560>>2]=fl;q[Wk>>2]=q[cl+4>>2]>>>32-fl|sl<>>32-Xk}Xk=q[$k>>2]<<2;Wk=Xk+Zk|0;q[Wk>>2]=q[Wk>>2]|q[Xk+ql>>2];Vk=Vk+1|0;if(Vk>>>0>2]){continue}break}}$k=0;Vk=q[ci+16>>2];q:{if((Vk|0)==q[gl>>2]){break q}while(1){Vk=w($k,20)+Vk|0;Xk=q[ml>>2]+(q[Vk+4>>2]<<2)|0;al=q[Vk>>2];Zk=q[Vk+12>>2];r:{if(Zk>>>0>3){break r}Wk=q[ci+12>>2];cl=Vk+16|0;if(!q[cl>>2]){Xk=Wk;break r}il=Vk+12|0;Vk=0;while(1){Wk=Cn(Wk,(Vk<<2)+Xk|0,Zk);Zk=q[il>>2];Wk=Wk+Zk|0;Vk=Vk+1|0;if(Vk>>>0>2]){continue}break}Xk=q[ci+12>>2]}Vk=q[ci+28>>2];Vk=r[al+84|0]?Vk:q[q[al+68>>2]+(Vk<<2)>>2];if(Vk>>>0>=t[al+80>>2]){break q}Wk=Vk;Vk=q[al+40>>2];Cn(q[q[al>>2]>>2]+w(Wk,Vk)|0,Xk,Vk);$k=$k+1|0;Vk=q[ci+16>>2];if($k>>>0<(q[gl>>2]-Vk|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;bl=bl+1|0;if((bl|0)==(_k|0)){break f}Vk=q[Ye+12>>2];continue}}Vk=q[Yk+28>>2]}if(Vk){continue}break}Xk=1}se(Yk+8|0);Vk=q[Yk+12>>2];Ye=q[Yk+16>>2];s:{if((Vk|0)==(Ye|0)){break s}while(1){An(q[Vk>>2]);Vk=Vk+4|0;if((Ye|0)!=(Vk|0)){continue}break}Ye=q[Yk+16>>2];Zh=q[Yk+12>>2];if((Ye|0)==(Zh|0)){break s}q[Yk+16>>2]=Ye+(((Ye-Zh|0)+ -4>>>2^-1)<<2)}Ye=q[Yk+8>>2];if(Ye){An(Ye)}T=Yk+32|0;return Xk}bn();F()}bn();F()}function fe(Ye,Zh,ci){var tl=0,ul=0,vl=0,wl=0,xl=0,yl=0,zl=0,Al=0,Bl=0,Cl=0,Dl=0,El=0,Fl=0,Gl=0,Hl=0,Il=0,Jl=0,Kl=0,Ll=0,Ml=0,Nl=0,Ol=0,Pl=0,Ql=0,Rl=0,Sl=0;wl=T-32|0;T=wl;tl=q[Ye+12>>2];q[wl+16>>2]=0;q[wl+8>>2]=0;q[wl+12>>2]=0;a:{if(tl){if(tl>>>0>=1073741824){break a}ul=tl<<2;vl=Mm(ul);q[wl+8>>2]=vl;q[wl+12>>2]=vl;q[wl+16>>2]=ul+vl;yl=Dn(vl,0,ul);ul=tl;while(1){yl=yl+4|0;ul=ul+ -1|0;if(ul){continue}break}q[wl+12>>2]=yl}ul=q[Ye+628>>2];xl=q[ul>>2];if(xl){q[ul+4>>2]=xl;An(xl);q[ul+8>>2]=0;q[ul>>2]=0;q[ul+4>>2]=0;tl=q[Ye+12>>2];yl=q[wl+12>>2];vl=q[wl+8>>2]}q[ul>>2]=vl;q[ul+4>>2]=yl;q[ul+8>>2]=q[wl+16>>2];yl=0;q[wl+16>>2]=0;q[wl+8>>2]=0;q[wl+12>>2]=0;ul=0;b:{if(tl){if(tl>>>0>=1073741824){break b}vl=tl<<2;ul=Mm(vl);q[wl+8>>2]=ul;q[wl+12>>2]=ul;q[wl+16>>2]=ul+vl;yl=Dn(ul,0,vl);while(1){yl=yl+4|0;tl=tl+ -1|0;if(tl){continue}break}q[wl+12>>2]=yl}vl=q[Ye+640>>2];tl=q[vl>>2];if(tl){q[vl+4>>2]=tl;An(tl);q[vl+8>>2]=0;q[vl>>2]=0;q[vl+4>>2]=0;yl=q[wl+12>>2];ul=q[wl+8>>2]}q[vl>>2]=ul;q[vl+4>>2]=yl;q[vl+8>>2]=q[wl+16>>2];tl=wl+24|0;q[tl>>2]=0;q[tl+4>>2]=0;ul=wl+16|0;q[ul>>2]=0;q[ul+4>>2]=0;q[wl+8>>2]=0;q[wl+12>>2]=0;re(wl+8|0);xl=q[ul>>2];ul=q[wl+12>>2];vl=0;c:{if((xl|0)==(ul|0)){break c}vl=q[tl>>2]+q[wl+28>>2]|0;tl=(vl>>>0)/341|0;vl=q[ul+(tl<<2)>>2]+w(vl-w(tl,341)|0,12)|0}q[vl+4>>2]=0;q[vl+8>>2]=0;q[vl>>2]=Zh;ul=1;vl=q[wl+28>>2];tl=vl+1|0;q[wl+28>>2]=tl;d:{if(tl>>>0>>0){break d}Kl=Ye+640|0;Jl=Ye+628|0;Hl=ci+20|0;Ll=Ye+616|0;Ml=Ye+604|0;Il=Ye+556|0;Nl=Ye+548|0;Pl=Ye+588|0;while(1){Bl=q[wl+12>>2];ul=q[wl+24>>2];yl=tl+ -1|0;vl=ul+yl|0;xl=(vl>>>0)/341|0;vl=q[Bl+(xl<<2)>>2]+w(vl-w(xl,341)|0,12)|0;Al=q[vl+8>>2];xl=q[vl>>2];q[wl+28>>2]=yl;vl=q[wl+16>>2];yl=vl-Bl|0;if(((yl?w(yl>>2,341)+ -1|0:0)-(tl+ul|0)|0)+1>>>0>=682){An(q[vl+ -4>>2]);q[wl+16>>2]=q[wl+16>>2]+ -4}ul=0;if(xl>>>0>Zh>>>0){break d}vl=q[Jl>>2];zl=w(Al,12);Dl=zl+q[Kl>>2]|0;yl=nl(Ye,xl,Dl);if(yl>>>0>=t[Ye+12>>2]){break d}Bl=vl+zl|0;e:{f:{El=yl<<2;tl=q[Ye>>2]-q[El+q[Dl>>2]>>2]|0;if(!tl){if(!xl){break f}Dl=0;while(1){Al=0;tl=q[ci+16>>2];g:{if((tl|0)==q[Hl>>2]){break g}while(1){tl=w(Al,20)+tl|0;vl=q[Bl>>2]+(q[tl+4>>2]<<2)|0;zl=q[tl>>2];yl=q[tl+12>>2];h:{if(yl>>>0>3){break h}ul=q[ci+12>>2];El=tl+16|0;if(!q[El>>2]){vl=ul;break h}Cl=tl+12|0;tl=0;while(1){ul=Cn(ul,(tl<<2)+vl|0,yl);yl=q[Cl>>2];ul=ul+yl|0;tl=tl+1|0;if(tl>>>0>2]){continue}break}vl=q[ci+12>>2]}tl=q[ci+28>>2];tl=r[zl+84|0]?tl:q[q[zl+68>>2]+(tl<<2)>>2];if(tl>>>0>=t[zl+80>>2]){break g}ul=tl;tl=q[zl+40>>2];Cn(q[q[zl>>2]>>2]+w(ul,tl)|0,vl,tl);Al=Al+1|0;tl=q[ci+16>>2];if(Al>>>0<(q[Hl>>2]-tl|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;Dl=Dl+1|0;if((xl|0)!=(Dl|0)){continue}break}break f}i:{j:{k:{l:{if(xl>>>0<=2){vl=q[Ll>>2];q[vl>>2]=yl;ul=1;tl=q[Ye+12>>2];if(tl>>>0>1){break l}break i}if(t[Ye+8>>2]>t[Ye+4>>2]){break d}vl=q[Jl>>2];Cl=Al+1|0;Dl=w(Cl,12);ul=vl+Dl|0;if((ul|0)!=(Bl|0)){hd(ul,q[Bl>>2],q[Bl+4>>2]);vl=q[Jl>>2]}vl=El+q[vl+Dl>>2]|0;q[vl>>2]=q[vl>>2]+(1<>>1)-ul|0;tl=xl-ul|0;m:{if((tl|0)==(ul|0)){tl=ul;break m}vl=q[Ye+596>>2];if((vl|0)==q[Pl>>2]){break k}xl=q[vl>>2];Bl=q[Ye+600>>2];Fl=Bl+1|0;q[Ye+600>>2]=Fl;xl=xl&-2147483648>>>Bl;n:{if((Fl|0)==32){q[Ye+600>>2]=0;q[Ye+596>>2]=vl+4;if(xl){break n}break k}if(!xl){break k}}}vl=tl;tl=ul;break j}while(1){yl=(tl+ -1|0)==(yl|0)?0:yl+1|0;q[vl+(ul<<2)>>2]=yl;ul=ul+1|0;tl=q[Ye+12>>2];if(ul>>>0>>0){continue}break}break i}vl=ul}ul=q[Kl>>2];xl=ul+zl|0;Bl=q[xl>>2];zl=Bl+El|0;q[zl>>2]=q[zl>>2]+1;hd(ul+Dl|0,Bl,q[xl+4>>2]);if(tl){Bl=q[wl+28>>2]+q[wl+24>>2]|0;zl=q[wl+16>>2];ul=q[wl+12>>2];xl=zl-ul|0;if((Bl|0)==((xl?w(xl>>2,341)+ -1|0:0)|0)){re(wl+8|0);Bl=q[wl+24>>2]+q[wl+28>>2]|0;zl=q[wl+16>>2];ul=q[wl+12>>2]}xl=0;o:{if((ul|0)==(zl|0)){break o}xl=ul;ul=(Bl>>>0)/341|0;xl=q[xl+(ul<<2)>>2]+w(Bl-w(ul,341)|0,12)|0}q[xl+8>>2]=Al;q[xl+4>>2]=yl;q[xl>>2]=tl;q[wl+28>>2]=q[wl+28>>2]+1}if(!vl){break f}ul=q[wl+28>>2]+q[wl+24>>2]|0;xl=q[wl+16>>2];tl=q[wl+12>>2];Al=xl-tl|0;if((ul|0)==((Al?w(Al>>2,341)+ -1|0:0)|0)){re(wl+8|0);xl=q[wl+16>>2];ul=q[wl+24>>2]+q[wl+28>>2]|0;tl=q[wl+12>>2]}if((tl|0)==(xl|0)){tl=0}else{xl=tl;tl=(ul>>>0)/341|0;tl=q[xl+(tl<<2)>>2]+w(ul-w(tl,341)|0,12)|0}q[tl+8>>2]=Cl;q[tl+4>>2]=yl;q[tl>>2]=vl;tl=q[wl+28>>2]+1|0;q[wl+28>>2]=tl;break e}if(!xl){break f}El=0;while(1){if(tl){yl=q[Ml>>2];Fl=q[Ll>>2];Ql=q[Bl>>2];Rl=q[Dl>>2];tl=0;while(1){Al=Fl+(tl<<2)|0;q[yl+(q[Al>>2]<<2)>>2]=0;ul=q[Al>>2]<<2;vl=q[Ye>>2]-q[ul+Rl>>2]|0;p:{if(!vl){break p}ul=ul+yl|0;zl=q[Ye+560>>2];Gl=32-zl|0;if((vl|0)<=(Gl|0)){Cl=q[Il>>2];if((Cl|0)==q[Nl>>2]){q[ul>>2]=0;break p}q[ul>>2]=q[Cl>>2]<>>32-vl;vl=vl+q[Ye+560>>2]|0;q[Ye+560>>2]=vl;if((vl|0)!=32){break p}q[Ye+560>>2]=0;q[Il>>2]=Cl+4;break p}Cl=q[Il>>2];Ol=Cl+4|0;if((Ol|0)==q[Nl>>2]){q[ul>>2]=0;break p}Sl=q[Cl>>2];q[Il>>2]=Ol;Gl=vl-Gl|0;q[Ye+560>>2]=Gl;q[ul>>2]=q[Cl+4>>2]>>>32-Gl|Sl<>>32-vl}vl=q[Al>>2]<<2;ul=vl+yl|0;q[ul>>2]=q[ul>>2]|q[vl+Ql>>2];tl=tl+1|0;if(tl>>>0>2]){continue}break}}Al=0;tl=q[ci+16>>2];q:{if((tl|0)==q[Hl>>2]){break q}while(1){tl=w(Al,20)+tl|0;vl=q[Ml>>2]+(q[tl+4>>2]<<2)|0;zl=q[tl>>2];yl=q[tl+12>>2];r:{if(yl>>>0>3){break r}ul=q[ci+12>>2];Cl=tl+16|0;if(!q[Cl>>2]){vl=ul;break r}Fl=tl+12|0;tl=0;while(1){ul=Cn(ul,(tl<<2)+vl|0,yl);yl=q[Fl>>2];ul=ul+yl|0;tl=tl+1|0;if(tl>>>0>2]){continue}break}vl=q[ci+12>>2]}tl=q[ci+28>>2];tl=r[zl+84|0]?tl:q[q[zl+68>>2]+(tl<<2)>>2];if(tl>>>0>=t[zl+80>>2]){break q}ul=tl;tl=q[zl+40>>2];Cn(q[q[zl>>2]>>2]+w(ul,tl)|0,vl,tl);Al=Al+1|0;tl=q[ci+16>>2];if(Al>>>0<(q[Hl>>2]-tl|0)/20>>>0){continue}break}}q[ci+28>>2]=q[ci+28>>2]+1;q[Ye+8>>2]=q[Ye+8>>2]+1;El=El+1|0;if((El|0)==(xl|0)){break f}tl=q[Ye+12>>2];continue}}tl=q[wl+28>>2]}if(tl){continue}break}ul=1}se(wl+8|0);tl=q[wl+12>>2];Ye=q[wl+16>>2];s:{if((tl|0)==(Ye|0)){break s}while(1){An(q[tl>>2]);tl=tl+4|0;if((Ye|0)!=(tl|0)){continue}break}Ye=q[wl+16>>2];Zh=q[wl+12>>2];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0)<=(ci|0)?_l>>>0>=Wl>>>0?0:1:0){break h}Tl=bm+dm|0;Vl=r[Tl|0]|r[Tl+1|0]<<8|(r[Tl+2|0]<<16|r[Tl+3|0]<<24);q[Zh+16>>2]=Wl;q[Zh+20>>2]=ci;if(am){ci=0;while(1){Tl=n[q[q[Ye>>2]+20>>2]](Ye,ci)|0;Tl=q[q[q[(n[q[q[Ye>>2]+28>>2]](Ye)|0)+4>>2]+8>>2]+(Tl<<2)>>2];td(Tl,Vl);o[Tl+84|0]=1;q[Tl+72>>2]=q[Tl+68>>2];ci=ci+1|0;if((am|0)!=(ci|0)){continue}break}}Wl=1;Ye=Ld(Ul+672|0,Ul+704|0);k:{if(Zl>>>0>6){break k}l:{m:{switch(Zl-1|0){default:ci=Od(Ul+16|0,Xl);Zh=Md(ci,Zh,Ye);Nd(ci);if(Zh){break l}break k;case 0:ci=Od(Ul+16|0,Xl);Zh=Pd(ci,Zh,Ye);Nd(ci);if(Zh){break l}break k;case 1:ci=Sd(Ul+16|0,Xl);Zh=Qd(ci,Zh,Ye);Rd(ci);if(Zh){break l}break k;case 2:ci=Sd(Ul+16|0,Xl);Zh=Td(ci,Zh,Ye);Rd(ci);if(Zh){break l}break k;case 3:ci=Wd(Ul+16|0,Xl);Zh=Ud(ci,Zh,Ye);Vd(ci);if(Zh){break l}break k;case 4:ci=Wd(Ul+16|0,Xl);Zh=Xd(ci,Zh,Ye);Vd(ci);if(Zh){break l}break k;case 5:break m}}ci=Wd(Ul+16|0,Xl);Zh=Yd(ci,Zh,Ye);Vd(ci);if(!Zh){break k}}Wl=0}Zh=q[Ye+16>>2];if(Zh){q[Ye+20>>2]=Zh;An(Zh)}Zh=q[Ye>>2];if(Zh){q[Ye+4>>2]=Zh;An(Zh)}if(Wl){break h}}gm=1}Ye=q[Ul+704>>2];if(!Ye){break a}q[Ul+708>>2]=Ye;An(Ye);break a}bn();F()}bn();F()}Ye=q[Ul+672>>2];if(!Ye){break a}q[Ul+676>>2]=Ye;An(Ye)}T=Ul+720|0;return gm|0}function he(Ye,Zh,Yl){var km=0,lm=0,mm=0,nm=0;a:{if(Ye>>>0>5){break a}mm=q[Yl+16>>2];km=q[Yl+12>>2];lm=q[Yl+20>>2];if((km|0)<(lm|0)?1:(km|0)<=(lm|0)?t[Yl+8>>2]>mm>>>0?0:1:0){break a}km=r[mm+q[Yl>>2]|0];mm=mm+1|0;if(mm>>>0<1){lm=lm+1|0}q[Yl+16>>2]=mm;q[Yl+20>>2]=lm;lm=Zh;if(km&128){if(!he(Ye+1|0,Zh,Yl)){break a}Ye=q[Zh>>2]<<7;q[Zh>>2]=Ye;km=Ye|km&127}q[lm>>2]=km;nm=1}return nm}function ie(Ye,Zh){var Yl=0,om=0,pm=0,qm=0,rm=0,sm=0,tm=0;a:{b:{c:{om=q[Ye>>2];rm=(q[Ye+4>>2]-om|0)/24|0;Yl=rm+1|0;if(Yl>>>0<178956971){om=(q[Ye+8>>2]-om|0)/24|0;sm=om<<1;om=om>>>0<89478485?sm>>>0>>0?Yl:sm:178956970;pm=0;d:{if(!om){break d}if(om>>>0>=178956971){break c}pm=Mm(w(om,24))}Yl=pm+w(rm,24)|0;ve(Yl,Zh);rm=pm+w(om,24)|0;sm=Yl+24|0;Zh=q[Ye+4>>2];pm=q[Ye>>2];if((Zh|0)==(pm|0)){break b}while(1){Yl=Yl+ -24|0;q[Yl>>2]=1232;om=q[Zh+ -20>>2];qm=Yl+16|0;q[qm>>2]=0;q[Yl+8>>2]=0;q[Yl+12>>2]=0;q[Yl+4>>2]=om;om=Zh+ -16|0;q[Yl+8>>2]=q[om>>2];q[Yl+12>>2]=q[Zh+ -12>>2];tm=qm;qm=Zh+ -8|0;q[tm>>2]=q[qm>>2];q[qm>>2]=0;q[om>>2]=0;q[om+4>>2]=0;q[Yl+20>>2]=q[Zh+ -4>>2];Zh=Zh+ -24|0;if((pm|0)!=(Zh|0)){continue}break}pm=q[Ye+4>>2];Zh=q[Ye>>2];break a}bn();F()}ab(1780);F()}Zh=pm}q[Ye>>2]=Yl;q[Ye+8>>2]=rm;q[Ye+4>>2]=sm;if((Zh|0)!=(pm|0)){while(1){pm=pm+ -24|0;n[q[q[pm>>2]>>2]](pm)|0;if((Zh|0)!=(pm|0)){continue}break}}if(Zh){An(Zh)}}function je(Ye,Zh,um){var vm=0,wm=0,xm=0,ym=0,zm=0,Am=0,Bm=0,Cm=0,Dm=0,Em=0;wm=T-32|0;T=wm;q[wm+24>>2]=0;q[wm+16>>2]=0;q[wm+20>>2]=0;zm=q[Zh+12>>2];xm=zm;ym=q[Zh+20>>2];Am=ym;Bm=q[Zh+16>>2];vm=Bm+4|0;if(vm>>>0<4){ym=ym+1|0}Dm=q[Zh+8>>2];Cm=vm;a:{if((xm|0)<(ym|0)?1:(xm|0)<=(ym|0)?Dm>>>0>=vm>>>0?0:1:0){break a}xm=q[Zh>>2];vm=Bm+xm|0;vm=r[vm|0]|r[vm+1|0]<<8|(r[vm+2|0]<<16|r[vm+3|0]<<24);q[Zh+16>>2]=Cm;q[Zh+20>>2]=ym;b:{c:{vm=vm+ -2|0;if(vm>>>0<=1){if(vm-1){break c}if((zm|0)<(ym|0)?1:(zm|0)<=(ym|0)?Dm>>>0>Cm>>>0?0:1:0){break a}xm=o[xm+Cm|0];vm=Bm+5|0;if(vm>>>0<5){Am=Am+1|0}q[Zh+16>>2]=vm;q[Zh+20>>2]=Am;q[Ye+8>>2]=xm;if((xm|0)==1){if(ol(Ye,Zh,wm+16|0)){break b}break a}Gl(1848,23,q[3794]);break a}Gl(1872,24,q[3794]);break a}if(!ol(Ye,Zh,wm+16|0)){break a}}q[wm+8>>2]=q[wm+16>>2];q[wm>>2]=q[wm+20>>2];ke(wm+8|0,wm,Ye,um);Em=1}Ye=q[wm+16>>2];if(Ye){q[wm+20>>2]=Ye;An(Ye)}T=wm+32|0;return Em}function ke(Ye,Zh,um,Fm){var Gm=0,Hm=0,Im=0,Jm=x(0),Km=0,Lm=0,Mm=0,Nm=0;Gm=T-32|0;T=Gm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>2]=um;Pm=Zh+um|0;q[Om+24>>2]=Pm;Dn(um,0,Zh);q[Om+20>>2]=Pm;um=r[Fm|0]}q[Om+8>>2]=0;q[Om>>2]=0;q[Om+4>>2]=0;if(um&255){Zh=um<<24>>24;if((Zh|0)<=-1){break a}Zh=Zh<<2;um=Mm(Zh);q[Om>>2]=um;Pm=Zh+um|0;q[Om+8>>2]=Pm;Dn(um,0,Zh);q[Om+4>>2]=Pm}Zh=q[Sm>>2]+ -1|0;h:{i:{if(Zh>>>0>4){break i}j:{switch(Zh-1|0){case 3:Zh=1;if(me(Ye,Qm,Wm)){break i}break h;case 1:Zh=1;if(ne(Ye,Qm,Wm)){break i}break h;case 0:case 2:break i;default:break j}}Zh=1;if(!oe(Ye,Qm,Wm)){break h}}Wm=o[Fm|0]+Wm|0;Zh=0}Fm=q[Om>>2];if(Fm){q[Om+4>>2]=Fm;An(Fm)}Fm=q[Om+16>>2];if(Fm){q[Om+20>>2]=Fm;An(Fm)}if(!Zh){break f}break d;case 0:case 2:case 4:case 5:case 6:break f;case 7:break g}}Sm=q[q[Zm>>2]+(Rm<<2)>>2];Vm=q[_m>>2];Zh=n[q[q[Ye>>2]+28>>2]](Ye)|0;Pm=q[Qm+56>>2];Tm=q[Zh+40>>2];Zh=Mm(32);q[Om+16>>2]=Zh;q[Om+20>>2]=24;q[Om+24>>2]=-2147483616;o[Zh+24|0]=0;Fm=r[1726]|r[1727]<<8|(r[1728]<<16|r[1729]<<24);um=r[1722]|r[1723]<<8|(r[1724]<<16|r[1725]<<24);o[Zh+16|0]=um;o[Zh+17|0]=um>>>8;o[Zh+18|0]=um>>>16;o[Zh+19|0]=um>>>24;o[Zh+20|0]=Fm;o[Zh+21|0]=Fm>>>8;o[Zh+22|0]=Fm>>>16;o[Zh+23|0]=Fm>>>24;Fm=r[1718]|r[1719]<<8|(r[1720]<<16|r[1721]<<24);um=r[1714]|r[1715]<<8|(r[1716]<<16|r[1717]<<24);o[Zh+8|0]=um;o[Zh+9|0]=um>>>8;o[Zh+10|0]=um>>>16;o[Zh+11|0]=um>>>24;o[Zh+12|0]=Fm;o[Zh+13|0]=Fm>>>8;o[Zh+14|0]=Fm>>>16;o[Zh+15|0]=Fm>>>24;Fm=r[1710]|r[1711]<<8|(r[1712]<<16|r[1713]<<24);um=r[1706]|r[1707]<<8|(r[1708]<<16|r[1709]<<24);o[Zh|0]=um;o[Zh+1|0]=um>>>8;o[Zh+2|0]=um>>>16;o[Zh+3|0]=um>>>24;o[Zh+4|0]=Fm;o[Zh+5|0]=Fm>>>8;o[Zh+6|0]=Fm>>>16;o[Zh+7|0]=Fm>>>24;k:{l:{Fm=Tm+16|0;um=Fm;Zh=q[um>>2];if(!Zh){break l}while(1){Um=q[Zh+16>>2]<(Pm|0);um=Um?um:Zh;Zh=q[(Um<<2)+Zh>>2];if(Zh){continue}break}if((um|0)==(Fm|0)|(Pm|0)>2]){break l}Zh=um+20|0;if(!ga(Zh,Om+16|0)){break l}Zh=gk(Zh,Om+16|0);break k}Zh=gk(Tm,Om+16|0)}if(o[Om+27|0]<=-1){An(q[Om+16>>2])}Fm=Rm+1|0;m:{if(Zh){ud(Qm,Sm);break m}Zh=Vm+w(Rm,24)|0;um=q[Zh+4>>2];Rm=o[Qm+24|0];Vm=Rm<<2;Pm=Mm((Rm|0)!=(Rm&1073741823)?-1:Vm);if(!ik(hk(Om+16|0),u[Zh+20>>2],-1<>2]){$m=q[q[Sm>>2]>>2]+q[Sm+48>>2]|0;an=Zh+8|0;Um=0;Tm=0;um=0;while(1){if((Rm|0)>=1){cn=q[an>>2];Zh=0;dn=u[Om+16>>2];while(1){Ym=Zh<<2;u[Ym+Pm>>2]=x(dn*x(q[$m+(um<<2)>>2]))+u[cn+Ym>>2];um=um+1|0;Zh=Zh+1|0;if((Rm|0)!=(Zh|0)){continue}break}}Cn(q[q[Qm- -64>>2]>>2]+Tm|0,Pm,Vm);Tm=Tm+Vm|0;Um=Um+1|0;if(Um>>>0>2]){continue}break}}An(Pm)}Rm=Fm}Zh=1;Xm=Xm+1|0;if((Xm|0)<(n[q[q[Ye>>2]+24>>2]](Ye)|0)){continue}break c}break}An(Pm)}Zh=0}T=Om+32|0;return Zh|0}bn();F()}bn();F()}function me(Ye,en,fn){var gn=0,hn=0,jn=0,kn=0,ln=0,mn=0,nn=0,on=0,pn=0,qn=0,rn=0,sn=0,tn=0,un=0,vn=0;hn=T-16|0;T=hn;gn=o[en+24|0];q[hn+8>>2]=0;q[hn>>2]=0;q[hn+4>>2]=0;a:{b:{if(gn){if((gn|0)<=-1){break b}jn=gn<<2;kn=Mm(jn);q[hn>>2]=kn;ln=jn+kn|0;q[hn+8>>2]=ln;Dn(kn,0,jn);q[hn+4>>2]=ln;pn=Mm(jn);jn=Dn(pn,0,jn)}else{jn=0}if(!q[en+80>>2]){break a}sn=en+40|0;un=en+48|0;vn=Ye+48|0;while(1){tn=q[en>>2];mn=q[tn>>2];qn=q[un>>2];Ye=q[sn>>2];ln=$n(Ye,q[sn+4>>2],rn,nn);on=mn;mn=ln+qn|0;ln=Cn(kn,on+mn|0,Ye);if(gn<<24>>24>=1){mn=gn&255;qn=q[vn>>2];gn=0;while(1){on=gn<<2;q[on+jn>>2]=q[(fn+gn<<2)+qn>>2]+q[ln+on>>2];gn=gn+1|0;if(gn>>>0>>0){continue}break}}Cn(q[tn>>2]+w(Ye,rn)|0,pn,Ye);Ye=rn+1|0;if(Ye>>>0<1){nn=nn+1|0}rn=Ye;if(!nn&Ye>>>0>=t[en+80>>2]|nn>>>0>0){break a}gn=r[en+24|0];continue}}bn();F()}if(jn){An(pn)}if(kn){q[hn+4>>2]=kn;An(kn)}T=hn+16|0;return 1}function ne(Ye,en,fn){var wn=0,xn=0,yn=0,zn=0,Bn=0,En=0,Fn=0,Gn=0,Hn=0,In=0,Jn=0,Kn=0,Ln=0,Mn=0,Nn=0;xn=T-16|0;T=xn;wn=o[en+24|0];q[xn+8>>2]=0;q[xn>>2]=0;q[xn+4>>2]=0;a:{b:{if(wn){if((wn|0)<=-1){break b}yn=wn<<1;zn=Mm(yn);q[xn>>2]=zn;Bn=yn+zn|0;q[xn+8>>2]=Bn;Dn(zn,0,yn);q[xn+4>>2]=Bn;Hn=Mm(yn);yn=Dn(Hn,0,yn)}else{yn=0}if(!q[en+80>>2]){break a}Kn=en+40|0;Mn=en+48|0;Nn=Ye+48|0;while(1){Ln=q[en>>2];En=q[Ln>>2];In=q[Mn>>2];Ye=q[Kn>>2];Bn=$n(Ye,q[Kn+4>>2],Jn,Fn);Gn=En;En=Bn+In|0;Bn=Cn(zn,Gn+En|0,Ye);if(wn<<24>>24>=1){En=wn&255;In=q[Nn>>2];wn=0;while(1){Gn=wn<<1;p[Gn+yn>>1]=s[Bn+Gn>>1]+s[(fn+wn<<2)+In>>1];wn=wn+1|0;if(wn>>>0>>0){continue}break}}Cn(q[Ln>>2]+w(Ye,Jn)|0,Hn,Ye);Ye=Jn+1|0;if(Ye>>>0<1){Fn=Fn+1|0}Jn=Ye;if(!Fn&Ye>>>0>=t[en+80>>2]|Fn>>>0>0){break a}wn=r[en+24|0];continue}}bn();F()}if(yn){An(Hn)}if(zn){q[xn+4>>2]=zn;An(zn)}T=xn+16|0;return 1}function oe(Ye,en,fn){var Dn=0,On=0,Pn=0,Qn=0,Rn=0,Sn=0,Tn=0,Un=0,Vn=0,Wn=0;On=T-32|0;T=On;Dn=o[en+24|0];q[On+24>>2]=0;q[On+16>>2]=0;q[On+20>>2]=0;a:{b:{c:{if(Dn){if((Dn|0)<=-1){break c}Pn=Mm(Dn);q[On+16>>2]=Pn;q[On+20>>2]=Pn;q[On+24>>2]=Dn+Pn;while(1){o[Pn|0]=0;Pn=q[On+20>>2]+1|0;q[On+20>>2]=Pn;Dn=Dn+ -1|0;if(Dn){continue}break}Pn=r[en+24|0]}q[On+8>>2]=0;q[On>>2]=0;q[On+4>>2]=0;if(Pn&255){if(Pn<<24>>24<=-1){break b}Pn=Pn<<24>>24;Dn=Mm(Pn);q[On>>2]=Dn;q[On+4>>2]=Dn;q[On+8>>2]=Dn+Pn;while(1){o[Dn|0]=0;Dn=q[On+4>>2]+1|0;q[On+4>>2]=Dn;Pn=Pn+ -1|0;if(Pn){continue}break}}if(!q[en+80>>2]){Dn=q[On>>2];break a}Pn=en+40|0;Un=en+48|0;Tn=en+24|0;while(1){Vn=q[On+16>>2];Wn=q[q[en>>2]>>2];Dn=q[Pn>>2];Qn=q[Un>>2]+$n(Dn,q[Pn+4>>2],Rn,Sn)|0;Dn=Cn(Vn,Wn+Qn|0,Dn);d:{if(o[Tn|0]<1){break d}Qn=Ye+48|0;o[q[On>>2]]=r[Dn|0]+r[q[Qn>>2]+(fn<<2)|0];Dn=1;if(o[Tn|0]<2){break d}while(1){o[q[On>>2]+Dn|0]=r[q[On+16>>2]+Dn|0]+r[q[Qn>>2]+(fn+Dn<<2)|0];Dn=Dn+1|0;if((Dn|0)>2];Dn=q[On>>2];Cn(q[q[en>>2]>>2]+w(Qn,Rn)|0,Dn,Qn);Rn=Rn+1|0;if(Rn>>>0<1){Sn=Sn+1|0}Qn=Rn;if(!Sn&Qn>>>0>2]|Sn>>>0<0){continue}break}break a}bn();F()}bn();F()}if(Dn){q[On+4>>2]=Dn;An(Dn)}Ye=q[On+16>>2];if(Ye){q[On+20>>2]=Ye;An(Ye)}T=On+32|0;return 1}function pe(Ye){Ye=Ye|0;var bn=0,en=0,fn=0,Cn=0;q[Ye>>2]=1596;bn=q[Ye+60>>2];if(bn){Cn=Ye- -64|0;en=q[Cn>>2];fn=bn;a:{if((bn|0)==(en|0)){break a}while(1){en=en+ -4|0;fn=q[en>>2];q[en>>2]=0;if(fn){Hb(fn)}if((bn|0)!=(en|0)){continue}break}fn=q[Ye+60>>2]}q[Cn>>2]=bn;An(fn)}bn=q[Ye+48>>2];if(bn){q[Ye+52>>2]=bn;An(bn)}bn=q[Ye+36>>2];if(bn){Cn=Ye+40|0;en=q[Cn>>2];fn=bn;b:{if((bn|0)==(en|0)){break b}while(1){en=en+ -24|0;n[q[q[en>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te(ao+8|0,ao+4|0);Yn=q[Ye+8>>2];Xn=Ye+4|0;while(1){$n=q[Xn>>2];if(($n|0)==(Yn|0)){Zn=q[Ye>>2];q[Ye>>2]=q[ao+8>>2];q[ao+8>>2]=Zn;q[Ye+4>>2]=q[ao+12>>2];q[ao+12>>2]=$n;_n=Ye+8|0;Xn=q[_n>>2];q[_n>>2]=q[ao+16>>2];q[ao+16>>2]=Xn;Ye=Ye+12|0;_n=q[Ye>>2];q[Ye>>2]=q[ao+20>>2];q[ao+20>>2]=_n;if((Xn|0)!=(Yn|0)){q[ao+16>>2]=Xn+(((Xn-$n|0)+ -4>>>2^-1)<<2)}if(!Zn){break a}An(Zn);break a}else{Yn=Yn+ -4|0;ue(ao+8|0,Yn);continue}}}ab(1780);F()}ab(1780);F()}ab(1780);F()}T=ao+32|0}function se(Ye){var io=0,jo=0,ko=0,lo=0,mo=0,no=0,oo=0;jo=q[Ye+16>>2];io=(jo>>>0)/341|0;ko=q[Ye+4>>2];no=q[Ye+8>>2];a:{if((ko|0)==(no|0)){mo=Ye+20|0;break a}lo=(io<<2)+ko|0;io=q[lo>>2]+w(jo-w(io,341)|0,12)|0;mo=Ye+20|0;jo=jo+q[mo>>2]|0;oo=(jo>>>0)/341|0;jo=q[(oo<<2)+ko>>2]+w(jo-w(oo,341)|0,12)|0;if((io|0)==(jo|0)){break a}while(1){io=io+12|0;if((io-q[lo>>2]|0)==4092){io=q[lo+4>>2];lo=lo+4|0}if((io|0)!=(jo|0)){continue}break}}q[mo>>2]=0;io=no-ko>>2;if(io>>>0>2){while(1){An(q[ko>>2]);ko=q[Ye+4>>2]+4|0;q[Ye+4>>2]=ko;io=q[Ye+8>>2]-ko>>2;if(io>>>0>2){continue}break}}io=io+ -1|0;if(io>>>0<=1){q[Ye+16>>2]=io-1|0?170:341}}function te(Ye,po){var qo=0,ro=0,so=0,to=0,uo=0,vo=0,wo=0;a:{so=q[Ye+8>>2];qo=q[Ye+12>>2];b:{if((so|0)!=(qo|0)){qo=so;break b}ro=q[Ye+4>>2];to=q[Ye>>2];if(ro>>>0>to>>>0){so=so-ro|0;vo=so>>2;to=((ro-to>>2)+1|0)/-2<<2;uo=to+ro|0;qo=Ye;if(so){En(uo,ro,so);ro=q[Ye+4>>2]}q[qo+4>>2]=ro+to;qo=uo+(vo<<2)|0;q[Ye+8>>2]=qo;break b}qo=qo-to|0;qo=qo?qo>>1:1;if(qo>>>0>=1073741824){break a}uo=qo<<2;vo=Mm(uo);wo=uo+vo|0;uo=vo+(qo&-4)|0;qo=uo;if((ro|0)!=(so|0)){qo=uo;while(1){q[qo>>2]=q[ro>>2];qo=qo+4|0;ro=ro+4|0;if((so|0)!=(ro|0)){continue}break}to=q[Ye>>2]}q[Ye+8>>2]=qo;q[Ye+4>>2]=uo;q[Ye>>2]=vo;q[Ye+12>>2]=wo;if(!to){break b}An(to);qo=q[Ye+8>>2]}q[qo>>2]=q[po>>2];q[Ye+8>>2]=q[Ye+8>>2]+4;return}ab(1780);F()}function ue(Ye,po){var xo=0,yo=0,zo=0,Ao=0,Bo=0,Co=0;a:{zo=q[Ye+4>>2];yo=q[Ye>>2];b:{if((zo|0)!=(yo|0)){xo=zo;break b}Ao=q[Ye+8>>2];xo=q[Ye+12>>2];if(Ao>>>0>>0){Bo=((xo-Ao>>2)+1|0)/2<<2;xo=Bo+Ao|0;yo=Ao-zo|0;if(yo){xo=xo-yo|0;En(xo,zo,yo);Ao=q[Ye+8>>2]}q[Ye+4>>2]=xo;q[Ye+8>>2]=Ao+Bo;break b}xo=xo-yo|0;xo=xo?xo>>1:1;if(xo>>>0>=1073741824){break a}yo=xo<<2;Bo=Mm(yo);Co=yo+Bo|0;xo=Bo+(xo+3&-4)|0;c:{if((zo|0)==(Ao|0)){yo=xo;break c}yo=xo;while(1){q[yo>>2]=q[zo>>2];yo=yo+4|0;zo=zo+4|0;if((Ao|0)!=(zo|0)){continue}break}zo=q[Ye>>2]}q[Ye+8>>2]=yo;q[Ye+4>>2]=xo;q[Ye>>2]=Bo;q[Ye+12>>2]=Co;if(!zo){break b}An(zo);xo=q[Ye+4>>2]}q[xo+ -4>>2]=q[po>>2];q[Ye+4>>2]=q[Ye+4>>2]+ -4;return}ab(1780);F()}function ve(Ye,An){var po=0,Do=0,Eo=0,Fo=0,Go=0,Ho=0;q[Ye>>2]=1232;po=q[An+4>>2];q[Ye+16>>2]=0;q[Ye+8>>2]=0;q[Ye+12>>2]=0;q[Ye+4>>2]=po;a:{po=q[An+12>>2]-q[An+8>>2]|0;b:{if(!po){break b}Do=po>>2;if(Do>>>0>=1073741824){break a}po=Mm(po);q[Ye+8>>2]=po;Eo=Ye+12|0;q[Eo>>2]=po;q[Ye+16>>2]=po+(Do<<2);Fo=q[An+8>>2];Do=q[An+12>>2]-Fo|0;if((Do|0)<1){break b}Go=Eo,Ho=Cn(po,Fo,Do)+Do|0,q[Go>>2]=Ho}q[Ye+20>>2]=q[An+20>>2];return}bn();F()}function we(Ye){q[Ye+12>>2]=-1;q[Ye+16>>2]=0;q[Ye+4>>2]=0;q[Ye+8>>2]=0;q[Ye>>2]=1908}function xe(Ye,An,Io){Ye=Ye|0;An=An|0;Io=Io|0;q[Ye+4>>2]=An;An=q[q[q[An+4>>2]+8>>2]+(Io<<2)>>2];q[Ye+12>>2]=Io;q[Ye+8>>2]=An;return 1}function ye(Ye,An){Ye=Ye|0;An=An|0;q[Ye+12>>2]=-1;q[Ye+8>>2]=An;return 1}function ze(Ye,An,Io){Ye=Ye|0;An=An|0;Io=Io|0;var Jo=0,Ko=0;Jo=q[Ye+8>>2];a:{if(o[Jo+24|0]<1){break a}if(!td(Jo,q[An+4>>2]-q[An>>2]>>2)){break a}Ko=n[q[q[Ye>>2]+32>>2]](Ye,An,Io)|0}return Ko|0}function Ae(q,Ye,An){q=q|0;Ye=Ye|0;An=An|0;return 1}function Be(Ye){var An=0,Io=0,Lo=0,Mo=0,No=0,Oo=0,Po=0,Qo=0;a:{Lo=q[Ye+8>>2];if(r[Lo+84|0]){break a}An=q[Ye+16>>2];if(!An|!r[An+84|0]){break a}Io=q[Lo+72>>2];Mo=q[Lo+68>>2];o[An+84|0]=0;Io=Io-Mo>>2;No=q[An+68>>2];Mo=q[An+72>>2]-No>>2;b:{if(Io>>>0>Mo>>>0){md(An+68|0,Io-Mo|0,1992);Lo=q[Ye+8>>2];break b}if(Io>>>0>=Mo>>>0){break b}q[An+72>>2]=No+(Io<<2)}An=0;Mo=r[Lo+84|0];Oo=Lo+72|0;Po=Ye+16|0;Qo=Lo+68|0;while(1){if(An>>>0>=(Mo?0:q[Oo>>2]-q[Lo+68>>2]>>2)>>>0){break a}Io=An;No=q[q[Po>>2]+68>>2]+(An<<2)|0;if(!Mo){Io=q[q[Qo>>2]+(An<<2)>>2]}q[No>>2]=Io;An=An+1|0;continue}}return q[Ye+16>>2]}function Ce(Ye,Ro){Ye=Ye|0;Ro=Ro|0;var So=0,To=0,Uo=0;if((n[q[q[Ro>>2]+20>>2]](Ro)|0)>=1){while(1){So=bl(q[q[Ye+4>>2]+4>>2],n[q[q[Ro>>2]+24>>2]](Ro,To)|0);if((So|0)==-1){return 0}a:{Uo=q[Ye+4>>2];if(r[Uo+36|0]<=1){if(n[q[q[Ro>>2]+28>>2]](Ro,q[q[q[Uo+4>>2]+8>>2]+(So<<2)>>2])){break a}return 0}So=Pj(Uo,So);if(!So){return 0}if(n[q[q[Ro>>2]+28>>2]](Ro,So)){break a}return 0}To=To+1|0;if((To|0)<(n[q[q[Ro>>2]+20>>2]](Ro)|0)){continue}break}}return 1}function De(Ye,Ro,Vo){Ye=Ye|0;Ro=Ro|0;Vo=Vo|0;var Wo=0,Xo=0,Yo=0,Zo=0,_o=0,$o=0,ap=0,bp=0,cp=0,dp=0,ep=0;Wo=q[Ro+4>>2];Xo=q[Ro>>2];Ro=q[q[Ye+8>>2]+40>>2];Yo=Ro;Zo=Mm((Ro|0)>-1?Ro:-1);Wo=Wo-Xo|0;if((Wo|0)>=1){dp=Wo>>2;while(1){$o=q[Vo+12>>2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){continue}break}}q[Ye+40>>2]=ip}op=1;if((mp|0)<1){break a}op=0;jp=0;while(1){kp=q[fp+16>>2];ip=q[fp+12>>2];hp=q[fp+20>>2];if((ip|0)<(hp|0)?1:(ip|0)<=(hp|0)?t[fp+8>>2]>kp>>>0?0:1:0){break a}np=r[kp+q[fp>>2]|0];kp=kp+1|0;if(kp>>>0<1){hp=hp+1|0}ip=fp;q[ip+16>>2]=kp;q[ip+20>>2]=hp;n[q[q[Ye>>2]+48>>2]](lp+8|0,Ye,np);hp=q[Ye+36>>2];ip=q[lp+8>>2];q[lp+8>>2]=0;kp=jp<<2;np=hp+kp|0;hp=q[np>>2];q[np>>2]=ip;if(hp){n[q[q[hp>>2]+4>>2]](hp)}hp=q[lp+8>>2];q[lp+8>>2]=0;if(hp){n[q[q[hp>>2]+4>>2]](hp)}hp=q[q[pp>>2]+kp>>2];if(!hp){break a}if(!(rp=hp,sp=n[q[q[Ye>>2]+28>>2]](Ye)|0,tp=n[q[q[Ye>>2]+20>>2]](Ye,jp)|0,qp=q[q[hp>>2]+8>>2],n[qp](rp|0,sp|0,tp|0)|0)){break a}jp=jp+1|0;if((mp|0)!=(jp|0)){continue}break}op=1}T=lp+16|0;return op|0}function Ie(Ye,fp){var up=0,vp=0,wp=0,xp=0,yp=0,zp=0,Ap=0,Bp=0,Cp=0;vp=q[Ye+8>>2];wp=Ye+4|0;up=q[wp>>2];if(vp-up>>2>>>0>=fp>>>0){Ye=fp<<2;Bp=wp,Cp=Dn(up,0,Ye)+Ye|0,q[Bp>>2]=Cp;return}a:{wp=q[Ye>>2];xp=up-wp>>2;yp=xp+fp|0;if(yp>>>0<1073741824){xp=xp<<2;vp=vp-wp|0;Ap=vp>>1;vp=vp>>2>>>0<536870911?Ap>>>0>>0?yp:Ap:1073741823;if(vp){if(vp>>>0>=1073741824){break a}zp=Mm(vp<<2)}xp=xp+zp|0;Dn(xp,0,fp<<2);fp=(yp<<2)+zp|0;yp=(vp<<2)+zp|0;if((up|0)!=(wp|0)){while(1){up=up+ -4|0;vp=q[up>>2];q[up>>2]=0;xp=xp+ -4|0;q[xp>>2]=vp;if((up|0)!=(wp|0)){continue}break}wp=q[Ye>>2];up=q[Ye+4>>2]}q[Ye>>2]=xp;q[Ye+8>>2]=yp;q[Ye+4>>2]=fp;if((up|0)!=(wp|0)){while(1){up=up+ -4|0;Ye=q[up>>2];q[up>>2]=0;if(Ye){n[q[q[Ye>>2]+4>>2]](Ye)}if((up|0)!=(wp|0)){continue}break}}if(wp){An(wp)}return}bn();F()}ab(2144);F()}function Je(Ye,fp){Ye=Ye|0;fp=fp|0;var Dp=0,Ep=0,Fp=0,Gp=0,Hp=0,Ip=0,Jp=0;Dp=q[Ye+60>>2];a:{if(!Dp){break a}q[Dp+4>>2]=Ye+48;if(!n[q[q[Dp>>2]+12>>2]](Dp)){break a}b:{Ep=n[q[q[Ye>>2]+24>>2]](Ye)|0;if((Ep|0)<1){break b}Gp=Ye+60|0;Dp=0;while(1){c:{Hp=q[(n[q[q[Ye>>2]+28>>2]](Ye)|0)+4>>2];Ip=n[q[q[Ye>>2]+20>>2]](Ye,Dp)|0;Fp=q[Gp>>2];if(!n[q[q[Fp>>2]+8>>2]](Fp,q[q[Hp+8>>2]+(Ip<<2)>>2])){break c}Dp=Dp+1|0;if((Ep|0)!=(Dp|0)){continue}break b}break}return 0}if(!n[q[q[Ye>>2]+36>>2]](Ye,fp)){break a}if(!n[q[q[Ye>>2]+40>>2]](Ye,fp)){break a}Jp=n[q[q[Ye>>2]+44>>2]](Ye)|0}return Jp|0}function Ke(Ye,fp){Ye=Ye|0;fp=fp|0;var Kp=0,Lp=0,Mp=0,Np=0,Op=0;Kp=1;Lp=n[q[q[Ye>>2]+24>>2]](Ye)|0;a:{if((Lp|0)<1){break a}Np=Ye+48|0;Kp=0;Op=Ye+36|0;Ye=0;while(1){Mp=q[q[Op>>2]+(Ye<<2)>>2];if(!n[q[q[Mp>>2]+16>>2]](Mp,Np,fp)){break a}Ye=Ye+1|0;if((Lp|0)!=(Ye|0)){continue}break}Kp=1}return Kp|0}function Le(Ye,fp){Ye=Ye|0;fp=fp|0;var Pp=0,Qp=0,Rp=0,Sp=0,Tp=0;Pp=1;Qp=n[q[q[Ye>>2]+24>>2]](Ye)|0;a:{if((Qp|0)<1){break a}Sp=Ye+48|0;Pp=0;Tp=Ye+36|0;Ye=0;while(1){Rp=q[q[Tp>>2]+(Ye<<2)>>2];if(!n[q[q[Rp>>2]+20>>2]](Rp,Sp,fp)){break a}Ye=Ye+1|0;if((Qp|0)!=(Ye|0)){continue}break}Pp=1}return Pp|0}function Me(Ye){Ye=Ye|0;var fp=0,Up=0,Vp=0,Wp=0,Xp=0,Yp=0,Zp=0,_p=0,$p=0,aq=0,bq=0,cq=0,dq=0;Wp=T-16|0;T=Wp;fp=1;Zp=n[q[q[Ye>>2]+24>>2]](Ye)|0;a:{if((Zp|0)<1){break a}dq=Ye+48|0;Yp=Ye+36|0;while(1){b:{c:{if(!q[(n[q[q[Ye>>2]+28>>2]](Ye)|0)+40>>2]){break c}_p=Xp<<2;fp=q[_p+q[Yp>>2]>>2];Up=q[fp+8>>2];$p=Be(fp);if(!$p){break c}fp=n[q[q[Ye>>2]+28>>2]](Ye)|0;aq=q[Up+56>>2];bq=q[fp+40>>2];fp=Mm(32);q[Wp>>2]=fp;q[Wp+4>>2]=24;q[Wp+8>>2]=-2147483616;o[fp+24|0]=0;Up=r[2076]|r[2077]<<8|(r[2078]<<16|r[2079]<<24);Vp=r[2072]|r[2073]<<8|(r[2074]<<16|r[2075]<<24);o[fp+16|0]=Vp;o[fp+17|0]=Vp>>>8;o[fp+18|0]=Vp>>>16;o[fp+19|0]=Vp>>>24;o[fp+20|0]=Up;o[fp+21|0]=Up>>>8;o[fp+22|0]=Up>>>16;o[fp+23|0]=Up>>>24;Up=r[2068]|r[2069]<<8|(r[2070]<<16|r[2071]<<24);Vp=r[2064]|r[2065]<<8|(r[2066]<<16|r[2067]<<24);o[fp+8|0]=Vp;o[fp+9|0]=Vp>>>8;o[fp+10|0]=Vp>>>16;o[fp+11|0]=Vp>>>24;o[fp+12|0]=Up;o[fp+13|0]=Up>>>8;o[fp+14|0]=Up>>>16;o[fp+15|0]=Up>>>24;Up=r[2060]|r[2061]<<8|(r[2062]<<16|r[2063]<<24);Vp=r[2056]|r[2057]<<8|(r[2058]<<16|r[2059]<<24);o[fp|0]=Vp;o[fp+1|0]=Vp>>>8;o[fp+2|0]=Vp>>>16;o[fp+3|0]=Vp>>>24;o[fp+4|0]=Up;o[fp+5|0]=Up>>>8;o[fp+6|0]=Up>>>16;o[fp+7|0]=Up>>>24;d:{e:{Vp=bq+16|0;Up=Vp;fp=q[Up>>2];if(!fp){break e}while(1){cq=q[fp+16>>2]<(aq|0);Up=cq?Up:fp;fp=q[(cq<<2)+fp>>2];if(fp){continue}break}if((Up|0)==(Vp|0)|(aq|0)>2]){break e}fp=Up+20|0;if(!ga(fp,Wp)){break e}fp=gk(fp,Wp);break d}fp=gk(bq,Wp)}if(o[Wp+11|0]<=-1){An(q[Wp>>2])}if(!fp){break c}ud(q[q[q[Yp>>2]+_p>>2]+8>>2],$p);break b}fp=q[q[Yp>>2]+(Xp<<2)>>2];if(n[q[q[fp>>2]+24>>2]](fp,dq)){break b}fp=0;break a}fp=1;Xp=Xp+1|0;if((Zp|0)!=(Xp|0)){continue}break}}T=Wp+16|0;return fp|0}function Ne(Ye,eq,fq){Ye=Ye|0;eq=eq|0;fq=fq|0;if(fq>>>0>3){q[Ye>>2]=0;return}a:{b:{switch(fq-1|0){default:eq=Mm(20);we(eq);break a;case 0:eq=Mm(24);Re(eq);break a;case 1:eq=Mm(36);Re(eq);q[eq+32>>2]=0;q[eq+24>>2]=-1;q[eq+28>>2]=0;q[eq>>2]=10764;break a;case 2:break b}}eq=Mm(28);Re(eq);q[eq+24>>2]=-1;q[eq>>2]=6744;q[Ye>>2]=eq;return}q[Ye>>2]=eq}function Oe(Ye){Ye=Ye|0;var eq=0,fq=0,gq=0,hq=0,iq=0;q[Ye>>2]=2004;eq=Ye+60|0;fq=q[eq>>2];q[eq>>2]=0;if(fq){n[q[q[fq>>2]+4>>2]](fq)}eq=q[Ye+48>>2];if(eq){q[Ye+52>>2]=eq;An(eq)}fq=q[Ye+36>>2];if(fq){eq=fq;iq=Ye+40|0;gq=q[iq>>2];hq=eq;a:{if((eq|0)==(gq|0)){break a}while(1){gq=gq+ -4|0;eq=q[gq>>2];q[gq>>2]=0;if(eq){n[q[q[eq>>2]+4>>2]](eq)}if((fq|0)!=(gq|0)){continue}break}hq=q[Ye+36>>2]}eq=hq;q[iq>>2]=fq;An(eq)}q[Ye>>2]=1384;eq=q[Ye+16>>2];if(eq){q[Ye+20>>2]=eq;An(eq)}eq=q[Ye+4>>2];if(eq){q[Ye+8>>2]=eq;An(eq)}return Ye|0}function Pe(Ye){Ye=Ye|0;var jq=0,kq=0,lq=0,mq=0,nq=0;q[Ye>>2]=2004;jq=Ye+60|0;kq=q[jq>>2];q[jq>>2]=0;if(kq){n[q[q[kq>>2]+4>>2]](kq)}jq=q[Ye+48>>2];if(jq){q[Ye+52>>2]=jq;An(jq)}kq=q[Ye+36>>2];if(kq){jq=kq;nq=Ye+40|0;lq=q[nq>>2];mq=jq;a:{if((jq|0)==(lq|0)){break a}while(1){lq=lq+ -4|0;jq=q[lq>>2];q[lq>>2]=0;if(jq){n[q[q[jq>>2]+4>>2]](jq)}if((kq|0)!=(lq|0)){continue}break}mq=q[Ye+36>>2]}jq=mq;q[nq>>2]=kq;An(jq)}q[Ye>>2]=1384;jq=q[Ye+16>>2];if(jq){q[Ye+20>>2]=jq;An(jq)}jq=q[Ye+4>>2];if(jq){q[Ye+8>>2]=jq;An(jq)}An(Ye)}function Qe(Ye,oq){Ye=Ye|0;oq=oq|0;var pq=0,qq=0;qq=q[Ye+16>>2];pq=0;a:{if(q[Ye+20>>2]-qq>>2<=(oq|0)){break a}oq=q[(oq<<2)+qq>>2];pq=0;if((oq|0)<0){break a}pq=Be(q[q[Ye+36>>2]+(oq<<2)>>2])}return pq|0}function Re(Ye){we(Ye);q[Ye+20>>2]=0;q[Ye>>2]=2220}function Se(q,Ye,oq){q=q|0;Ye=Ye|0;oq=oq|0;return xe(q,Ye,oq)|0}function Te(Ye,oq){Ye=Ye|0;oq=oq|0;var rq=0,sq=0;sq=q[Ye+4>>2];a:{if(sq){rq=1;if(r[sq+36|0]<2){break a}}rq=n[q[q[Ye>>2]+48>>2]](Ye,q[oq+4>>2]-q[oq>>2]>>2)|0}return rq|0}function Ue(Ye,oq,tq){Ye=Ye|0;oq=oq|0;tq=tq|0;var uq=0,vq=0,wq=0,xq=0,yq=0,zq=0,Aq=0,Bq=0,Cq=0,Dq=0;wq=T-16|0;T=wq;Aq=q[tq+8>>2];xq=q[tq+16>>2];yq=q[tq+12>>2];uq=yq;vq=q[tq+20>>2];a:{if((uq|0)<(vq|0)?1:(uq|0)<=(vq|0)?Aq>>>0>xq>>>0?0:1:0){break a}Bq=q[tq>>2];Cq=o[Bq+xq|0];uq=vq;zq=xq+1|0;if(zq>>>0<1){uq=uq+1|0}q[tq+16>>2]=zq;q[tq+20>>2]=uq;b:{if((Cq|0)==-2){break b}if((yq|0)<(uq|0)?1:(yq|0)<=(uq|0)?Aq>>>0>zq>>>0?0:1:0){break a}yq=o[zq+Bq|0];xq=xq+2|0;if(xq>>>0<2){vq=vq+1|0}uq=tq;q[uq+16>>2]=xq;q[uq+20>>2]=vq;n[q[q[Ye>>2]+40>>2]](wq+8|0,Ye,Cq,yq);vq=q[wq+8>>2];q[wq+8>>2]=0;uq=q[Ye+20>>2];q[Ye+20>>2]=vq;if(!uq){q[wq+8>>2]=0;break b}n[q[q[uq>>2]+4>>2]](uq);uq=q[wq+8>>2];q[wq+8>>2]=0;if(!uq){break b}n[q[q[uq>>2]+4>>2]](uq)}uq=q[Ye+20>>2];if(uq){if(!n[q[q[Ye>>2]+28>>2]](Ye,uq)){break a}}if(!n[q[q[Ye>>2]+36>>2]](Ye,oq,tq)){break a}tq=q[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:{if(!Ye){q[Eq>>2]=0;break a}Hb(Ye);Ye=q[Eq>>2];q[Eq>>2]=0;if(!Ye){break a}Hb(Ye)}Ye=q[Eq+8>>2];q[Eq+8>>2]=0;if(Ye){Hb(Ye)}T=Eq+80|0}function Ze(Ye,oq){Ye=Ye|0;oq=oq|0;var tq=0,Zq=0,_q=0,$q=0,ar=0,br=0,cr=0,dr=0,er=0;Zq=q[Ye+8>>2];tq=q[Zq+28>>2]+ -1|0;if(tq>>>0>5){return 0}a:{b:{switch(tq-1|0){case 0:$q=o[Zq+24|0];ar=Mm(($q|0)>-1?$q:-1);tq=q[Ye+16>>2];Zq=0;c:{if(!q[tq+80>>2]){break c}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}br=($q|0)<1;dr=Ye+8|0;tq=0;while(1){Ye=0;if(!br){while(1){o[Ye+ar|0]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if(($q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[dr>>2]- -64>>2]>>2]+cr|0,ar,$q);cr=$q+cr|0;_q=_q+1|0;if((_q|0)!=(oq|0)){continue}break}break a;default:$q=o[Zq+24|0];ar=Mm(($q|0)>-1?$q:-1);tq=q[Ye+16>>2];Zq=0;d:{if(!q[tq+80>>2]){break d}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}br=($q|0)<1;dr=Ye+8|0;tq=0;while(1){Ye=0;if(!br){while(1){o[Ye+ar|0]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if(($q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[dr>>2]- -64>>2]>>2]+cr|0,ar,$q);cr=$q+cr|0;_q=_q+1|0;if((_q|0)!=(oq|0)){continue}break}break a;case 2:_q=o[Zq+24|0];Zq=_q+_q|0;ar=Mm(Zq>>>0<_q>>>0?-1:Zq);tq=q[Ye+16>>2];Zq=0;e:{if(!q[tq+80>>2]){break e}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}br=_q<<1;dr=(_q|0)<1;er=Ye+8|0;tq=0;while(1){Ye=0;if(!dr){while(1){p[(Ye<<1)+ar>>1]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if((_q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[er>>2]- -64>>2]>>2]+cr|0,ar,br);cr=cr+br|0;$q=$q+1|0;if(($q|0)!=(oq|0)){continue}break}break a;case 1:_q=o[Zq+24|0];Zq=_q+_q|0;ar=Mm(Zq>>>0<_q>>>0?-1:Zq);tq=q[Ye+16>>2];Zq=0;f:{if(!q[tq+80>>2]){break f}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}br=_q<<1;dr=(_q|0)<1;er=Ye+8|0;tq=0;while(1){Ye=0;if(!dr){while(1){p[(Ye<<1)+ar>>1]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if((_q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[er>>2]- -64>>2]>>2]+cr|0,ar,br);cr=cr+br|0;$q=$q+1|0;if(($q|0)!=(oq|0)){continue}break}break a;case 4:_q=o[Zq+24|0];br=_q<<2;ar=Mm((_q|0)!=(_q&1073741823)?-1:br);tq=q[Ye+16>>2];Zq=0;g:{if(!q[tq+80>>2]){break g}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}dr=(_q|0)<1;er=Ye+8|0;tq=0;while(1){Ye=0;if(!dr){while(1){q[(Ye<<2)+ar>>2]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if((_q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[er>>2]- -64>>2]>>2]+cr|0,ar,br);cr=cr+br|0;$q=$q+1|0;if(($q|0)!=(oq|0)){continue}break}break a;case 3:break b}}_q=o[Zq+24|0];br=_q<<2;ar=Mm((_q|0)!=(_q&1073741823)?-1:br);tq=q[Ye+16>>2];Zq=0;h:{if(!q[tq+80>>2]){break h}Zq=q[q[tq>>2]>>2]+q[tq+48>>2]|0}if(!oq){break a}dr=(_q|0)<1;er=Ye+8|0;tq=0;while(1){Ye=0;if(!dr){while(1){q[(Ye<<2)+ar>>2]=q[Zq+(tq<<2)>>2];tq=tq+1|0;Ye=Ye+1|0;if((_q|0)!=(Ye|0)){continue}break}}Cn(q[q[q[er>>2]- -64>>2]>>2]+cr|0,ar,br);cr=cr+br|0;$q=$q+1|0;if(($q|0)!=(oq|0)){continue}break}}An(ar);return 1}function _e(Ye){Ye=Ye|0;var oq=0,fr=0;q[Ye>>2]=2220;fr=Ye+20|0;oq=q[fr>>2];q[fr>>2]=0;if(oq){n[q[q[oq>>2]+4>>2]](oq)}q[Ye>>2]=1908;fr=Ye+16|0;oq=q[fr>>2];q[fr>>2]=0;if(oq){Hb(oq)}return Ye|0}function $e(Ye){Ye=Ye|0;var gr=0,hr=0;q[Ye>>2]=2220;hr=Ye+20|0;gr=q[hr>>2];q[hr>>2]=0;if(gr){n[q[q[gr>>2]+4>>2]](gr)}q[Ye>>2]=1908;hr=Ye+16|0;gr=q[hr>>2];q[hr>>2]=0;if(gr){Hb(gr)}An(Ye)}function af(Ye){Ye=Ye|0;return o[q[Ye+8>>2]+24|0]}function bf(Ye,ir,jr,kr,lr,mr){var nr=0,or=0,pr=0,qr=0;nr=T-32|0;T=nr;pr=q[q[q[ir+4>>2]+8>>2]+(kr<<2)>>2];a:{b:{if((n[q[q[ir>>2]+8>>2]](ir)|0)!=1|jr+ -1>>>0>5){break b}qr=n[q[q[ir>>2]+36>>2]](ir)|0;or=n[q[q[ir>>2]+44>>2]](ir,kr)|0;if(!(or?qr:0)){q[Ye>>2]=0;break a}kr=n[q[q[ir>>2]+40>>2]](ir,kr)|0;if(kr){ir=q[ir+44>>2];q[nr+12>>2]=kr;q[nr+8>>2]=ir;q[nr+20>>2]=or;q[nr+16>>2]=or+12;df(Ye,jr,pr,lr,nr+8|0,mr);if(q[Ye>>2]){break a}q[Ye>>2]=0;break b}ir=q[ir+44>>2];q[nr+12>>2]=qr;q[nr+8>>2]=ir;q[nr+20>>2]=or;q[nr+16>>2]=or+12;ef(Ye,jr,pr,lr,nr+8|0,mr);if(q[Ye>>2]){break a}q[Ye>>2]=0}q[Ye>>2]=0}T=nr+32|0}function cf(Ye,ir,jr){var kr=0,lr=0,mr=0,rr=0,sr=0,tr=0,ur=0,vr=0;q[Ye>>2]=3044;q[Ye+4>>2]=ir;ir=q[jr+8>>2];kr=q[jr+12>>2];lr=q[jr+16>>2];rr=q[jr+20>>2];sr=q[jr>>2];tr=q[jr+4>>2];q[Ye+40>>2]=0;mr=Ye+32|0;q[mr>>2]=0;q[mr+4>>2]=0;q[Ye+24>>2]=lr;q[Ye+28>>2]=rr;q[Ye+16>>2]=ir;q[Ye+20>>2]=kr;q[Ye+8>>2]=sr;q[Ye+12>>2]=tr;a:{ir=q[jr+28>>2]-q[jr+24>>2]|0;b:{if(!ir){break b}kr=ir>>2;if(kr>>>0>=1073741824){break a}ir=Mm(ir);q[Ye+32>>2]=ir;lr=Ye+36|0;q[lr>>2]=ir;q[Ye+40>>2]=ir+(kr<<2);kr=q[jr+24>>2];jr=q[jr+28>>2]-kr|0;if((jr|0)<1){break b}ur=lr,vr=Cn(ir,kr,jr)+jr|0,q[ur>>2]=vr}q[Ye>>2]=6584;return}bn();F()}function df(Ye,ir,jr,wr,xr,yr){ir=ir+ -1|0;if(ir>>>0>5){q[Ye>>2]=0;return}a:{b:{switch(ir-1|0){default:ir=Mm(60);ff(ir,jr,wr,xr);q[ir>>2]=2336;break a;case 0:ir=Mm(60);ff(ir,jr,wr,xr);q[ir>>2]=3100;break a;case 2:ir=Mm(112);ff(ir,jr,wr,xr);q[ir>>2]=3336;q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir+68>>2]=0;q[ir+72>>2]=0;q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+84>>2]=0;q[ir+88>>2]=0;q[ir+92>>2]=0;q[ir+96>>2]=0;q[ir+100>>2]=0;q[ir+104>>2]=0;q[ir+108>>2]=0;break a;case 1:ir=Mm(92);ff(ir,jr,wr,xr);q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir>>2]=3584;q[ir+88>>2]=yr;q[ir+68>>2]=0;q[ir+72>>2]=0;q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+84>>2]=0;break a;case 3:ir=Mm(104);ff(ir,jr,wr,xr);q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir>>2]=3812;q[ir+84>>2]=0;jr=q[xr+4>>2];q[ir+88>>2]=q[xr>>2];q[ir+92>>2]=jr;jr=q[xr+12>>2];q[ir+96>>2]=q[xr+8>>2];q[ir+100>>2]=jr;break a;case 4:break b}}ir=Mm(124);ff(ir,jr,wr,xr);q[ir>>2]=4048;jr=ir- -64|0;q[jr>>2]=0;q[jr+4>>2]=0;jr=q[xr+4>>2];q[ir+72>>2]=q[xr>>2];q[ir+76>>2]=jr;jr=q[xr+12>>2];q[ir+80>>2]=q[xr+8>>2];q[ir+84>>2]=jr;q[ir+92>>2]=-1;q[ir+96>>2]=-1;q[ir+88>>2]=1;q[ir+60>>2]=4284;q[ir+100>>2]=-1;q[ir+104>>2]=-1;ah(ir+108|0);q[Ye>>2]=ir;return}q[Ye>>2]=ir}function ef(Ye,ir,jr,wr,xr,yr){ir=ir+ -1|0;if(ir>>>0>5){q[Ye>>2]=0;return}a:{b:{switch(ir-1|0){default:ir=Mm(60);Vf(ir,jr,wr,xr);q[ir>>2]=4676;break a;case 0:ir=Mm(60);Vf(ir,jr,wr,xr);q[ir>>2]=5100;break a;case 2:ir=Mm(112);Vf(ir,jr,wr,xr);q[ir>>2]=5324;q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir+68>>2]=0;q[ir+72>>2]=0;q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+84>>2]=0;q[ir+88>>2]=0;q[ir+92>>2]=0;q[ir+96>>2]=0;q[ir+100>>2]=0;q[ir+104>>2]=0;q[ir+108>>2]=0;break a;case 1:ir=Mm(92);Vf(ir,jr,wr,xr);q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir>>2]=5560;q[ir+88>>2]=yr;q[ir+68>>2]=0;q[ir+72>>2]=0;q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+84>>2]=0;break a;case 3:ir=Mm(104);Vf(ir,jr,wr,xr);q[ir+76>>2]=0;q[ir+80>>2]=0;q[ir+60>>2]=0;q[ir+64>>2]=0;q[ir>>2]=5776;q[ir+84>>2]=0;jr=q[xr+4>>2];q[ir+88>>2]=q[xr>>2];q[ir+92>>2]=jr;jr=q[xr+12>>2];q[ir+96>>2]=q[xr+8>>2];q[ir+100>>2]=jr;break a;case 4:break b}}ir=Mm(124);Vf(ir,jr,wr,xr);q[ir>>2]=6e3;jr=ir- -64|0;q[jr>>2]=0;q[jr+4>>2]=0;jr=q[xr+4>>2];q[ir+72>>2]=q[xr>>2];q[ir+76>>2]=jr;jr=q[xr+12>>2];q[ir+80>>2]=q[xr+8>>2];q[ir+84>>2]=jr;q[ir+92>>2]=-1;q[ir+96>>2]=-1;q[ir+88>>2]=1;q[ir+60>>2]=6220;q[ir+100>>2]=-1;q[ir+104>>2]=-1;ah(ir+108|0);q[Ye>>2]=ir;return}q[Ye>>2]=ir}function ff(Ye,ir,jr,wr){var xr=0,yr=0,zr=0,Ar=0,Br=0,Cr=0,Dr=0,Er=0;q[Ye>>2]=3044;q[Ye+4>>2]=ir;ir=q[jr+8>>2];xr=q[jr+12>>2];yr=q[jr+16>>2];Ar=q[jr+20>>2];Br=q[jr>>2];Cr=q[jr+4>>2];q[Ye+40>>2]=0;zr=Ye+32|0;q[zr>>2]=0;q[zr+4>>2]=0;q[Ye+24>>2]=yr;q[Ye+28>>2]=Ar;q[Ye+16>>2]=ir;q[Ye+20>>2]=xr;q[Ye+8>>2]=Br;q[Ye+12>>2]=Cr;a:{ir=q[jr+28>>2]-q[jr+24>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+Wr>>2]+q[Qr+Ur>>2]|0;q[Ye>>2]=Qr;j:{if((Qr|0)>q[Yr>>2]){Qr=Qr-q[Xr>>2]|0}else{if((Qr|0)>=q[bs>>2]){break j}Qr=Qr+q[Xr>>2]|0}q[Ye>>2]=Qr}Tr=Tr+1|0;Sr=q[_r>>2];if((Tr|0)<(Sr|0)){continue}break}}Vr=Vr+1|0;if((Vr|0)<(es|0)){continue}break}}An(as);return 1}function nf(Ye){Ye=Ye|0;var wr=0;q[Ye>>2]=3044;wr=q[Ye+32>>2];if(wr){q[Ye+36>>2]=wr;An(wr)}return Ye|0}function of(Ye,Pr,Qr,Rr,Sr,hs){Ye=Ye|0;Pr=Pr|0;Qr=Qr|0;Rr=Rr|0;Sr=Sr|0;hs=hs|0;var is=0,js=0,ks=0,ls=0,ms=0,ns=0,os=0,ps=0,qs=0,rs=0,ss=0,ts=0,us=0,vs=0,ws=0,xs=0,ys=0,zs=0,As=0,Bs=0,Cs=0,Ds=0;q[Ye+8>>2]=Sr;hs=Ye+32|0;is=q[hs>>2];Rr=q[Ye+36>>2]-is>>2;a:{if(Rr>>>0>>0){Fa(hs,Sr-Rr|0);break a}if(Rr>>>0<=Sr>>>0){break a}q[Ye+36>>2]=is+(Sr<<2)}hs=0;Rr=(Sr&1073741823)!=(Sr|0)?-1:Sr<<2;rs=Dn(Mm(Rr),0,Rr);ws=Dn(Mm(Rr),0,Rr);os=Ye+8|0;is=q[os>>2];b:{if((is|0)<1){break b}ps=Ye+16|0;Rr=Ye+32|0;qs=Ye+12|0;while(1){is=hs<<2;ls=q[is+rs>>2];ns=q[ps>>2];c:{if((ls|0)>(ns|0)){ks=q[Rr>>2];q[is+ks>>2]=ns;break c}ks=q[Rr>>2];is=is+ks|0;ns=q[qs>>2];if((ls|0)<(ns|0)){q[is>>2]=ns;break c}q[is>>2]=ls}hs=hs+1|0;is=q[os>>2];if((hs|0)<(is|0)){continue}break}if((is|0)<1){break b}Rr=0;os=Ye+16|0;ls=Ye+20|0;ps=Ye+8|0;qs=Ye+12|0;while(1){is=Rr<<2;hs=is+Qr|0;is=q[Pr+is>>2]+q[is+ks>>2]|0;q[hs>>2]=is;d:{if((is|0)>q[os>>2]){is=is-q[ls>>2]|0}else{if((is|0)>=q[qs>>2]){break d}is=is+q[ls>>2]|0}q[hs>>2]=is}Rr=Rr+1|0;is=q[ps>>2];if((Rr|0)<(is|0)){continue}break}}Rr=q[Ye+56>>2];xs=q[Rr>>2];Rr=q[Rr+4>>2]-xs|0;if((Rr|0)>=5){ys=Rr>>2;As=Sr<<2;Bs=q[Ye+52>>2];os=Ye+16|0;ps=Ye+32|0;qs=Ye+8|0;ns=Ye+20|0;us=Ye+12|0;ss=q[Ye+48>>2];Cs=ss+28|0;ls=1;while(1){e:{f:{g:{if(ys>>>0>ls>>>0){Ye=q[(ls<<2)+xs>>2];zs=(Sr|0)<1;if(!zs){Dn(rs,0,As)}if((Ye|0)==-1){Ye=w(Sr,ls);break f}Ds=q[ss>>2];ks=0;Rr=Ye;while(1){h:{if(q[Ds+(Rr>>>3&536870908)>>2]>>>(Rr&31)&1){break h}hs=q[q[q[ss+64>>2]+12>>2]+(Rr<<2)>>2];if((hs|0)==-1){break h}ms=q[Bs>>2];js=q[Cs>>2];vs=q[ms+(q[js+(hs<<2)>>2]<<2)>>2];if((vs|0)>=(ls|0)){break h}ts=hs+1|0;ts=q[ms+(q[js+(((ts>>>0)%3|0?ts:hs+ -2|0)<<2)>>2]<<2)>>2];if((ts|0)>=(ls|0)){break h}hs=q[ms+(q[js+(hs+((hs>>>0)%3|0?-1:2)<<2)>>2]<<2)>>2];if((hs|0)>=(ls|0)){break h}i:{if(zs){break i}js=w(Sr,hs);ms=w(Sr,ts);vs=w(Sr,vs);hs=0;while(1){q[ws+(hs<<2)>>2]=(q[(hs+js<<2)+Qr>>2]+q[(hs+ms<<2)+Qr>>2]|0)-q[(hs+vs<<2)+Qr>>2];hs=hs+1|0;if((hs|0)!=(Sr|0)){continue}break}hs=0;if((Sr|0)<=0){break i}while(1){js=hs<<2;ms=js+rs|0;q[ms>>2]=q[ms>>2]+q[js+ws>>2];hs=hs+1|0;if((hs|0)!=(Sr|0)){continue}break}}ks=ks+1|0}hs=-1;Rr=((Rr>>>0)%3|0?-1:2)+Rr|0;j:{if((Rr|0)==-1|q[q[ss>>2]+(Rr>>>3&536870908)>>2]>>>(Rr&31)&1){break j}Rr=q[q[q[ss+64>>2]+12>>2]+(Rr<<2)>>2];if((Rr|0)==-1){break j}if((Rr>>>0)%3){hs=Rr+ -1|0;break j}hs=Rr+2|0}Rr=(Ye|0)==(hs|0)?-1:hs;if((Rr|0)!=-1){continue}break}Ye=w(Sr,ls);if(!ks){break f}hs=0;if((Sr|0)<=0){break g}while(1){Rr=(hs<<2)+rs|0;q[Rr>>2]=q[Rr>>2]/(ks|0);hs=hs+1|0;if((hs|0)!=(Sr|0)){continue}break}break g}cn();F()}if((is|0)<1){break e}hs=0;while(1){Rr=hs<<2;is=q[Rr+rs>>2];js=q[os>>2];k:{if((is|0)>(js|0)){ks=q[ps>>2];q[Rr+ks>>2]=js;break k}ks=q[ps>>2];Rr=Rr+ks|0;js=q[us>>2];if((is|0)<(js|0)){q[Rr>>2]=js;break k}q[Rr>>2]=is}hs=hs+1|0;is=q[qs>>2];if((hs|0)<(is|0)){continue}break}Rr=0;if((is|0)<1){break e}Ye=Ye<<2;js=Ye+Qr|0;ms=Ye+Pr|0;while(1){hs=Rr<<2;Ye=hs+js|0;hs=q[hs+ms>>2]+q[hs+ks>>2]|0;q[Ye>>2]=hs;l:{if((hs|0)>q[os>>2]){hs=hs-q[ns>>2]|0}else{if((hs|0)>=q[us>>2]){break l}hs=hs+q[ns>>2]|0}q[Ye>>2]=hs}Rr=Rr+1|0;is=q[qs>>2];if((Rr|0)<(is|0)){continue}break}break e}if((is|0)<1){break e}js=(w(ls+ -1|0,Sr)<<2)+Qr|0;hs=0;while(1){Rr=hs<<2;is=q[Rr+js>>2];ms=q[os>>2];m:{if((is|0)>(ms|0)){ks=q[ps>>2];q[Rr+ks>>2]=ms;break m}ks=q[ps>>2];Rr=Rr+ks|0;ms=q[us>>2];if((is|0)<(ms|0)){q[Rr>>2]=ms;break m}q[Rr>>2]=is}hs=hs+1|0;is=q[qs>>2];if((hs|0)<(is|0)){continue}break}Rr=0;if((is|0)<1){break e}Ye=Ye<<2;js=Ye+Qr|0;ms=Ye+Pr|0;while(1){hs=Rr<<2;Ye=hs+js|0;hs=q[hs+ms>>2]+q[hs+ks>>2]|0;q[Ye>>2]=hs;n:{if((hs|0)>q[os>>2]){hs=hs-q[ns>>2]|0}else{if((hs|0)>=q[us>>2]){break n}hs=hs+q[ns>>2]|0}q[Ye>>2]=hs}Rr=Rr+1|0;is=q[qs>>2];if((Rr|0)<(is|0)){continue}break}}ls=ls+1|0;if((ls|0)<(ys|0)){continue}break}}An(ws);An(rs);return 1}function pf(Ye){Ye=Ye|0;var Pr=0;q[Ye>>2]=3336;Pr=q[Ye+96>>2];if(Pr){An(Pr)}Pr=q[Ye+84>>2];if(Pr){An(Pr)}Pr=q[Ye+72>>2];if(Pr){An(Pr)}Pr=q[Ye+60>>2];if(Pr){An(Pr)}q[Ye>>2]=3044;Pr=q[Ye+32>>2];if(Pr){q[Ye+36>>2]=Pr;An(Pr)}return Ye|0}function qf(Ye){Ye=Ye|0;var Qr=0;q[Ye>>2]=3336;Qr=q[Ye+96>>2];if(Qr){An(Qr)}Qr=q[Ye+84>>2];if(Qr){An(Qr)}Qr=q[Ye+72>>2];if(Qr){An(Qr)}Qr=q[Ye+60>>2];if(Qr){An(Qr)}q[Ye>>2]=3044;Qr=q[Ye+32>>2];if(Qr){q[Ye+36>>2]=Qr;An(Qr)}An(Ye)}function rf(q){q=q|0;return 4}function sf(Ye,Rr){Ye=Ye|0;Rr=Rr|0;var Sr=0,hs=0,Es=0,Fs=0,Gs=0,Hs=0,Is=0,Js=0,Ks=0,Ls=0,Ms=0;Js=T-32|0;T=Js;a:{if(s[Rr+38>>1]<=513){Es=q[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if(Ys>>>0>>0){Fa(_s,Zs-Ys|0);break a}if(Ys>>>0<=Zs>>>0){break a}q[Ye+36>>2]=ct+(Zs<<2)}q[bt+56>>2]=0;q[bt+60>>2]=0;q[bt+48>>2]=0;q[bt+52>>2]=0;q[bt+40>>2]=0;q[bt+44>>2]=0;_s=bt+32|0;q[_s>>2]=0;q[_s+4>>2]=0;q[bt+24>>2]=0;q[bt+28>>2]=0;q[bt+16>>2]=0;q[bt+20>>2]=0;q[bt>>2]=0;Ys=0;if(Zs){Ad(bt+16|0,Zs,bt);at=q[bt+28>>2];Ys=q[_s>>2]}q[bt>>2]=0;Ys=Ys-at>>2;b:{if(Ys>>>0>=Zs>>>0){if(Ys>>>0<=Zs>>>0){break b}q[bt+32>>2]=(Zs<<2)+at;break b}Ad(bt+16|12,Zs-Ys|0,bt)}q[bt>>2]=0;_s=q[bt+40>>2];Ys=q[bt+44>>2]-_s>>2;c:{if(Ys>>>0>=Zs>>>0){if(Ys>>>0<=Zs>>>0){break c}q[bt+44>>2]=_s+(Zs<<2);break c}Ad(bt+40|0,Zs-Ys|0,bt)}q[bt>>2]=0;_s=q[bt+52>>2];Ys=q[bt+56>>2]-_s>>2;d:{if(Ys>>>0>=Zs>>>0){if(Ys>>>0<=Zs>>>0){break d}q[bt+56>>2]=_s+(Zs<<2);break d}Ad(bt+52|0,Zs-Ys|0,bt)}et=Ye+8|0;e:{if(q[et>>2]<=0){break e}ft=q[bt+16>>2];at=0;ht=Ye+16|0;Ys=Ye+32|0;dt=Ye+12|0;while(1){_s=at<<2;$s=q[_s+ft>>2];it=q[ht>>2];f:{if(($s|0)>(it|0)){ct=q[Ys>>2];q[_s+ct>>2]=it;break f}ct=q[Ys>>2];_s=_s+ct|0;it=q[dt>>2];if(($s|0)<(it|0)){q[_s>>2]=it;break f}q[_s>>2]=$s}at=at+1|0;_s=q[et>>2];if((at|0)<(_s|0)){continue}break}if((_s|0)<1){break e}Ys=0;et=Ye+16|0;at=Ye+20|0;ft=Ye+8|0;ht=Ye+12|0;while(1){$s=Ys<<2;_s=$s+Xs|0;$s=q[Rr+$s>>2]+q[$s+ct>>2]|0;q[_s>>2]=$s;g:{if(($s|0)>q[et>>2]){$s=$s-q[at>>2]|0}else{if(($s|0)>=q[ht>>2]){break g}$s=$s+q[at>>2]|0}q[_s>>2]=$s}Ys=Ys+1|0;if((Ys|0)>2]){continue}break}}wt=q[Ye+52>>2];ft=q[Ye+48>>2];qt=Mm(16);Ys=qt;q[Ys>>2]=0;q[Ys+4>>2]=0;q[Ys+8>>2]=0;q[Ys+12>>2]=0;q[bt+8>>2]=0;q[bt>>2]=0;q[bt+4>>2]=0;h:{if(Zs){if(Zs>>>0>=1073741824){break h}Ys=Zs<<2;mt=Mm(Ys);q[bt>>2]=mt;_s=Ys+mt|0;q[bt+8>>2]=_s;Dn(mt,0,Ys);q[bt+4>>2]=_s}Ys=1;_s=q[Ye+56>>2];ut=q[_s>>2];_s=q[_s+4>>2]-ut|0;i:{if((_s|0)<5){break i}vt=_s>>2;xt=Zs<<2;ht=Ye+8|0;it=Ye+16|0;nt=Ye+32|0;ot=Ye+20|0;pt=Ye+12|0;yt=ft+28|0;et=1;while(1){j:{k:{l:{if(vt>>>0>et>>>0){m:{n:{ct=q[(et<<2)+ut>>2];if((ct|0)==-1){break n}gt=ct+((ct>>>0)%3|0?-1:2)|0;rt=gt>>>5;dt=1;st=1<<(gt&31);tt=q[ft>>2];_s=0;Ys=ct;o:{while(1){p:{if(q[tt+(Ys>>>3&536870908)>>2]>>>(Ys&31)&1){break p}$s=q[q[q[ft+64>>2]+12>>2]+(Ys<<2)>>2];if(($s|0)==-1){break p}kt=q[wt>>2];at=q[yt>>2];lt=q[kt+(q[at+($s<<2)>>2]<<2)>>2];if((lt|0)>=(et|0)){break p}jt=$s+1|0;jt=q[kt+(q[at+(((jt>>>0)%3|0?jt:$s+ -2|0)<<2)>>2]<<2)>>2];if((jt|0)>=(et|0)){break p}$s=q[kt+(q[at+($s+(($s>>>0)%3|0?-1:2)<<2)>>2]<<2)>>2];if(($s|0)>=(et|0)){break p}if((Zs|0)>=1){kt=q[(bt+16|0)+w(_s,12)>>2];$s=w(Zs,$s);jt=w(Zs,jt);lt=w(Zs,lt);at=0;while(1){q[kt+(at<<2)>>2]=(q[($s+at<<2)+Xs>>2]+q[(at+jt<<2)+Xs>>2]|0)-q[(at+lt<<2)+Xs>>2];at=at+1|0;if((at|0)!=(Zs|0)){continue}break}}$s=4;_s=_s+1|0;if((_s|0)==4){break o}}q:{if(dt&1){at=-1;$s=Ys+1|0;Ys=($s>>>0)%3|0?$s:Ys+ -2|0;if((Ys|0)==-1|q[q[ft>>2]+(Ys>>>3&536870908)>>2]>>>(Ys&31)&1){break q}Ys=q[q[q[ft+64>>2]+12>>2]+(Ys<<2)>>2];if((Ys|0)==-1){break q}$s=Ys+1|0;at=($s>>>0)%3|0?$s:Ys+ -2|0;break q}at=-1;Ys=((Ys>>>0)%3|0?-1:2)+Ys|0;if((Ys|0)==-1|q[q[ft>>2]+(Ys>>>3&536870908)>>2]>>>(Ys&31)&1){break q}Ys=q[q[q[ft+64>>2]+12>>2]+(Ys<<2)>>2];if((Ys|0)==-1){break q}if((Ys>>>0)%3){at=Ys+ -1|0;break q}at=Ys+2|0}r:{if((at|0)==(ct|0)){break r}Ys=at;$s=(at|0)!=-1;at=($s|dt^-1)&1;Ys=at?Ys:-1;dt=$s&dt;if(!((gt|0)==-1|at)){if(q[q[ft>>2]+(rt<<2)>>2]&st){break r}$s=q[q[q[ft+64>>2]+12>>2]+(gt<<2)>>2];if(($s|0)==-1){break r}dt=0;if(($s>>>0)%3){Ys=$s+ -1|0}else{Ys=$s+2|0}}if((Ys|0)!=-1){continue}}break}$s=_s;if(($s|0)<1){break n}}gt=(Zs|0)<1;if(!gt){Dn(mt,0,xt)}Ys=$s+ -1|0;dt=(Ys<<2)+qt|0;Ys=w(Ys,12)+Ye|0;kt=Ys+60|0;rt=q[Ys- -64>>2];Ys=0;st=q[bt>>2];ct=0;_s=0;while(1){at=q[dt>>2];q[dt>>2]=at+1;if(rt>>>0<=at>>>0){break i}s:{if(q[q[kt>>2]+(at>>>3&536870908)>>2]>>>(at&31)&1){break s}_s=_s+1|0;if(gt){break s}tt=q[(bt+16|0)+w(ct,12)>>2];at=0;while(1){lt=at<<2;jt=lt+st|0;q[jt>>2]=q[jt>>2]+q[lt+tt>>2];at=at+1|0;if((at|0)!=(Zs|0)){continue}break}}ct=ct+1|0;if(($s|0)!=(ct|0)){continue}break}dt=w(Zs,et);$s=dt;if(!_s){break m}at=0;if((Zs|0)>0){break l}break k}$s=w(Zs,et)}if(q[ht>>2]<1){break j}dt=(w(et+ -1|0,Zs)<<2)+Xs|0;at=0;while(1){Ys=at<<2;_s=q[Ys+dt>>2];gt=q[it>>2];t:{if((_s|0)>(gt|0)){ct=q[nt>>2];q[Ys+ct>>2]=gt;break t}ct=q[nt>>2];Ys=Ys+ct|0;gt=q[pt>>2];if((_s|0)<(gt|0)){q[Ys>>2]=gt;break t}q[Ys>>2]=_s}at=at+1|0;_s=q[ht>>2];if((at|0)<(_s|0)){continue}break}Ys=0;if((_s|0)<1){break j}_s=$s<<2;at=_s+Xs|0;dt=Rr+_s|0;while(1){$s=Ys<<2;_s=$s+at|0;$s=q[$s+dt>>2]+q[$s+ct>>2]|0;q[_s>>2]=$s;u:{if(($s|0)>q[it>>2]){$s=$s-q[ot>>2]|0}else{if(($s|0)>=q[pt>>2]){break u}$s=$s+q[ot>>2]|0}q[_s>>2]=$s}Ys=Ys+1|0;if((Ys|0)>2]){continue}break}break j}cn();F()}while(1){Ys=(at<<2)+mt|0;q[Ys>>2]=q[Ys>>2]/(_s|0);at=at+1|0;if((at|0)!=(Zs|0)){continue}break}}if(q[ht>>2]<1){break j}at=0;while(1){Ys=at<<2;_s=q[Ys+mt>>2];$s=q[it>>2];v:{if((_s|0)>($s|0)){ct=q[nt>>2];q[Ys+ct>>2]=$s;break v}ct=q[nt>>2];Ys=Ys+ct|0;$s=q[pt>>2];if((_s|0)<($s|0)){q[Ys>>2]=$s;break v}q[Ys>>2]=_s}at=at+1|0;_s=q[ht>>2];if((at|0)<(_s|0)){continue}break}Ys=0;if((_s|0)<1){break j}_s=dt<<2;at=_s+Xs|0;dt=Rr+_s|0;while(1){$s=Ys<<2;_s=$s+at|0;$s=q[$s+dt>>2]+q[$s+ct>>2]|0;q[_s>>2]=$s;w:{if(($s|0)>q[it>>2]){$s=$s-q[ot>>2]|0}else{if(($s|0)>=q[pt>>2]){break w}$s=$s+q[ot>>2]|0}q[_s>>2]=$s}Ys=Ys+1|0;if((Ys|0)>2]){continue}break}}Ys=1;et=et+1|0;if((et|0)<(vt|0)){continue}break}}Ye=q[bt>>2];if(Ye){q[bt+4>>2]=Ye;An(Ye)}An(qt);Ye=q[bt+52>>2];if(Ye){q[bt+56>>2]=Ye;An(Ye)}Ye=q[bt+40>>2];if(Ye){q[bt+44>>2]=Ye;An(Ye)}Ye=q[bt+28>>2];if(Ye){q[bt+32>>2]=Ye;An(Ye)}Ye=q[bt+16>>2];if(Ye){q[bt+20>>2]=Ye;An(Ye)}T=bt- -64|0;return Ys|0}bn();F()}function wf(Ye){Ye=Ye|0;var Rr=0,Xs=0;q[Ye>>2]=3584;Rr=q[Ye+76>>2];if(Rr){An(Rr)}Xs=Ye+68|0;Rr=q[Xs>>2];q[Xs>>2]=0;if(Rr){An(Rr)}q[Ye>>2]=3044;Rr=q[Ye+32>>2];if(Rr){q[Ye+36>>2]=Rr;An(Rr)}return Ye|0}function xf(Ye){Ye=Ye|0;var Ys=0,Zs=0;q[Ye>>2]=3584;Ys=q[Ye+76>>2];if(Ys){An(Ys)}Zs=Ye+68|0;Ys=q[Zs>>2];q[Zs>>2]=0;if(Ys){An(Ys)}q[Ye>>2]=3044;Ys=q[Ye+32>>2];if(Ys){q[Ye+36>>2]=Ys;An(Ys)}An(Ye)}function yf(q){q=q|0;return 3}function zf(Ye){Ye=Ye|0;if(!(!q[Ye+60>>2]|!q[Ye+44>>2]|(!q[Ye+48>>2]|!q[Ye+52>>2]))){return q[Ye+56>>2]!=0|0}return 0}function Af(Ye,_s){Ye=Ye|0;_s=_s|0;var zt=0;if(!(q[_s+56>>2]|!_s|r[_s+24|0]!=3)){q[Ye+60>>2]=_s;zt=1}return zt|0}function Bf(Ye,_s){Ye=Ye|0;_s=_s|0;var At=0,Bt=0,Ct=0,Dt=0,Et=0,Ft=0,Gt=0,Ht=0,It=0,Jt=0,Kt=0;Gt=T-32|0;T=Gt;q[Gt+28>>2]=0;a:{b:{if(s[_s+38>>1]<=513){Et=q[_s+12>>2];At=q[_s+20>>2];Ct=q[_s+16>>2];Bt=Ct+4|0;if(Bt>>>0<4){At=At+1|0}Dt=Bt;Bt=At;if((Et|0)<(At|0)?1:(Et|0)<=(At|0)?t[_s+8>>2]>=Dt>>>0?0:1:0){break a}At=Ct+q[_s>>2]|0;At=r[At|0]|r[At+1|0]<<8|(r[At+2|0]<<16|r[At+3|0]<<24);q[Gt+28>>2]=At;q[_s+16>>2]=Dt;q[_s+20>>2]=Bt;break b}if(!tf(1,Gt+28|0,_s)){break a}At=q[Gt+28>>2]}if(!At){break a}Dt=Ye+76|0;uf(Dt,At);It=ah(Gt+8|0);c:{if(!bh(It,_s)){break c}Et=1;while(1){Ct=1<<(Ht&31);Ft=dh(It);Bt=q[Dt>>2]+(Ht>>>3&536870908)|0;Et=Et^Ft;Ft=q[Bt>>2]|Ct;d:{if(!(Et&1)){break d}Ft=q[Bt>>2]&(Ct^-1)}Ct=Ft;Et=Et^1;q[Bt>>2]=Ct;Ht=Ht+1|0;if((At|0)!=(Ht|0)){continue}break}Ht=0;Bt=q[_s+12>>2];Et=Bt;At=q[_s+20>>2];Ct=At;It=q[_s+16>>2];Dt=It+4|0;if(Dt>>>0<4){At=At+1|0}Jt=q[_s+8>>2];Ft=Dt;Dt=At;if((Bt|0)<(At|0)?1:(Bt|0)<=(At|0)?Jt>>>0>=Ft>>>0?0:1:0){break c}Kt=q[_s>>2];At=Kt+It|0;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u=x(u[Nt>>2]-qu);ru=u[Nt+20>>2];fu=x(u[Nt+4>>2]-ru);su=u[Nt+24>>2];gu=x(u[Nt+8>>2]-su);pu=x(x(x(x(cu*cu)+x(0))+x(fu*fu))+x(gu*gu));e:{if(!(pu>x(0))){hu=x(0);if(q[Ye+88>>2]>257){break e}}eu=x(eu-qu);nu=x(nu-ru);mu=x(mu-su);au=x(x(x(x(x(cu*eu)+x(0))+x(fu*nu))+x(gu*mu))/pu);gu=x(mu-x(gu*au));fu=x(nu-x(fu*au));cu=x(eu-x(cu*au));hu=x(E(x(x(x(gu*gu)+x(x(fu*fu)+x(x(cu*cu)+x(0))))/pu)))}eu=hu;Lt=Ye+80|0;_s=q[Lt>>2]+ -1|0;Mt=q[q[Ye+76>>2]+(_s>>>3&536870908)>>2];q[Lt>>2]=_s;cu=x(bu-iu);hu=x(x(cu*au)+iu);iu=x(lu-ou);bu=x(iu*eu);_s=Mt>>>(_s&31)&1;bu=x(hu+(_s?bu:x(-bu)));hu=x(x(iu*au)+ou);au=x(cu*eu);au=x(hu+(_s?x(-au):au));f:{if(((k(au),e(0))&2147483647)>>>0>=2139095041){_s=q[Ye+68>>2];q[_s>>2]=-2147483648;break f}_s=q[Ye+68>>2];Ye=_s;ku=C(+au+.5);g:{if(y(ku)<2147483648){Lt=~~ku;break g}Lt=-2147483648}q[Ye>>2]=Lt}Lt=((k(bu),e(0))&2147483647)>>>0>2139095040;ku=C(+bu+.5);h:{if(y(ku)<2147483648){Ye=~~ku;break h}Ye=-2147483648}q[_s+4>>2]=Lt?-2147483648:Ye;break c}i:{if(!ju){_s=q[Ye+72>>2];Mt=w(Ot,_s);break i}if((Mt|0)<=0){if(q[Ye+72>>2]<1){break c}Lt=q[Ye+68>>2];_s=0;while(1){q[Lt+(_s<<2)>>2]=0;_s=_s+1|0;if((_s|0)>2]){continue}break}break c}_s=q[Ye+72>>2];Mt=w(_s,Mt+ -1|0)}if((_s|0)<1){break c}Ot=q[Ye+68>>2];_s=0;while(1){q[Ot+(_s<<2)>>2]=q[(_s+Mt<<2)+Lt>>2];_s=_s+1|0;if((_s|0)>2]){continue}break}}T=Nt+48|0;return}cn();F()}function Ef(Ye){Ye=Ye|0;var _s=0;q[Ye>>2]=3812;_s=q[Ye+76>>2];if(_s){An(_s)}q[Ye>>2]=3044;_s=q[Ye+32>>2];if(_s){q[Ye+36>>2]=_s;An(_s)}return Ye|0}function Ff(Ye){Ye=Ye|0;var Lt=0;q[Ye>>2]=3812;Lt=q[Ye+76>>2];if(Lt){An(Lt)}q[Ye>>2]=3044;Lt=q[Ye+32>>2];if(Lt){q[Ye+36>>2]=Lt;An(Lt)}An(Ye)}function Gf(q){q=q|0;return 5}function Hf(Ye,Mt){Ye=Ye|0;Mt=Mt|0;var uu=0,vu=0,wu=0,xu=0,yu=0,zu=0,Au=0,Bu=0,Cu=0,Du=0,Eu=0;Bu=T-16|0;T=Bu;wu=q[Mt+12>>2];uu=q[Mt+20>>2];xu=q[Mt+16>>2];vu=xu+4|0;if(vu>>>0<4){uu=uu+1|0}yu=vu;vu=uu;a:{if((wu|0)<(uu|0)?1:(wu|0)<=(uu|0)?t[Mt+8>>2]>=yu>>>0?0:1:0){break a}uu=xu+q[Mt>>2]|0;uu=r[uu|0]|r[uu+1|0]<<8|(r[uu+2|0]<<16|r[uu+3|0]<<24);q[Mt+16>>2]=yu;q[Mt+20>>2]=vu;if((uu|0)<0){break a}uf(Ye+76|0,uu);yu=ah(Bu);b:{if(!bh(yu,Mt)){break b}if((uu|0)>=1){wu=1;while(1){xu=1<<(Au&31);zu=dh(yu);vu=q[Ye+76>>2]+(Au>>>3&536870908)|0;wu=wu^zu;zu=q[vu>>2]|xu;c:{if(!(wu&1)){break c}zu=q[vu>>2]&(xu^-1)}xu=zu;wu=wu^1;q[vu>>2]=xu;Au=Au+1|0;if((uu|0)!=(Au|0)){continue}break}}vu=q[Mt+12>>2];Au=vu;uu=q[Mt+20>>2];wu=uu;yu=q[Mt+16>>2];xu=yu+4|0;if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1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;h=o[b|0];q[e>>2]=h;q[e+4>>2]=h>>31;b=b+1|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 0:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;q[e>>2]=r[b|0];q[e+4>>2]=0;b=b+1|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 1:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;h=p[b>>1];q[e>>2]=h;q[e+4>>2]=h>>31;b=b+2|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 2:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;q[e>>2]=s[b>>1];q[e+4>>2]=0;b=b+2|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 3:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;h=q[b>>2];q[e>>2]=h;q[e+4>>2]=h>>31;b=b+4|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 4:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;q[e>>2]=q[b>>2];q[e+4>>2]=0;b=b+4|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 5:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){h=q[b+4>>2];e=(f<<3)+d|0;q[e>>2]=q[b>>2];q[e+4>>2]=h;b=b+8|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 6:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){h=q[b+4>>2];e=(f<<3)+d|0;q[e>>2]=q[b>>2];q[e+4>>2]=h;b=b+8|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}break a;case 7:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24<1){break c}g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;g=e;i=u[b>>2];f:{if(x(y(i))=x(1)?i>x(0)?~~x(A(x(C(x(i/x(4294967296)))),x(4294967296)))>>>0:~~x(D(x(x(i-x(~~i>>>0>>>0))/x(4294967296))))>>>0:0;k=~~i>>>0;break f}h=-2147483648;k=0}q[g>>2]=k;q[e+4>>2]=h;b=b+4|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}break c;case 8:e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24<1){break d}g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;g=e;j=v[b>>3];g:{if(y(j)<0x8000000000000000){h=y(j)>=1?j>0?~~A(C(j/4294967296),4294967295)>>>0:~~D((j- +(~~j>>>0>>>0))/4294967296)>>>0:0;k=~~j>>>0;break g}h=-2147483648;k=0}q[g>>2]=k;q[e+4>>2]=h;b=b+8|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}break d;case 9:break e}}e=o[a+24|0];if(((e|0)>(c|0)?c:e)<<24>>24>=1){g=q[q[a>>2]>>2];e=q[a+48>>2]+$n(q[a+40>>2],q[a+44>>2],b,0)|0;b=g+e|0;while(1){e=(f<<3)+d|0;q[e>>2]=r[b|0];q[e+4>>2]=0;b=b+1|0;f=f+1|0;e=o[a+24|0];if((f|0)<((e|0)>(c|0)?c:e)<<24>>24){continue}break}}if((e|0)>=(c|0)){break b}Dn((e<<3)+d|0,0,c-e<<3);break b}if((e|0)>=(c|0)){break b}break a}if((e|0)>=(c|0)){break b}Dn((e<<3)+d|0,0,c-e<<3)}return}Dn((e<<3)+d|0,0,c-e<<3)}function Lf(a){a=a|0;var b=0;q[a>>2]=4048;q[a>>2]=3044;b=q[a+32>>2];if(b){q[a+36>>2]=b;An(b)}return a|0}function Mf(a){a=a|0;var c=0;q[a>>2]=4048;q[a>>2]=3044;c=q[a+32>>2];if(c){q[a+36>>2]=c;An(c)}An(a)}function Nf(a){a=a|0;return 6}function Of(a){a=a|0;var d=0;a:{if(!q[a- -64>>2]|!q[a+68>>2]|(!q[a+44>>2]|!q[a+48>>2])){break a}if(!q[a+52>>2]|!q[a+56>>2]){break a}d=q[a+92>>2]!=-1}return d|0}function Pf(a,l){a=a|0;l=l|0;var m=0;if(!(q[l+56>>2]|r[l+24|0]!=3)){q[a- -64>>2]=l;m=1}return m|0}function Qf(a,l){a=a|0;l=l|0;var n=0,o=0,p=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0;w=q[l+12>>2];p=w;o=q[l+20>>2];u=o;x=q[l+16>>2];n=x+4|0;if(n>>>0<4){o=o+1|0}y=q[l+8>>2];t=n;n=o;a:{if((p|0)<(n|0)?1:(p|0)<=(n|0)?y>>>0>=t>>>0?0:1:0){break a}z=q[l>>2];o=x+z|0;p=r[o|0]|r[o+1|0]<<8|(r[o+2|0]<<16|r[o+3|0]<<24);q[l+16>>2]=t;q[l+20>>2]=n;n=w;o=u;v=x+8|0;if(v>>>0<8){o=o+1|0}if((n|0)<(o|0)?1:(n|0)<=(o|0)?y>>>0>=v>>>0?0:1:0){break a}n=t+z|0;n=r[n|0]|r[n+1|0]<<8|(r[n+2|0]<<16|r[n+3|0]<<24);q[l+16>>2]=v;q[l+20>>2]=o;if((p|0)>(n|0)){break a}q[a+16>>2]=n;q[a+12>>2]=p;t=p;p=(n>>31)-((p>>31)+(n>>>0

>>0)|0)|0;n=n-t|0;if(!p&n>>>0>2147483646|p>>>0>0){break a}p=n+1|0;q[a+20>>2]=p;t=a+24|0;n=(p|0)/2|0;q[t>>2]=n;q[a+28>>2]=0-n;if(!(p&1)){q[t>>2]=n+ -1}if(s[l+38>>1]<=513){if((w|0)<(o|0)?1:(w|0)<=(o|0)?y>>>0>v>>>0?0:1:0){break a}n=r[v+z|0];o=u;u=x+9|0;if(u>>>0<9){o=o+1|0}p=l;q[p+16>>2]=u;q[p+20>>2]=o;if(n>>>0>1){break a}q[a+88>>2]=n-1|0?0:1}A=bh(a+108|0,l)}return A|0}function Rf(a,l,r,s,B,C){a=a|0;l=l|0;r=r|0;s=s|0;B=B|0;C=C|0;var D=0,E=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0;E=T-32|0;T=E;q[a+68>>2]=C;s=q[a+56>>2];B=q[s>>2];C=s+4|0;D=q[C>>2];q[E+24>>2]=0;q[E+16>>2]=0;q[E+20>>2]=0;a:{B=D-B|0;if((B|0)<1){break a}s=q[s>>2];if((s|0)!=q[C>>2]){P=B>>2;Q=a+60|0;R=a+108|0;K=a+8|0;L=a+16|0;M=a+32|0;N=a+20|0;O=a+12|0;S=a+56|0;while(1){Sf(Q,q[(I<<2)+s>>2],E+16|0);B=q[E+20>>2];D=B>>31;C=q[E+16>>2];G=C>>31;J=q[E+24>>2];H=J>>31;s=0;H=H^H+J;D=H+((D^B+D)+(G^C+G)|0)|0;if(D>>>0>>0){s=1}b:{if(!(s|D)){q[E+16>>2]=q[a+104>>2];break b}G=q[a+104>>2];H=G>>31;B=ao($n(G,H,B,B>>31),V,D,s);q[E+20>>2]=B;s=ao($n(G,H,C,C>>31),V,D,s);q[E+16>>2]=s;C=s;s=s>>31;s=(G-(C+s^s)|0)+((B|0)<0?B:0-B|0)|0;if((J|0)>=0){q[E+24>>2]=s;break b}q[E+24>>2]=0-s}s=dh(R);C=q[E+16>>2];c:{if(!s){B=q[E+20>>2];break c}q[E+24>>2]=0-q[E+24>>2];B=0-q[E+20>>2]|0;q[E+20>>2]=B;C=0-C|0;q[E+16>>2]=C}d:{if((C|0)>=0){s=q[a+104>>2];C=s+q[E+24>>2]|0;s=s+B|0;break d}e:{if((B|0)<=-1){C=q[E+24>>2];s=C>>31;s=s^s+C;break e}C=q[E+24>>2];s=C>>31;s=q[a+100>>2]-(s^s+C)|0}if((C|0)<=-1){C=B;B=B>>31;C=C+B^B;break d}C=B;B=B>>31;C=q[a+100>>2]-(C+B^B)|0}B=q[a+100>>2];f:{if(!(s|C)){C=B;s=B;break f}if(!((B|0)!=(C|0)|s)){s=C;break f}if(!((s|0)!=(B|0)|C)){C=s;break f}g:{if(s){break g}D=q[a+104>>2];if((D|0)>=(C|0)){break g}C=(D<<1)-C|0;s=0;break f}h:{if((s|0)!=(B|0)){break h}D=q[a+104>>2];if((D|0)<=(C|0)){break h}C=(D<<1)-C|0;break f}i:{if((B|0)!=(C|0)){break i}B=q[a+104>>2];if((B|0)<=(s|0)){break i}s=(B<<1)-s|0;break f}if(C){break f}C=0;B=q[a+104>>2];if((B|0)>=(s|0)){break f}s=(B<<1)-s|0}q[E+12>>2]=C;q[E+8>>2]=s;j:{if(q[K>>2]<1){break j}C=0;while(1){D=q[L>>2];k:{if((s|0)>(D|0)){B=q[M>>2];q[B+(C<<2)>>2]=D;break k}B=q[M>>2];D=B+(C<<2)|0;G=q[O>>2];if((s|0)<(G|0)){q[D>>2]=G;break k}q[D>>2]=s}C=C+1|0;D=q[K>>2];if((C|0)<(D|0)){s=q[(E+8|0)+(C<<2)>>2];continue}break}s=0;if((D|0)<1){break j}C=I<<3;G=C+r|0;J=l+C|0;while(1){D=s<<2;C=D+G|0;D=q[D+J>>2]+q[B+D>>2]|0;q[C>>2]=D;l:{if((D|0)>q[L>>2]){H=D-q[N>>2]|0}else{if((D|0)>=q[O>>2]){break l}H=D+q[N>>2]|0}q[C>>2]=H}s=s+1|0;if((s|0)>2]){continue}break}}I=I+1|0;if((I|0)>=(P|0)){break a}B=q[S>>2];s=q[B>>2];if(q[B+4>>2]-s>>2>>>0>I>>>0){continue}break}}cn();F()}T=E+32|0;return 1}function Sf(a,l,s){a=a|0;l=l|0;s=s|0;var B=0,C=0,U=0,W=0,X=0,Y=0,Z=0,_=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0;C=T-96|0;T=C;B=q[a+16>>2];o[C+92|0]=1;q[C+88>>2]=l;q[C+84>>2]=l;q[C+80>>2]=B;W=q[a+20>>2];U=q[W>>2];a:{b:{c:{d:{B=q[q[B+28>>2]+(l<<2)>>2];if(q[W+4>>2]-U>>2>>>0>B>>>0){B=q[q[a+8>>2]+(q[U+(B<<2)>>2]<<2)>>2];U=q[a+4>>2];if(!r[U+84|0]){B=q[q[U+68>>2]+(B<<2)>>2]}q[C+72>>2]=0;q[C+76>>2]=0;W=C- -64|0;q[W>>2]=0;q[W+4>>2]=0;q[C+56>>2]=0;q[C+60>>2]=0;Kf(U,B,o[U+24|0],C+56|0);if((l|0)==-1){break a}B=l+1|0;W=(B>>>0)%3|0?B:l+ -2|0;ea=((l>>>0)%3|0?-1:2)+l|0;la=a+28|0;X=!q[la>>2];ma=a+20|0;na=a+16|0;oa=a+8|0;while(1){U=W;B=ea;e:{if(X){break e}B=l+1|0;U=(B>>>0)%3|0?B:l+ -2|0;B=l+ -1|0;if((l>>>0)%3){break e}B=l+2|0}X=q[ma>>2];l=q[X>>2];U=q[q[q[na>>2]+28>>2]+(U<<2)>>2];if(q[X+4>>2]-l>>2>>>0<=U>>>0){break d}U=q[q[oa>>2]+(q[l+(U<<2)>>2]<<2)>>2];X=a+4|0;l=q[X>>2];if(!r[l+84|0]){U=q[q[l+68>>2]+(U<<2)>>2]}q[C+48>>2]=0;q[C+52>>2]=0;q[C+40>>2]=0;q[C+44>>2]=0;q[C+32>>2]=0;q[C+36>>2]=0;Kf(l,U,o[l+24|0],C+32|0);U=q[ma>>2];l=q[U>>2];B=q[q[q[na>>2]+28>>2]+(B<<2)>>2];if(q[U+4>>2]-l>>2>>>0<=B>>>0){break c}U=q[q[oa>>2]+(q[l+(B<<2)>>2]<<2)>>2];l=q[X>>2];if(!r[l+84|0]){U=q[q[l+68>>2]+(U<<2)>>2]}X=C+24|0;B=X;q[B>>2]=0;q[B+4>>2]=0;_=C+16|0;B=_;q[B>>2]=0;q[B+4>>2]=0;q[C+8>>2]=0;q[C+12>>2]=0;Kf(l,U,o[l+24|0],C+8|0);B=q[C+8>>2];l=q[C+56>>2];fa=B-l|0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$|0;W=B;B=Y;W=W+B|0;if(W>>>0>>0){l=l+1|0}B=a;W=B+W|0;a=l+U|0;a=W>>>0>>0?a+1|0:a;B=W;if(_){break b}}if((B|0)<536870913){break a}a=((a&536870911)<<3|B>>>29)&7;l=0;Y=ao(Y,$,a,l);Z=ao(Z,ca,a,l);aa=ao(aa,da,a,l);break a}cn();F()}cn();F()}cn();F()}if((a|0)<0?1:(a|0)<=0?B>>>0>=536870913?0:1:0){break a}l=a>>>29;a=(a&536870911)<<3|B>>>29;Y=ao(Y,$,a,l);Z=ao(Z,ca,a,l);aa=ao(aa,da,a,l)}q[s+8>>2]=Y;q[s+4>>2]=Z;q[s>>2]=aa;T=C+96|0}function Tf(a,l){a=a|0;l=l|0;if(l>>>0<=1){q[a+28>>2]=l;a=1}else{a=0}return a|0}function Uf(a){var l=0,s=0,F=0;l=q[a+8>>2];F=q[a>>2];a:{if(r[a+12|0]){b:{c:{d:{e:{if((l|0)==-1){break e}s=l+1|0;l=(s>>>0)%3|0?s:l+ -2|0;if((l|0)==-1|q[q[F>>2]+(l>>>3&536870908)>>2]>>>(l&31)&1){break e}l=q[q[q[F+64>>2]+12>>2]+(l<<2)>>2];if((l|0)!=-1){break d}}q[a+8>>2]=-1;break c}s=l+1|0;l=(s>>>0)%3|0?s:l+ -2|0;q[a+8>>2]=l;if((l|0)!=-1){break b}}l=-1;s=q[a+4>>2];f:{if((s|0)==-1){break f}s=s+((s>>>0)%3|0?-1:2)|0;if((s|0)==-1|q[q[F>>2]+(s>>>3&536870908)>>2]>>>(s&31)&1){break f}F=q[q[q[F+64>>2]+12>>2]+(s<<2)>>2];if((F|0)==-1){break f}if((F>>>0)%3){l=F+ -1|0;break f}l=F+2|0}o[a+12|0]=0;q[a+8>>2]=l;return}if((l|0)!=q[a+4>>2]){break a}q[a+8>>2]=-1;return}s=-1;g:{if((l|0)==-1){break g}l=l+((l>>>0)%3|0?-1:2)|0;if((l|0)==-1|q[q[F>>2]+(l>>>3&536870908)>>2]>>>(l&31)&1){break g}l=q[q[q[F+64>>2]+12>>2]+(l<<2)>>2];if((l|0)==-1){break g}if((l>>>0)%3){s=l+ -1|0;break g}s=l+2|0}q[a+8>>2]=s}}function Vf(a,r,T,V){var ra=0,sa=0,ta=0,ua=0,va=0,wa=0,xa=0,ya=0;q[a>>2]=3044;q[a+4>>2]=r;r=q[T+8>>2];ra=q[T+12>>2];sa=q[T+16>>2];ua=q[T+20>>2];va=q[T>>2];wa=q[T+4>>2];q[a+40>>2]=0;ta=a+32|0;q[ta>>2]=0;q[ta+4>>2]=0;q[a+24>>2]=sa;q[a+28>>2]=ua;q[a+16>>2]=r;q[a+20>>2]=ra;q[a+8>>2]=va;q[a+12>>2]=wa;a:{r=q[T+28>>2]-q[T+24>>2]|0;b:{if(!r){break b}ra=r>>2;if(ra>>>0>=1073741824){break a}r=Mm(r);q[a+32>>2]=r;sa=a+36|0;q[sa>>2]=r;q[a+40>>2]=r+(ra<<2);ra=q[T+24>>2];T=q[T+28>>2]-ra|0;if((T|0)<1){break b}xa=sa,ya=Cn(r,ra,T)+T|0,q[xa>>2]=ya}q[a>>2]=5044;r=q[V+4>>2];q[a+44>>2]=q[V>>2];q[a+48>>2]=r;r=q[V+12>>2];q[a+52>>2]=q[V+8>>2];q[a+56>>2]=r;return}bn();F()}function Wf(a,r,T,V,za,Aa){a=a|0;r=r|0;T=T|0;V=V|0;za=za|0;Aa=Aa|0;var Ba=0,Ca=0,Da=0,Ea=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0,Na=0,Oa=0,Pa=0,Qa=0,Ra=0;q[a+8>>2]=za;Aa=a+32|0;Ca=q[Aa>>2];V=q[a+36>>2]-Ca>>2;a:{if(V>>>0>>0){Fa(Aa,za-V|0);break a}if(V>>>0<=za>>>0){break a}q[a+36>>2]=Ca+(za<<2)}Ra=q[a+52>>2];Oa=q[a+48>>2];V=0;Aa=(za&1073741823)!=(za|0)?-1:za<<2;Na=Dn(Mm(Aa),0,Aa);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a|0)>=(Ca|0)){break f}V=q[Da+(V<<2)>>2];if((V|0)>=(Ca|0)){break f}if((za|0)>=1){Ba=w(V,za);a=w(a,za);Da=w(za,Ka);V=0;while(1){q[(V<<2)+Na>>2]=(q[(V+Ba<<2)+T>>2]+q[(a+V<<2)+T>>2]|0)-q[(V+Da<<2)+T>>2];V=V+1|0;if((za|0)!=(V|0)){continue}break}}if((Aa|0)<1){break e}V=0;while(1){a=V<<2;Aa=q[a+Na>>2];Da=q[Ha>>2];g:{if((Aa|0)>(Da|0)){Ba=q[Ga>>2];q[a+Ba>>2]=Da;break g}Ba=q[Ga>>2];a=a+Ba|0;Da=q[Ea>>2];if((Aa|0)<(Da|0)){q[a>>2]=Da;break g}q[a>>2]=Aa}V=V+1|0;Aa=q[Ia>>2];if((V|0)<(Aa|0)){continue}break}V=0;if((Aa|0)<1){break e}a=Ma<<2;Ma=a+T|0;Da=a+r|0;while(1){Aa=V<<2;a=Aa+Ma|0;Aa=q[Aa+Da>>2]+q[Aa+Ba>>2]|0;q[a>>2]=Aa;h:{if((Aa|0)>q[Ha>>2]){Aa=Aa-q[Ja>>2]|0}else{if((Aa|0)>=q[Ea>>2]){break h}Aa=Aa+q[Ja>>2]|0}q[a>>2]=Aa}V=V+1|0;Aa=q[Ia>>2];if((V|0)<(Aa|0)){continue}break}break e}cn();F()}if((Aa|0)<1){break e}Da=(w(Ca+ -1|0,za)<<2)+T|0;V=0;while(1){a=V<<2;Aa=q[a+Da>>2];Ka=q[Ha>>2];i:{if((Aa|0)>(Ka|0)){Ba=q[Ga>>2];q[a+Ba>>2]=Ka;break i}Ba=q[Ga>>2];a=a+Ba|0;Ka=q[Ea>>2];if((Aa|0)<(Ka|0)){q[a>>2]=Ka;break i}q[a>>2]=Aa}V=V+1|0;Aa=q[Ia>>2];if((V|0)<(Aa|0)){continue}break}V=0;if((Aa|0)<1){break e}a=Ma<<2;Ma=a+T|0;Da=a+r|0;while(1){Aa=V<<2;a=Aa+Ma|0;Aa=q[A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xa=Sa-q[Va>>2]|0}else{if((Sa|0)>=q[Wa>>2]){break d}Xa=Sa+q[Va>>2]|0}q[V>>2]=Xa}Aa=Aa+1|0;Ta=q[_a>>2];if((Aa|0)<(Ta|0)){continue}break}}V=q[a+56>>2];eb=q[V>>2];V=q[V+4>>2]-eb|0;if((V|0)>=5){fb=V>>2;gb=q[a+48>>2];kb=za<<2;lb=q[a+52>>2];Za=a+16|0;_a=a+32|0;Wa=a+8|0;bb=a+20|0;cb=a+12|0;Va=1;while(1){e:{f:{g:{if(fb>>>0>Va>>>0){Aa=q[(Va<<2)+eb>>2];hb=(za|0)<1;if(!hb){Dn($a,0,kb)}if((Aa|0)==-1){a=w(za,Va);break f}ib=q[gb+12>>2];Ya=0;V=Aa;while(1){a=q[ib+(V<<2)>>2];h:{if((a|0)==-1){break h}Ua=-1;ab=q[lb>>2];Sa=q[gb>>2];jb=q[ab+(q[Sa+(a<<2)>>2]<<2)>>2];Xa=a+1|0;Xa=(Xa>>>0)%3|0?Xa:a+ -2|0;if((Xa|0)!=-1){Xa=q[Sa+(Xa<<2)>>2]}else{Xa=-1}a=a+((a>>>0)%3|0?-1:2)|0;if((a|0)!=-1){Ua=q[Sa+(a<<2)>>2]}if((jb|0)>=(Va|0)){break h}a=q[(Xa<<2)+ab>>2];if((a|0)>=(Va|0)){break h}Sa=q[ab+(Ua<<2)>>2];if((Sa|0)>=(Va|0)){break h}i:{if(hb){break i}Ua=w(za,Sa);a=w(a,za);ab=w(za,jb);Sa=0;while(1){q[db+(Sa<<2)>>2]=(q[(Sa+Ua<<2)+T>>2]+q[(a+Sa<<2)+T>>2]|0)-q[(Sa+ab<<2)+T>>2];Sa=Sa+1|0;if((Sa|0)!=(za|0)){continue}break}Sa=0;if((za|0)<=0){break i}while(1){a=Sa<<2;Ua=a+$a|0;q[Ua>>2]=q[Ua>>2]+q[a+db>>2];Sa=Sa+1|0;if((Sa|0)!=(za|0)){continue}break}}Ya=Ya+1|0}V=((V>>>0)%3|0?-1:2)+V|0;a=-1;j:{if((V|0)==-1){break j}V=q[ib+(V<<2)>>2];a=-1;if((V|0)==-1){break j}a=V+ -1|0;if((V>>>0)%3){break j}a=V+2|0}V=(a|0)==(Aa|0)?-1:a;if((V|0)!=-1){continue}break}a=w(za,Va);if(!Ya){break f}Sa=0;if((za|0)<=0){break g}while(1){V=(Sa<<2)+$a|0;q[V>>2]=q[V>>2]/(Ya|0);Sa=Sa+1|0;if((Sa|0)!=(za|0)){continue}break}break g}cn();F()}if((Ta|0)<1){break e}Sa=0;while(1){V=Sa<<2;Aa=q[V+$a>>2];Ta=q[Za>>2];k:{if((Aa|0)>(Ta|0)){Ua=q[_a>>2];q[V+Ua>>2]=Ta;break k}Ua=q[_a>>2];V=V+Ua|0;Ta=q[cb>>2];if((Aa|0)<(Ta|0)){q[V>>2]=Ta;break k}q[V>>2]=Aa}Sa=Sa+1|0;Ta=q[Wa>>2];if((Sa|0)<(Ta|0)){continue}break}Aa=0;if((Ta|0)<1){break e}a=a<<2;Sa=a+T|0;Ya=a+r|0;while(1){V=Aa<<2;a=V+Sa|0;V=q[V+Ya>>2]+q[V+Ua>>2]|0;q[a>>2]=V;l:{if((V|0)>q[Za>>2]){V=V-q[bb>>2]|0}else{if((V|0)>=q[cb>>2]){break l}V=V+q[bb>>2]|0}q[a>>2]=V}Aa=Aa+1|0;Ta=q[Wa>>2];if((Aa|0)<(Ta|0)){continue}break}break e}if((Ta|0)<1){break e}Ya=(w(Va+ -1|0,za)<<2)+T|0;Sa=0;while(1){V=Sa<<2;Aa=q[V+Ya>>2];Ta=q[Za>>2];m:{if((Aa|0)>(Ta|0)){Ua=q[_a>>2];q[V+Ua>>2]=Ta;break m}Ua=q[_a>>2];V=V+Ua|0;Ta=q[cb>>2];if((Aa|0)<(Ta|0)){q[V>>2]=Ta;break m}q[V>>2]=Aa}Sa=Sa+1|0;Ta=q[Wa>>2];if((Sa|0)<(Ta|0)){continue}break}Aa=0;if((Ta|0)<1){break e}a=a<<2;Sa=a+T|0;Ya=a+r|0;while(1){V=Aa<<2;a=V+Sa|0;V=q[V+Ya>>2]+q[V+Ua>>2]|0;q[a>>2]=V;n:{if((V|0)>q[Za>>2]){V=V-q[bb>>2]|0}else{if((V|0)>=q[cb>>2]){break n}V=V+q[bb>>2]|0}q[a>>2]=V}Aa=Aa+1|0;Ta=q[Wa>>2];if((Aa|0)<(Ta|0)){continue}break}}Va=Va+1|0;if((Va|0)<(fb|0)){continue}break}}An(db);An($a);return 1}function Yf(a){a=a|0;var r=0;q[a>>2]=5324;r=q[a+96>>2];if(r){An(r)}r=q[a+84>>2];if(r){An(r)}r=q[a+72>>2];if(r){An(r)}r=q[a+60>>2];if(r){An(r)}q[a>>2]=3044;r=q[a+32>>2];if(r){q[a+36>>2]=r;An(r)}return a|0}function Zf(a){a=a|0;var T=0;q[a>>2]=5324;T=q[a+96>>2];if(T){An(T)}T=q[a+84>>2];if(T){An(T)}T=q[a+72>>2];if(T){An(T)}T=q[a+60>>2];if(T){An(T)}q[a>>2]=3044;T=q[a+32>>2];if(T){q[a+36>>2]=T;An(T)}An(a)}function _f(a,V,za,Aa,mb,nb){a=a|0;V=V|0;za=za|0;Aa=Aa|0;mb=mb|0;nb=nb|0;var ob=0,pb=0,qb=0,rb=0,sb=0,tb=0,ub=0,vb=0,wb=0,xb=0,yb=0,zb=0,Ab=0,Bb=0,Cb=0,Db=0,Eb=0,Fb=0,Gb=0,Hb=0,Ib=0,Jb=0,Kb=0,Lb=0,Mb=0;qb=T+ -64|0;T=qb;q[a+8>>2]=mb;nb=a+32|0;rb=q[nb>>2];Aa=q[a+36>>2]-rb>>2;a:{if(Aa>>>0>>0){Fa(nb,mb-Aa|0);break a}if(Aa>>>0<=mb>>>0){break a}q[a+36>>2]=rb+(mb<<2)}q[qb+56>>2]=0;q[qb+60>>2]=0;q[qb+48>>2]=0;q[qb+52>>2]=0;q[qb+40>>2]=0;q[qb+44>>2]=0;Aa=qb+32|0;q[Aa>>2]=0;q[Aa+4>>2]=0;q[qb+24>>2]=0;q[qb+28>>2]=0;q[qb+16>>2]=0;q[qb+20>>2]=0;q[qb>>2]=0;nb=0;if(mb){Ad(qb+16|0,mb,qb);pb=q[qb+28>>2];nb=q[Aa>>2]}q[qb>>2]=0;Aa=nb-pb>>2;b:{if(Aa>>>0>=mb>>>0){if(Aa>>>0<=mb>>>0){break b}q[qb+32>>2]=(mb<<2)+pb;break b}Ad(qb+16|12,mb-Aa|0,qb)}q[qb>>2]=0;nb=q[qb+40>>2];Aa=q[qb+44>>2]-nb>>2;c:{if(Aa>>>0>=mb>>>0){if(Aa>>>0<=mb>>>0){break c}q[qb+44>>2]=nb+(mb<<2);break c}Ad(qb+40|0,mb-Aa|0,qb)}q[qb>>2]=0;nb=q[qb+52>>2];Aa=q[qb+56>>2]-nb>>2;d:{if(Aa>>>0>=mb>>>0){if(Aa>>>0<=mb>>>0){break d}q[qb+56>>2]=nb+(mb<<2);break d}Ad(qb+52|0,mb-Aa|0,qb)}tb=a+8|0;e:{if(q[tb>>2]<=0){break e}vb=q[qb+16>>2];pb=0;sb=a+16|0;Aa=a+32|0;Ab=a+12|0;while(1){nb=pb<<2;ob=q[nb+vb>>2];wb=q[sb>>2];f:{if((ob|0)>(wb|0)){rb=q[Aa>>2];q[nb+rb>>2]=wb;break f}rb=q[Aa>>2];nb=nb+rb|0;wb=q[Ab>>2];if((ob|0)<(wb|0)){q[nb>>2]=wb;break f}q[nb>>2]=ob}pb=pb+1|0;nb=q[tb>>2];if((pb|0)<(nb|0)){continue}break}if((nb|0)<1){break e}nb=0;tb=a+16|0;pb=a+20|0;vb=a+8|0;sb=a+12|0;while(1){ob=nb<<2;Aa=ob+za|0;ob=q[V+ob>>2]+q[ob+rb>>2]|0;q[Aa>>2]=ob;g:{if((ob|0)>q[tb>>2]){ob=ob-q[pb>>2]|0}else{if((ob|0)>=q[sb>>2]){break g}ob=ob+q[pb>>2]|0}q[Aa>>2]=ob}nb=nb+1|0;if((nb|0)>2]){continue}break}}Lb=q[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<2)+za>>2];pb=pb+1|0;if((pb|0)!=(mb|0)){continue}break}}ob=4;nb=nb+1|0;if((nb|0)==4){break o}}q:{if(sb&1){xb=Aa+1|0;Aa=(xb>>>0)%3|0?xb:Aa+ -2|0;ob=-1;if((Aa|0)==-1){break q}Aa=q[ub+(Aa<<2)>>2];ob=-1;if((Aa|0)==-1){break q}ob=Aa+1|0;ob=(ob>>>0)%3|0?ob:Aa+ -2|0;break q}Aa=((Aa>>>0)%3|0?-1:2)+Aa|0;ob=-1;if((Aa|0)==-1){break q}Aa=q[ub+(Aa<<2)>>2];ob=-1;if((Aa|0)==-1){break q}ob=Aa+ -1|0;if((Aa>>>0)%3){break q}ob=Aa+2|0}r:{if((ob|0)==(rb|0)){break r}Aa=ob;ob=(ob|0)!=-1;pb=(ob|sb^-1)&1;Aa=pb?Aa:-1;sb=ob&sb;if(!((Db|0)==-1|pb)){ob=q[Gb>>2];if((ob|0)==-1){break r}sb=0;if((ob>>>0)%3){Aa=ob+ -1|0}else{Aa=ob+2|0}}if((Aa|0)!=-1){continue}}break}ob=nb;if((ob|0)<1){break n}}ub=(mb|0)<1;if(!ub){Dn(Bb,0,Mb)}Aa=ob+ -1|0;sb=(Aa<<2)+Hb|0;Aa=w(Aa,12)+a|0;xb=Aa+60|0;zb=q[Aa- -64>>2];rb=0;Cb=q[qb>>2];Aa=0;nb=0;while(1){pb=q[sb>>2];q[sb>>2]=pb+1;if(zb>>>0<=pb>>>0){break i}s:{if(q[q[xb>>2]+(pb>>>3&536870908)>>2]>>>(pb&31)&1){break s}nb=nb+1|0;if(ub){break s}yb=q[(qb+16|0)+w(Aa,12)>>2];pb=0;while(1){Db=pb<<2;Gb=Db+Cb|0;q[Gb>>2]=q[Gb>>2]+q[yb+Db>>2];pb=pb+1|0;if((pb|0)!=(mb|0)){continue}break}}Aa=Aa+1|0;if((ob|0)!=(Aa|0)){continue}break}ob=w(mb,tb);Aa=ob;if(!nb){break m}pb=0;if((mb|0)>0){break l}break k}Aa=w(mb,tb)}if(q[vb>>2]<1){break j}sb=(w(tb+ -1|0,mb)<<2)+za|0;pb=0;while(1){nb=pb<<2;ob=q[nb+sb>>2];ub=q[Ab>>2];t:{if((ob|0)>(ub|0)){rb=q[wb>>2];q[nb+rb>>2]=ub;break t}rb=q[wb>>2];nb=nb+rb|0;ub=q[Fb>>2];if((ob|0)<(ub|0)){q[nb>>2]=ub;break t}q[nb>>2]=ob}pb=pb+1|0;ob=q[vb>>2];if((pb|0)<(ob|0)){continue}break}nb=0;if((ob|0)<1){break j}Aa=Aa<<2;pb=Aa+za|0;sb=V+Aa|0;while(1){ob=nb<<2;Aa=ob+pb|0;ob=q[ob+sb>>2]+q[ob+rb>>2]|0;q[Aa>>2]=ob;u:{if((ob|0)>q[Ab>>2]){ob=ob-q[Eb>>2]|0}else{if((ob|0)>=q[Fb>>2]){break u}ob=ob+q[Eb>>2]|0}q[Aa>>2]=ob}nb=nb+1|0;if((nb|0)>2]){continue}break}break j}cn();F()}while(1){Aa=(pb<<2)+Bb|0;q[Aa>>2]=q[Aa>>2]/(nb|0);pb=pb+1|0;if((pb|0)!=(mb|0)){continue}break}}if(q[vb>>2]<1){break j}pb=0;while(1){Aa=pb<<2;nb=q[Aa+Bb>>2];sb=q[Ab>>2];v:{if((nb|0)>(sb|0)){rb=q[wb>>2];q[Aa+rb>>2]=sb;break v}rb=q[wb>>2];Aa=Aa+rb|0;sb=q[Fb>>2];if((nb|0)<(sb|0)){q[Aa>>2]=sb;break v}q[Aa>>2]=nb}pb=pb+1|0;Aa=q[vb>>2];if((pb|0)<(Aa|0)){continue}break}nb=0;if((Aa|0)<1){break j}Aa=ob<<2;pb=Aa+za|0;sb=V+Aa|0;while(1){ob=nb<<2;Aa=ob+pb|0;ob=q[ob+sb>>2]+q[ob+rb>>2]|0;q[Aa>>2]=ob;w:{if((ob|0)>q[Ab>>2]){ob=ob-q[Eb>>2]|0}else{if((ob|0)>=q[Fb>>2]){break w}ob=ob+q[Eb>>2]|0}q[Aa>>2]=ob}nb=nb+1|0;if((nb|0)>2]){continue}break}}rb=1;tb=tb+1|0;if((tb|0)<(Kb|0)){continue}break}}a=q[qb>>2];if(a){q[qb+4>>2]=a;An(a)}An(Hb);a=q[qb+52>>2];if(a){q[qb+56>>2]=a;An(a)}a=q[qb+40>>2];if(a){q[qb+44>>2]=a;An(a)}a=q[qb+28>>2];if(a){q[qb+32>>2]=a;An(a)}a=q[qb+16>>2];if(a){q[qb+20>>2]=a;An(a)}T=qb- -64|0;return rb|0}bn();F()}function $f(a){a=a|0;var V=0,za=0;q[a>>2]=5560;V=q[a+76>>2];if(V){An(V)}za=a+68|0;V=q[za>>2];q[za>>2]=0;if(V){An(V)}q[a>>2]=3044;V=q[a+32>>2];if(V){q[a+36>>2]=V;An(V)}return a|0}function ag(a){a=a|0;var Aa=0,Fa=0;q[a>>2]=5560;Aa=q[a+76>>2];if(Aa){An(Aa)}Fa=a+68|0;Aa=q[Fa>>2];q[Fa>>2]=0;if(Aa){An(Aa)}q[a>>2]=3044;Aa=q[a+32>>2];if(Aa){q[a+36>>2]=Aa;An(Aa)}An(a)}function bg(a,mb,nb,Nb,Ob,Pb){a=a|0;mb=mb|0;nb=nb|0;Nb=Nb|0;Ob=Ob|0;Pb=Pb|0;var Qb=0,Rb=0,Sb=0,Tb=0,Ub=0,Vb=0,Wb=0,Xb=0,Yb=0,Zb=0,_b=0,$b=0;q[a+64>>2]=Pb;q[a+72>>2]=Ob;Pb=Mm((Ob&1073741823)!=(Ob|0)?-1:Ob<<2);Nb=q[a+68>>2];q[a+68>>2]=Pb;if(Nb){An(Nb)}q[a+8>>2]=Ob;Pb=a+32|0;Qb=q[Pb>>2];Nb=q[a+36>>2]-Qb>>2;a:{if(Nb>>>0>>0){Fa(Pb,Ob-Nb|0);break a}if(Nb>>>0<=Ob>>>0){break a}q[a+36>>2]=Qb+(Ob<<2)}b:{Nb=q[a+56>>2];Qb=q[Nb+4>>2];Pb=q[Nb>>2];Nb=Qb-Pb|0;if((Nb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ob+20>>2];gc=x(u[Ob+4>>2]-tc);uc=u[Ob+24>>2];hc=x(u[Ob+8>>2]-uc);qc=x(x(x(x(ec*ec)+x(0))+x(gc*gc))+x(hc*hc));d:{if(!(qc>x(0))){ic=x(0);if(q[a+88>>2]>257){break d}}fc=x(fc-sc);oc=x(oc-tc);nc=x(nc-uc);bc=x(x(x(x(x(ec*fc)+x(0))+x(gc*oc))+x(hc*nc))/qc);hc=x(nc-x(hc*bc));gc=x(oc-x(gc*bc));ec=x(fc-x(ec*bc));ic=x(E(x(x(x(hc*hc)+x(x(gc*gc)+x(x(ec*ec)+x(0))))/qc)))}fc=ic;nb=a+80|0;mb=q[nb>>2]+ -1|0;Nb=q[q[a+76>>2]+(mb>>>3&536870908)>>2];q[nb>>2]=mb;ec=x(dc-jc);ic=x(x(ec*bc)+jc);jc=x(mc-pc);dc=x(jc*fc);mb=Nb>>>(mb&31)&1;dc=x(ic+(mb?dc:x(-dc)));ic=x(x(jc*bc)+pc);bc=x(ec*fc);bc=x(ic+(mb?x(-bc):bc));e:{if(((k(bc),e(0))&2147483647)>>>0>=2139095041){mb=q[a+68>>2];q[mb>>2]=-2147483648;break e}mb=q[a+68>>2];a=mb;lc=C(+bc+.5);f:{if(y(lc)<2147483648){nb=~~lc;break f}nb=-2147483648}q[a>>2]=nb}nb=((k(dc),e(0))&2147483647)>>>0>2139095040;lc=C(+dc+.5);g:{if(y(lc)<2147483648){a=~~lc;break g}a=-2147483648}q[mb+4>>2]=nb?-2147483648:a;break b}h:{if(!kc){mb=q[a+72>>2];Nb=w(Pb,mb);break h}if((Nb|0)<=0){if(q[a+72>>2]<1){break b}nb=q[a+68>>2];mb=0;while(1){q[nb+(mb<<2)>>2]=0;mb=mb+1|0;if((mb|0)>2]){continue}break}break b}mb=q[a+72>>2];Nb=w(mb,Nb+ -1|0)}if((mb|0)<1){break b}Pb=q[a+68>>2];mb=0;while(1){q[Pb+(mb<<2)>>2]=q[(mb+Nb<<2)+nb>>2];mb=mb+1|0;if((mb|0)>2]){continue}break}}T=Ob+48|0;return}cn();F()}function dg(a){a=a|0;var mb=0;q[a>>2]=5776;mb=q[a+76>>2];if(mb){An(mb)}q[a>>2]=3044;mb=q[a+32>>2];if(mb){q[a+36>>2]=mb;An(mb)}return a|0}function eg(a){a=a|0;var nb=0;q[a>>2]=5776;nb=q[a+76>>2];if(nb){An(nb)}q[a>>2]=3044;nb=q[a+32>>2];if(nb){q[a+36>>2]=nb;An(nb)}An(a)}function fg(a,Nb,vc,wc,xc,yc){a=a|0;Nb=Nb|0;vc=vc|0;wc=wc|0;xc=xc|0;yc=yc|0;var zc=0,Ac=0,Bc=0,Cc=0,Dc=0,Ec=0,Fc=0,Gc=0,Hc=0,Ic=0,Jc=0,Kc=0;wc=0;a:{if((xc|0)!=2){break a}q[a+8>>2]=2;q[a- -64>>2]=yc;wc=a+32|0;xc=q[wc>>2];yc=q[a+36>>2]-xc|0;zc=yc>>2;b:{if(zc>>>0<=1){Fa(wc,2-zc|0);break b}if((yc|0)==8){break b}q[a+36>>2]=xc+8}wc=1;xc=q[a+56>>2];yc=q[xc+4>>2];xc=q[xc>>2];zc=yc-xc|0;if((zc|0)<1){break a}if((xc|0)!=(yc|0)){Hc=a+60|0;Ic=zc>>2;zc=a+8|0;Dc=a+16|0;Ec=a+32|0;Fc=a+20|0;Gc=a+12|0;Jc=a+56|0;while(1){if(!gg(Hc,q[(Bc<<2)+xc>>2],vc,Bc)){wc=0;break a}c:{if(q[zc>>2]<1){break c}xc=0;while(1){wc=xc<<2;yc=q[(wc+a|0)+68>>2];Ac=q[Dc>>2];d:{if((yc|0)>(Ac|0)){Cc=q[Ec>>2];q[wc+Cc>>2]=Ac;break d}Cc=q[Ec>>2];wc=wc+Cc|0;Ac=q[Gc>>2];if((yc|0)<(Ac|0)){q[wc>>2]=Ac;break d}q[wc>>2]=yc}xc=xc+1|0;wc=q[zc>>2];if((xc|0)<(wc|0)){continue}break}yc=0;if((wc|0)<1){break c}wc=Bc<<3;Ac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a|0;Nb=Oc+wc|0;Oc=xc;xc=V;a=Oc+(vc?xc:0-((0>>0)+xc|0)|0)|0;ed=Wc,fd=ao(Nb,Nb>>>0>>0?a+1|0:a,Xc,Nc),q[ed+8>>2]=fd;vc=1}T=Lc+80|0;return vc}function hg(a){a=a|0;var Nb=0;q[a>>2]=6e3;q[a>>2]=3044;Nb=q[a+32>>2];if(Nb){q[a+36>>2]=Nb;An(Nb)}return a|0}function ig(a){a=a|0;var vc=0;q[a>>2]=6e3;q[a>>2]=3044;vc=q[a+32>>2];if(vc){q[a+36>>2]=vc;An(vc)}An(a)}function jg(a,wc,gd,hd,id,jd){a=a|0;wc=wc|0;gd=gd|0;hd=hd|0;id=id|0;jd=jd|0;var kd=0,ld=0,md=0,nd=0,od=0,pd=0,qd=0,rd=0,sd=0,td=0,ud=0,vd=0,wd=0,xd=0,yd=0;ld=T-32|0;T=ld;q[a+68>>2]=jd;hd=q[a+56>>2];id=q[hd>>2];jd=hd+4|0;kd=q[jd>>2];q[ld+24>>2]=0;q[ld+16>>2]=0;q[ld+20>>2]=0;a:{id=kd-id|0;if((id|0)<1){break a}hd=q[hd>>2];if((hd|0)!=q[jd>>2]){vd=id>>2;wd=a+60|0;xd=a+108|0;qd=a+8|0;rd=a+16|0;sd=a+32|0;td=a+20|0;ud=a+12|0;yd=a+56|0;while(1){kg(wd,q[(od<<2)+hd>>2],ld+16|0);id=q[ld+20>>2];kd=id>>31;jd=q[ld+16>>2];md=jd>>31;pd=q[ld+24>>2];nd=pd>>31;hd=0;nd=nd^nd+pd;kd=nd+((kd^id+kd)+(md^jd+md)|0)|0;if(kd>>>0>>0){hd=1}b:{if(!(hd|kd)){q[ld+16>>2]=q[a+104>>2];break b}md=q[a+104>>2];nd=md>>31;id=ao($n(md,nd,id,id>>31),V,kd,hd);q[ld+20>>2]=id;hd=ao($n(md,nd,jd,jd>>31),V,kd,hd);q[ld+16>>2]=hd;jd=hd;hd=hd>>31;hd=(md-(jd+hd^hd)|0)+((id|0)<0?id:0-id|0)|0;if((pd|0)>=0){q[ld+24>>2]=hd;break b}q[ld+24>>2]=0-hd}hd=dh(xd);jd=q[ld+16>>2];c:{if(!hd){id=q[ld+20>>2];break c}q[ld+24>>2]=0-q[ld+24>>2];id=0-q[ld+20>>2]|0;q[ld+20>>2]=id;jd=0-jd|0;q[ld+16>>2]=jd}d:{if((jd|0)>=0){hd=q[a+104>>2];jd=hd+q[ld+24>>2]|0;hd=hd+id|0;break d}e:{if((id|0)<=-1){jd=q[ld+24>>2];hd=jd>>31;hd=hd^hd+jd;break e}jd=q[ld+24>>2];hd=jd>>31;hd=q[a+100>>2]-(hd^hd+jd)|0}if((jd|0)<=-1){jd=id;id=id>>31;jd=jd+id^id;break d}jd=id;id=id>>31;jd=q[a+100>>2]-(jd+id^id)|0}id=q[a+100>>2];f:{if(!(hd|jd)){jd=id;hd=id;break f}if(!((id|0)!=(jd|0)|hd)){hd=jd;break f}if(!((hd|0)!=(id|0)|jd)){jd=hd;break f}g:{if(hd){break g}kd=q[a+104>>2];if((kd|0)>=(jd|0)){break g}jd=(kd<<1)-jd|0;hd=0;break f}h:{if((hd|0)!=(id|0)){break h}kd=q[a+104>>2];if((kd|0)<=(jd|0)){break h}jd=(kd<<1)-jd|0;break f}i:{if((id|0)!=(jd|0)){break i}id=q[a+104>>2];if((id|0)<=(hd|0)){break i}hd=(id<<1)-hd|0;break f}if(jd){break f}jd=0;id=q[a+104>>2];if((id|0)>=(hd|0)){break f}hd=(id<<1)-hd|0}q[ld+12>>2]=jd;q[ld+8>>2]=hd;j:{if(q[qd>>2]<1){break j}jd=0;while(1){kd=q[rd>>2];k:{if((hd|0)>(kd|0)){id=q[sd>>2];q[id+(jd<<2)>>2]=kd;break k}id=q[sd>>2];kd=id+(jd<<2)|0;md=q[ud>>2];if((hd|0)<(md|0)){q[kd>>2]=md;break k}q[kd>>2]=hd}jd=jd+1|0;kd=q[qd>>2];if((jd|0)<(kd|0)){hd=q[(ld+8|0)+(jd<<2)>>2];continue}break}hd=0;if((kd|0)<1){break j}jd=od<<3;md=jd+gd|0;pd=wc+jd|0;while(1){kd=hd<<2;jd=kd+md|0;kd=q[kd+pd>>2]+q[id+kd>>2]|0;q[jd>>2]=kd;l:{if((kd|0)>q[rd>>2]){nd=kd-q[td>>2]|0}else{if((kd|0)>=q[ud>>2]){break l}nd=kd+q[td>>2]|0}q[jd>>2]=nd}hd=hd+1|0;if((hd|0)>2]){continue}break}}od=od+1|0;if((od|0)>=(vd|0)){break a}id=q[yd>>2];hd=q[id>>2];if(q[id+4>>2]-hd>>2>>>0>od>>>0){continue}break}}cn();F()}T=ld+32|0;return 1}function kg(a,wc,gd){a=a|0;wc=wc|0;gd=gd|0;var hd=0,id=0,jd=0,zd=0,Ad=0,Bd=0,Cd=0,Dd=0,Ed=0,Fd=0,Gd=0,Hd=0,Id=0,Jd=0,Kd=0,Ld=0,Md=0,Nd=0,Od=0,Pd=0,Qd=0,Rd=0,Sd=0,Td=0,Ud=0,Vd=0;jd=T-96|0;T=jd;id=q[a+16>>2];o[jd+92|0]=1;q[jd+88>>2]=wc;q[jd+84>>2]=wc;q[jd+80>>2]=id;hd=-1;hd=(wc|0)!=-1?q[q[id>>2]+(wc<<2)>>2]:hd;zd=q[a+20>>2];id=q[zd>>2];a:{b:{c:{d:{if(q[zd+4>>2]-id>>2>>>0>hd>>>0){id=q[q[a+8>>2]+(q[id+(hd<<2)>>2]<<2)>>2];hd=q[a+4>>2];if(!r[hd+84|0]){id=q[q[hd+68>>2]+(id<<2)>>2]}q[jd+72>>2]=0;q[jd+76>>2]=0;zd=jd- -64|0;q[zd>>2]=0;q[zd+4>>2]=0;q[jd+56>>2]=0;q[jd+60>>2]=0;Kf(hd,id,o[hd+24|0],jd+56|0);if((wc|0)==-1){break a}hd=wc+1|0;zd=(hd>>>0)%3|0?hd:wc+ -2|0;Jd=((wc>>>0)%3|0?-1:2)+wc|0;Qd=a+28|0;Ad=!q[Qd>>2];Rd=a+20|0;Sd=a+8|0;Td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zd>>>0>>0){wc=wc+1|0}hd=a;zd=hd+zd|0;a=wc+id|0;a=zd>>>0>>0?a+1|0:a;hd=zd;if(Dd){break b}}if((hd|0)<536870913){break a}a=((a&536870911)<<3|hd>>>29)&7;wc=0;Bd=ao(Bd,Ed,a,wc);Cd=ao(Cd,Hd,a,wc);Fd=ao(Fd,Id,a,wc);break a}cn();F()}cn();F()}cn();F()}if((a|0)<0?1:(a|0)<=0?hd>>>0>=536870913?0:1:0){break a}wc=a>>>29;a=(a&536870911)<<3|hd>>>29;Bd=ao(Bd,Ed,a,wc);Cd=ao(Cd,Hd,a,wc);Fd=ao(Fd,Id,a,wc)}q[gd+8>>2]=Bd;q[gd+4>>2]=Cd;q[gd>>2]=Fd;T=jd+96|0}function lg(a){var wc=0,gd=0,Wd=0;wc=q[a+8>>2];Wd=q[a>>2];a:{if(r[a+12|0]){b:{c:{d:{e:{if((wc|0)==-1){break e}gd=wc+1|0;wc=(gd>>>0)%3|0?gd:wc+ -2|0;if((wc|0)==-1){break e}wc=q[q[Wd+12>>2]+(wc<<2)>>2];if((wc|0)!=-1){break d}}q[a+8>>2]=-1;break c}gd=wc+1|0;wc=(gd>>>0)%3|0?gd:wc+ -2|0;q[a+8>>2]=wc;if((wc|0)!=-1){break b}}gd=q[a+4>>2];wc=-1;f:{if((gd|0)==-1){break f}gd=gd+((gd>>>0)%3|0?-1:2)|0;wc=-1;if((gd|0)==-1){break f}gd=q[q[Wd+12>>2]+(gd<<2)>>2];wc=-1;if((gd|0)==-1){break f}wc=gd+ -1|0;if((gd>>>0)%3){break f}wc=gd+2|0}o[a+12|0]=0;q[a+8>>2]=wc;return}if((wc|0)!=q[a+4>>2]){break a}q[a+8>>2]=-1;return}gd=-1;g:{if((wc|0)==-1){break g}wc=wc+((wc>>>0)%3|0?-1:2)|0;gd=-1;if((wc|0)==-1){break g}wc=q[q[Wd+12>>2]+(wc<<2)>>2];gd=-1;if((wc|0)==-1){break g}gd=wc+ -1|0;if((wc>>>0)%3){break g}gd=wc+2|0}q[a+8>>2]=gd}}function mg(a,Xd,Yd,Zd,_d,$d){a=a|0;Xd=Xd|0;Yd=Yd|0;Zd=Zd|0;_d=_d|0;$d=$d|0;var ae=0,be=0,ce=0,de=0,ee=0,fe=0,ge=0,he=0,ie=0,je=0,ke=0,le=0,me=0,ne=0;q[a+8>>2]=_d;be=a+32|0;ae=q[be>>2];$d=q[a+36>>2]-ae>>2;a:{if($d>>>0<_d>>>0){Fa(be,_d-$d|0);break a}if($d>>>0<=_d>>>0){break a}q[a+36>>2]=ae+(_d<<2)}be=0;$d=(_d&1073741823)!=(_d|0)?-1:_d<<2;ke=Dn(Mm($d),0,$d);ee=a+8|0;ae=q[ee>>2];b:{if((ae|0)<1){break b}ge=a+16|0;$d=a+32|0;he=a+12|0;while(1){ae=be<<2;de=q[ae+ke>>2];ce=q[ge>>2];c:{if((de|0)>(ce|0)){fe=q[$d>>2];q[ae+fe>>2]=ce;break c}fe=q[$d>>2];ae=ae+fe|0;ce=q[he>>2];if((de|0)<(ce|0)){q[ae>>2]=ce;break c}q[ae>>2]=de}be=be+1|0;ae=q[ee>>2];if((be|0)<(ae|0)){continue}break}if((ae|0)<1){break b}be=0;ee=a+16|0;de=a+20|0;ge=a+8|0;he=a+12|0;while(1){ae=be<<2;$d=ae+Yd|0;ae=q[Xd+ae>>2]+q[ae+fe>>2]|0;q[$d>>2]=ae;d:{if((ae|0)>q[ee>>2]){ae=ae-q[de>>2]|0}else{if((ae|0)>=q[he>>2]){break d}ae=ae+q[de>>2]|0}q[$d>>2]=ae}be=be+1|0;ae=q[ge>>2];if((be|0)<(ae|0)){continue}break}}if((_d|0)<(Zd|0)){me=0-_d<<2;de=a+16|0;fe=a+32|0;ee=a+8|0;ge=a+20|0;he=a+12|0;$d=_d;while(1){e:{if((ae|0)<1){break e}je=$d<<2;le=je+Yd|0;ne=le+me|0;be=0;while(1){a=be<<2;ae=q[a+ne>>2];ie=q[de>>2];f:{if((ae|0)>(ie|0)){ce=q[fe>>2];q[a+ce>>2]=ie;break f}ce=q[fe>>2];a=a+ce|0;ie=q[he>>2];if((ae|0)<(ie|0)){q[a>>2]=ie;break f}q[a>>2]=ae}be=be+1|0;ae=q[ee>>2];if((be|0)<(ae|0)){continue}break}be=0;if((ae|0)<1){break e}je=Xd+je|0;while(1){ae=be<<2;a=ae+le|0;ae=q[ae+je>>2]+q[ae+ce>>2]|0;q[a>>2]=ae;g:{if((ae|0)>q[de>>2]){ae=ae-q[ge>>2]|0}else{if((ae|0)>=q[he>>2]){break g}ae=ae+q[ge>>2]|0}q[a>>2]=ae}be=be+1|0;ae=q[ee>>2];if((be|0)<(ae|0)){continue}break}}$d=_d+$d|0;if(($d|0)<(Zd|0)){continue}break}}An(ke);return 1}function ng(a,Xd,Yd){a=a|0;Xd=Xd|0;Yd=Yd|0;var Zd=0;a:{if(!Se(a,Xd,Yd)){break a}a=q[a+8>>2];if(r[a+24|0]!=3){break a}Zd=q[a+28>>2]==9}return Zd|0}function og(a,Xd,Yd){a=a|0;Xd=Xd|0;Yd=Yd|0;var _d=0,$d=0,oe=0,pe=0,qe=0;a:{if(r[q[a+4>>2]+36|0]<=1){_d=q[Yd+16>>2];$d=q[Yd+12>>2];oe=q[Yd+20>>2];qe=oe;pe=0;if(($d|0)<(qe|0)?1:($d|0)<=(qe|0)?t[Yd+8>>2]>_d>>>0?0:1:0){break a}$d=r[_d+q[Yd>>2]|0];_d=_d+1|0;if(_d>>>0<1){oe=oe+1|0}q[Yd+16>>2]=_d;q[Yd+20>>2]=oe;q[a+24>>2]=$d}pe=Xe(a,Xd,Yd)}return pe|0}function pg(a,Xd,Yd){a=a|0;Xd=Xd|0;Yd=Yd|0;var re=0,se=0,te=0,ue=0,ve=0;re=T-16|0;T=re;a:{b:{if(r[q[a+4>>2]+36|0]<=1){Xd=q[a+24>>2];break b}ue=q[Yd+16>>2];se=q[Yd+12>>2];te=q[Yd+20>>2];Xd=te;ve=0;if((se|0)<(Xd|0)?1:(se|0)<=(Xd|0)?t[Yd+8>>2]>ue>>>0?0:1:0){break a}Xd=r[ue+q[Yd>>2]|0];se=ue+1|0;if(se>>>0<1){te=te+1|0}q[Yd+16>>2]=se;q[Yd+20>>2]=te;q[a+24>>2]=Xd}q[re+12>>2]=-1;q[re+8>>2]=1116;q[(re+8|0)+4>>2]=Xd;ve=ld(re+8|0,q[a+16>>2])}a=ve;T=re+16|0;return a|0}function qg(a,Xd){a=a|0;Xd=Xd|0;var Yd=0,we=0,xe=0,ye=0,ze=0,Ae=x(0),Be=0,Ce=0;we=T-32|0;T=we;ye=o[q[a+8>>2]+24|0];Yd=q[a+16>>2];if(q[Yd+80>>2]){ze=q[q[Yd>>2]>>2]+q[Yd+48>>2]|0}q[we+8>>2]=-1;q[we+12>>2]=-1;q[we>>2]=-1;q[we+4>>2]=-1;a:{Yd=q[a+24>>2];if(Yd+ -2>>>0>28){break a}q[we>>2]=Yd;Yd=-1<>2]=xe;q[we+4>>2]=Yd^-1;q[we+12>>2]=(xe|0)/2;if(!Xd){xe=1;break a}ye=ye<<2;Yd=0;Ce=a+8|0;a=0;while(1){Ae=x(x(1)/x(xe|0));xe=Yd<<2;rg(x(Ae*x(q[xe+ze>>2])),x(Ae*x(q[(xe|4)+ze>>2])),we+20|0);Cn(q[q[q[Ce>>2]- -64>>2]>>2]+a|0,we+20|0,ye);xe=1;Be=Be+1|0;if((Be|0)==(Xd|0)){break a}Yd=Yd+2|0;a=a+ye|0;xe=q[we+8>>2];continue}}T=we+32|0;return xe|0}function rg(a,Xd,De){var Ee=0,Fe=0,Ge=x(0),He=x(0),Ie=x(0),Je=0,Ke=0;Ge=x(a+Xd);a:{b:{Ie=x(a-Xd);if(Ie<=x(.5)^1|Ie>=x(-.5)^1|Ge>=x(.5)^1){break b}Fe=1;if(!(Ge<=x(1.5))){break b}He=Xd;break a}c:{if(!!(Ge<=x(.5))){He=x(x(.5)-a);a=x(x(.5)-Xd);break c}if(!!(Ge>=x(1.5))){He=x(x(1.5)-a);a=x(x(1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]=-1;q[Xd+76>>2]=-1;q[Xd+68>>2]=1;q[Xd+40>>2]=9308;break a}if((De|0)!=6){break c}Xd=Mm(104);q[Xd+4>>2]=Ye;De=q[Pe+4>>2];q[Xd+8>>2]=q[Pe>>2];q[Xd+12>>2]=De;De=q[Pe+12>>2];q[Xd+16>>2]=q[Pe+8>>2];q[Xd+20>>2]=De;q[Xd+36>>2]=Qe;q[Xd+32>>2]=Le;q[Xd+28>>2]=We;q[Xd+24>>2]=Ve;q[Xd+64>>2]=Qe;q[Xd+60>>2]=Le;q[Xd+56>>2]=We;q[Xd+52>>2]=Ve;q[Xd+44>>2]=0;q[Xd+48>>2]=0;q[Xd>>2]=9748;q[Xd+72>>2]=-1;q[Xd+76>>2]=-1;q[Xd+68>>2]=1;q[Xd+40>>2]=10168;break a}q[a>>2]=0}q[a>>2]=0;return}q[Xd+80>>2]=-1;q[Xd+84>>2]=-1;ah(Xd+88|0);q[a>>2]=Xd}function vg(a){a=a|0;q[a>>2]=6860;return a|0}function wg(a){a=a|0;q[a>>2]=6860;An(a)}function xg(a){a=a|0;var Xd=0;a:{if(!q[a+44>>2]|!q[a+48>>2]|(!q[a+24>>2]|!q[a+28>>2])){break a}if(!q[a+32>>2]|!q[a+36>>2]){break a}Xd=q[a+72>>2]!=-1}return Xd|0}function yg(a,De){a=a|0;De=De|0;var Le=0;if(!(q[De+56>>2]|r[De+24|0]!=3)){q[a+44>>2]=De;Le=1}return Le|0}function zg(a,De){a=a|0;De=De|0;var Pe=0,Qe=0,Ze=0,_e=0,$e=0,af=0,bf=0,cf=0,df=0,ef=0,ff=0;$e=q[De+12>>2];Pe=$e;Qe=q[De+20>>2];Ze=Qe;af=q[De+16>>2];_e=af+4|0;if(_e>>>0<4){Qe=Qe+1|0}bf=q[De+8>>2];a:{if((Pe|0)<(Qe|0)?1:(Pe|0)<=(Qe|0)?bf>>>0>=_e>>>0?0:1:0){break a}cf=q[De>>2];Pe=af+cf|0;df=r[Pe|0]|r[Pe+1|0]<<8|(r[Pe+2|0]<<16|r[Pe+3|0]<<24);q[De+16>>2]=_e;q[De+20>>2]=Qe;ef=s[De+38>>1];if(ef>>>0<=513){Pe=$e;Qe=Ze;Ze=af+8|0;if(Ze>>>0<8){Qe=Qe+1|0}_e=Ze;if((Pe|0)<(Qe|0)?1:(Pe|0)<=(Qe|0)?bf>>>0>=_e>>>0?0:1:0){break a}q[De+16>>2]=_e;q[De+20>>2]=Qe}if(!(df&1)){break a}Pe=z(df)^31;if(Pe+ -1>>>0>28){break a}q[a+8>>2]=Pe+1;Pe=-2<>2]=Ze;q[a+12>>2]=Pe^-1;q[a+20>>2]=(Ze|0)/2;if(ef>>>0<=513){if(($e|0)<(Qe|0)?1:($e|0)<=(Qe|0)?bf>>>0>_e>>>0?0:1:0){break a}Pe=r[_e+cf|0];Ze=_e+1|0;if(Ze>>>0<1){Qe=Qe+1|0}q[De+16>>2]=Ze;q[De+20>>2]=Qe;if(Pe>>>0>1){break a}q[a+68>>2]=Pe-1|0?0:1}ff=bh(a+88|0,De)}return ff|0}function Ag(a,De,gf,hf,jf,kf){a=a|0;De=De|0;gf=gf|0;hf=hf|0;jf=jf|0;kf=kf|0;var lf=0,mf=0,nf=0,of=0,pf=0,qf=0,rf=0,sf=0,tf=0,uf=0,vf=0;lf=T-48|0;T=lf;rf=a+8|0;hf=q[rf>>2];if(hf+ -2>>>0<=28){q[a+72>>2]=hf;hf=-1<>2]=jf;q[a+76>>2]=hf^-1;q[a+84>>2]=(jf|0)/2}q[a+48>>2]=kf;hf=q[a+36>>2];jf=q[hf>>2];kf=hf+4|0;mf=q[kf>>2];q[lf+16>>2]=0;q[lf+8>>2]=0;q[lf+12>>2]=0;a:{jf=mf-jf|0;if((jf|0)<1){break a}hf=q[hf>>2];if((hf|0)!=q[kf>>2]){sf=jf>>2;tf=a+40|0;uf=a+88|0;vf=a+36|0;while(1){Sf(tf,q[(pf<<2)+hf>>2],lf+8|0);jf=q[lf+12>>2];mf=jf>>31;kf=q[lf+8>>2];of=kf>>31;qf=q[lf+16>>2];nf=qf>>31;hf=0;nf=nf^nf+qf;mf=nf+((mf^jf+mf)+(of^kf+of)|0)|0;if(mf>>>0>>0){hf=1}b:{if(!(hf|mf)){q[lf+8>>2]=q[a+84>>2];break b}of=q[a+84>>2];nf=of;nf=nf>>31;jf=ao($n(of,nf,jf,jf>>31),V,mf,hf);q[lf+12>>2]=jf;hf=ao($n(of,nf,kf,kf>>31),V,mf,hf);q[lf+8>>2]=hf;kf=hf;hf=hf>>31;hf=(of-(kf+hf^hf)|0)+((jf|0)<0?jf:0-jf|0)|0;if((qf|0)>=0){q[lf+16>>2]=hf;break b}q[lf+16>>2]=0-hf}hf=dh(uf);kf=q[lf+8>>2];c:{if(!hf){jf=q[lf+12>>2];break c}q[lf+16>>2]=0-q[lf+16>>2];jf=0-q[lf+12>>2]|0;q[lf+12>>2]=jf;kf=0-kf|0;q[lf+8>>2]=kf}d:{if((kf|0)>=0){kf=q[a+84>>2];hf=kf+q[lf+16>>2]|0;kf=jf+kf|0;break d}e:{if((jf|0)<=-1){hf=q[lf+16>>2];kf=hf>>31;kf=kf^hf+kf;break e}hf=q[lf+16>>2];kf=hf>>31;kf=q[a+80>>2]-(kf^hf+kf)|0}if((hf|0)<=-1){hf=jf>>31;hf=hf+jf^hf;break d}hf=jf>>31;hf=q[a+80>>2]-(hf+jf^hf)|0}jf=q[a+80>>2];f:{if(!(hf|kf)){hf=jf;kf=hf;break f}if(!((hf|0)!=(jf|0)|kf)){kf=hf;break f}if(!((jf|0)!=(kf|0)|hf)){hf=kf;break f}g:{if(kf){break g}mf=q[a+84>>2];if((mf|0)>=(hf|0)){break g}hf=(mf<<1)-hf|0;kf=0;break f}h:{if((jf|0)!=(kf|0)){break h}mf=q[a+84>>2];if((mf|0)<=(hf|0)){break h}hf=(mf<<1)-hf|0;break f}i:{if((hf|0)!=(jf|0)){break i}jf=q[a+84>>2];if((jf|0)<=(kf|0)){break i}kf=(jf<<1)-kf|0;break f}if(hf){break f}hf=0;jf=q[a+84>>2];if((jf|0)>=(kf|0)){break f}kf=(jf<<1)-kf|0}jf=pf<<3;mf=jf+De|0;of=q[mf+4>>2];q[lf+40>>2]=q[mf>>2];q[lf+44>>2]=of;q[lf+28>>2]=hf;q[lf+24>>2]=kf;Bg(lf+32|0,rf,lf+24|0,lf+40|0);hf=gf+jf|0;q[hf>>2]=q[lf+32>>2];q[hf+4>>2]=q[lf+36>>2];pf=pf+1|0;if((pf|0)>=(sf|0)){break a}jf=q[vf>>2];hf=q[jf>>2];if(q[jf+4>>2]-hf>>2>>>0>pf>>>0){continue}break}}cn();F()}T=lf+48|0;return 1}function Bg(a,De,gf,hf){var jf=0,kf=0,wf=0,xf=0,yf=0,zf=0,Af=0,Bf=0;xf=De+12|0;Af=q[xf>>2];kf=q[gf+4>>2]-Af|0;jf=q[gf>>2]-Af|0;q[gf>>2]=jf;q[gf+4>>2]=kf;wf=kf>>31;yf=wf+kf^wf;wf=jf>>31;xf=q[xf>>2];Bf=(yf+(wf+jf^wf)|0)<=(xf|0);if(!Bf){a:{b:{if((jf|0)>=0){zf=1;yf=1;if((kf|0)>-1){break a}wf=1;zf=-1;yf=-1;if((jf|0)>=1){break b}break a}wf=-1;zf=-1;yf=-1;if((kf|0)<1){break a}}zf=(kf|0)<1?-1:1;yf=wf}wf=kf<<1;kf=w(xf,zf);wf=wf-kf|0;q[gf+4>>2]=wf;xf=w(xf,yf);jf=(jf<<1)-xf|0;q[gf>>2]=jf;c:{if((w(yf,zf)|0)>=0){wf=0-wf|0;q[gf>>2]=wf;jf=0-jf|0;break c}q[gf>>2]=wf}kf=(jf+kf|0)/2|0;q[gf+4>>2]=kf;jf=(xf+wf|0)/2|0;q[gf>>2]=jf;xf=q[De+12>>2]}jf=q[hf>>2]+jf|0;q[a>>2]=jf;gf=q[hf+4>>2]+kf|0;q[a+4>>2]=gf;d:{if((xf|0)<(jf|0)){jf=jf-q[De+4>>2]|0;break d}if((jf|0)>=(0-xf|0)){break d}jf=q[De+4>>2]+jf|0}q[a>>2]=jf;e:{if((xf|0)<(gf|0)){gf=gf-q[De+4>>2]|0;break e}if((gf|0)>=(0-xf|0)){break e}gf=q[De+4>>2]+gf|0}q[a+4>>2]=gf;if(!Bf){f:{g:{if((jf|0)>=0){De=1;hf=1;if((gf|0)>-1){break f}kf=1;De=-1;hf=-1;if((jf|0)>=1){break g}break f}kf=-1;De=-1;hf=-1;if((gf|0)<1){break f}}De=(gf|0)<1?-1:1;hf=kf}wf=w(De,xf);kf=(gf<<1)-wf|0;q[a+4>>2]=kf;yf=w(hf,xf);gf=(jf<<1)-yf|0;q[a>>2]=gf;h:{if((w(De,hf)|0)>=0){kf=0-kf|0;q[a>>2]=kf;gf=0-gf|0;break h}q[a>>2]=kf}gf=(gf+wf|0)/2|0;q[a+4>>2]=gf;jf=(kf+yf|0)/2|0;q[a>>2]=jf}q[a>>2]=jf+Af;q[a+4>>2]=gf+Af}function Cg(a,De){a=a|0;De=De|0;var gf=0,hf=0,Cf=0,Df=0,Ef=0,Ff=0,Gf=0,Hf=0,If=0;gf=q[De+12>>2];Ff=gf;Cf=gf;gf=q[De+20>>2];Df=gf;Ef=q[De+16>>2];hf=Ef+4|0;if(hf>>>0<4){gf=gf+1|0}Gf=q[De+8>>2];Hf=hf;hf=gf;a:{if((Cf|0)<(gf|0)?1:(Cf|0)<=(gf|0)?Gf>>>0>=Hf>>>0?0:1:0){break a}gf=Ef+q[De>>2]|0;Cf=r[gf|0]|r[gf+1|0]<<8|(r[gf+2|0]<<16|r[gf+3|0]<<24);q[De+16>>2]=Hf;q[De+20>>2]=hf;if(s[De+38>>1]<=513){gf=Df;hf=Ef+8|0;if(hf>>>0<8){gf=gf+1|0}Df=hf;hf=gf;if((Ff|0)<(gf|0)?1:(Ff|0)<=(gf|0)?Gf>>>0>=Df>>>0?0:1:0){break a}q[De+16>>2]=Df;q[De+20>>2]=hf}if(!(Cf&1)){break a}De=z(Cf)^31;if(De+ -1>>>0>28){break a}If=1;q[a+8>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];q[pg+16>>2]=0;q[pg+8>>2]=0;q[pg+12>>2]=0;a:{ng=qg-ng|0;if((ng|0)<1){break a}mg=q[mg>>2];if((mg|0)!=q[og>>2]){wg=ng>>2;xg=a+40|0;yg=a+88|0;zg=a+36|0;while(1){Sf(xg,q[(tg<<2)+mg>>2],pg+8|0);ng=q[pg+12>>2];qg=ng>>31;og=q[pg+8>>2];sg=og>>31;ug=q[pg+16>>2];rg=ug>>31;mg=0;rg=rg^rg+ug;qg=rg+((qg^ng+qg)+(sg^og+sg)|0)|0;if(qg>>>0>>0){mg=1}b:{if(!(mg|qg)){q[pg+8>>2]=q[a+84>>2];break b}sg=q[a+84>>2];rg=sg;rg=rg>>31;ng=ao($n(sg,rg,ng,ng>>31),V,qg,mg);q[pg+12>>2]=ng;mg=ao($n(sg,rg,og,og>>31),V,qg,mg);q[pg+8>>2]=mg;og=mg;mg=mg>>31;mg=(sg-(og+mg^mg)|0)+((ng|0)<0?ng:0-ng|0)|0;if((ug|0)>=0){q[pg+16>>2]=mg;break b}q[pg+16>>2]=0-mg}mg=dh(yg);og=q[pg+8>>2];c:{if(!mg){ng=q[pg+12>>2];break c}q[pg+16>>2]=0-q[pg+16>>2];ng=0-q[pg+12>>2]|0;q[pg+12>>2]=ng;og=0-og|0;q[pg+8>>2]=og}d:{if((og|0)>=0){og=q[a+84>>2];mg=og+q[pg+16>>2]|0;og=ng+og|0;break d}e:{if((ng|0)<=-1){mg=q[pg+16>>2];og=mg>>31;og=og^mg+og;break e}mg=q[pg+16>>2];og=mg>>31;og=q[a+80>>2]-(og^mg+og)|0}if((mg|0)<=-1){mg=ng>>31;mg=mg+ng^mg;break d}mg=ng>>31;mg=q[a+80>>2]-(mg+ng^mg)|0}ng=q[a+80>>2];f:{if(!(mg|og)){mg=ng;og=mg;break f}if(!((mg|0)!=(ng|0)|og)){og=mg;break f}if(!((ng|0)!=(og|0)|mg)){mg=og;break f}g:{if(og){break g}qg=q[a+84>>2];if((qg|0)>=(mg|0)){break g}mg=(qg<<1)-mg|0;og=0;break f}h:{if((ng|0)!=(og|0)){break h}qg=q[a+84>>2];if((qg|0)<=(mg|0)){break h}mg=(qg<<1)-mg|0;break f}i:{if((mg|0)!=(ng|0)){break i}ng=q[a+84>>2];if((ng|0)<=(og|0)){break i}og=(ng<<1)-og|0;break f}if(mg){break f}mg=0;ng=q[a+84>>2];if((ng|0)>=(og|0)){break f}og=(ng<<1)-og|0}ng=tg<<3;qg=ng+De|0;sg=q[qg+4>>2];qg=q[qg>>2];q[pg+36>>2]=mg;q[pg+32>>2]=og;q[pg+24>>2]=qg;q[pg+28>>2]=sg;Lg(pg+40|0,vg,pg+32|0,pg+24|0);mg=lg+ng|0;q[mg>>2]=q[pg+40>>2];q[mg+4>>2]=q[pg+44>>2];tg=tg+1|0;if((tg|0)>=(wg|0)){break a}ng=q[zg>>2];mg=q[ng>>2];if(q[ng+4>>2]-mg>>2>>>0>tg>>>0){continue}break}}cn();F()}T=pg+48|0;return 1}function Lg(a,De,lg,mg){var ng=0,og=0,Ag=0,Bg=0,Cg=0,Dg=0,Eg=0,Fg=0;Bg=De+12|0;Eg=q[Bg>>2];og=q[lg+4>>2]-Eg|0;ng=q[lg>>2]-Eg|0;q[lg>>2]=ng;q[lg+4>>2]=og;Ag=og>>31;Cg=Ag+og^Ag;Ag=ng>>31;Bg=q[Bg>>2];Fg=(Cg+(Ag+ng^Ag)|0)<=(Bg|0);if(!Fg){a:{b:{if((ng|0)>=0){Ag=1;Dg=1;if((og|0)>-1){break a}Cg=1;Ag=-1;Dg=-1;if((ng|0)>=1){break b}break a}Cg=-1;Ag=-1;Dg=-1;if((og|0)<1){break a}}Ag=(og|0)<1?-1:1;Dg=Cg}Cg=og<<1;og=w(Ag,Bg);Cg=Cg-og|0;q[lg+4>>2]=Cg;Bg=w(Bg,Dg);ng=(ng<<1)-Bg|0;q[lg>>2]=ng;c:{if((w(Ag,Dg)|0)>=0){Cg=0-Cg|0;q[lg>>2]=Cg;ng=0-ng|0;break c}q[lg>>2]=Cg}og=(ng+og|0)/2|0;q[lg+4>>2]=og;ng=(Bg+Cg|0)/2|0;q[lg>>2]=ng}d:{e:{f:{g:{h:{i:{j:{k:{if(!ng){if(og){break j}Bg=1;Dg=0;break k}Bg=1;Ag=(ng|0)<0&(og|0)<1;if((ng|0)>=1){Dg=(og|0)>-1?2:1;if(Ag){break k}break i}Dg=(og|0)>0?3:0;if(!Ag){break i}}Ag=og;Cg=ng;break d}if((og|0)>=1){break f}break h}Ag=Dg+ -1|0;if(Ag>>>0>2){Ag=og;og=ng;Dg=0;break e}switch(Ag-1|0){case 0:break g;case 1:break f;default:break h}}Ag=0-ng|0;Dg=1;break e}Ag=0-og|0;og=0-ng|0;Dg=2;break e}Ag=ng;og=0-og|0;Dg=3}ng=lg;Cg=og;q[ng>>2]=og;q[ng+4>>2]=Ag;Bg=0}og=q[mg>>2]+Cg|0;q[a>>2]=og;ng=q[mg+4>>2]+Ag|0;q[a+4>>2]=ng;Ag=q[De+12>>2];l:{if((Ag|0)<(og|0)){og=og-q[De+4>>2]|0;break l}if((og|0)>=(0-Ag|0)){break l}og=q[De+4>>2]+og|0}q[a>>2]=og;m:{if((Ag|0)<(ng|0)){ng=ng-q[De+4>>2]|0;break m}if((ng|0)>=(0-Ag|0)){break m}ng=q[De+4>>2]+ng|0}q[a+4>>2]=ng;n:{if(Bg){lg=ng;ng=og;break n}De=(4-Dg&3)+ -1|0;o:{if(De>>>0>2){lg=ng;ng=og;break o}p:{switch(De-1|0){default:lg=0-og|0;break o;case 0:lg=0-ng|0;ng=0-og|0;break o;case 1:break p}}ng=0-ng|0;lg=og}q[a>>2]=ng;q[a+4>>2]=lg}if(!Fg){q:{r:{if((ng|0)>=0){De=1;Bg=1;if((lg|0)>-1){break q}og=1;De=-1;Bg=-1;if((ng|0)>=1){break r}break q}og=-1;De=-1;Bg=-1;if((lg|0)<1){break q}}De=(lg|0)<1?-1:1;Bg=og}mg=lg<<1;lg=w(De,Ag);og=mg-lg|0;q[a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=Qg^Og+Qg;break e}Og=q[Rg+16>>2];Qg=Og>>31;Qg=q[a+80>>2]-(Qg^Og+Qg)|0}if((Og|0)<=-1){Og=Pg>>31;Og=Og+Pg^Og;break d}Og=Pg>>31;Og=q[a+80>>2]-(Og+Pg^Og)|0}Pg=q[a+80>>2];f:{if(!(Og|Qg)){Og=Pg;Qg=Og;break f}if(!((Og|0)!=(Pg|0)|Qg)){Qg=Og;break f}if(!((Pg|0)!=(Qg|0)|Og)){Og=Qg;break f}g:{if(Qg){break g}Sg=q[a+84>>2];if((Sg|0)>=(Og|0)){break g}Og=(Sg<<1)-Og|0;Qg=0;break f}h:{if((Pg|0)!=(Qg|0)){break h}Sg=q[a+84>>2];if((Sg|0)<=(Og|0)){break h}Og=(Sg<<1)-Og|0;break f}i:{if((Og|0)!=(Pg|0)){break i}Pg=q[a+84>>2];if((Pg|0)<=(Qg|0)){break i}Qg=(Pg<<1)-Qg|0;break f}if(Og){break f}Og=0;Pg=q[a+84>>2];if((Pg|0)>=(Qg|0)){break f}Qg=(Pg<<1)-Qg|0}Pg=Vg<<3;Sg=Pg+De|0;Ug=q[Sg+4>>2];Sg=q[Sg>>2];q[Rg+36>>2]=Og;q[Rg+32>>2]=Qg;q[Rg+24>>2]=Sg;q[Rg+28>>2]=Ug;Lg(Rg+40|0,Xg,Rg+32|0,Rg+24|0);Og=Ng+Pg|0;q[Og>>2]=q[Rg+40>>2];q[Og+4>>2]=q[Rg+44>>2];Vg=Vg+1|0;if((Vg|0)>=(Yg|0)){break a}Pg=q[$g>>2];Og=q[Pg>>2];if(q[Pg+4>>2]-Og>>2>>>0>Vg>>>0){continue}break}}cn();F()}T=Rg+48|0;return 1}function Qg(a,De,Ng,Og,Pg,Qg){a=a|0;De=De|0;Ng=Ng|0;Og=Og|0;Pg=Pg|0;Qg=Qg|0;var ah=0,bh=0,ch=0,dh=0,eh=0,fh=0,gh=0,hh=0;Qg=T-32|0;T=Qg;bh=(Pg&1073741823)!=(Pg|0)?-1:Pg<<2;bh=Dn(Mm(bh),0,bh);ah=q[De>>2];ch=q[De+4>>2];eh=q[bh+4>>2];q[Qg+16>>2]=q[bh>>2];q[Qg+20>>2]=eh;q[Qg+8>>2]=ah;q[Qg+12>>2]=ch;ch=a+8|0;Lg(Qg+24|0,ch,Qg+16|0,Qg+8|0);q[Ng>>2]=q[Qg+24>>2];q[Ng+4>>2]=q[Qg+28>>2];if((Pg|0)<(Og|0)){eh=0-Pg<<2;a=Pg;while(1){ah=a<<2;dh=ah+De|0;gh=q[dh>>2];dh=q[dh+4>>2];ah=Ng+ah|0;fh=ah+eh|0;hh=q[fh+4>>2];q[Qg+16>>2]=q[fh>>2];q[Qg+20>>2]=hh;q[Qg+8>>2]=gh;q[Qg+12>>2]=dh;Lg(Qg+24|0,ch,Qg+16|0,Qg+8|0);q[ah>>2]=q[Qg+24>>2];q[ah+4>>2]=q[Qg+28>>2];a=a+Pg|0;if((a|0)<(Og|0)){continue}break}}An(bh);T=Qg+32|0;return 1}function Rg(a,De,Ng){a=a|0;De=De|0;Ng=Ng|0;if(Se(a,De,Ng)){a=q[q[q[q[De+4>>2]+8>>2]+(Ng<<2)>>2]+28>>2]==9}else{a=0}return a|0}function Sg(a,De,Ng){a=a|0;De=De|0;Ng=Ng|0;var Og=0;a:{if(r[q[a+4>>2]+36|0]<=1){Og=0;if(!n[q[q[a>>2]+52>>2]](a)){break a}}Og=Xe(a,De,Ng)}return Og|0}function Tg(a,De,Ng){a=a|0;De=De|0;Ng=Ng|0;De=T-32|0;T=De;a:{if(r[q[a+4>>2]+36|0]>=2){Ng=0;if(!n[q[q[a>>2]+52>>2]](a)){break a}}q[De+24>>2]=0;q[De+28>>2]=0;q[De+16>>2]=0;q[De+20>>2]=0;q[De+12>>2]=-1;q[De+8>>2]=1232;gd(De+8|0,q[a+24>>2],q[a+28>>2],o[q[a+8>>2]+24|0],u[a+32>>2]);Ng=ld(De+8|0,q[a+16>>2]);q[De+8>>2]=1232;a=q[De+16>>2];if(!a){break a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break a}Qg=r[ih+q[De>>2]|0];Ng=ih+1|0;if(Ng>>>0<1){Pg=Pg+1|0}q[De+16>>2]=Ng;q[De+20>>2]=Pg;if(Qg>>>0>31){break a}q[a+24>>2]=Qg;nh=1}return nh|0}function Wg(a,oh){a=a|0;oh=oh|0;var ph=0,qh=0,rh=0,sh=0,th=0,uh=0,vh=0,wh=0,xh=0,yh=0,zh=0,Ah=0,Bh=0,Ch=0,Dh=x(0);sh=T-16|0;T=sh;qh=q[a+24>>2];rh=o[q[a+8>>2]+24|0];th=rh<<2;uh=Mm((rh&1073741823)!=(rh|0)?-1:th);vh=hk(sh+8|0);a:{if(!ik(vh,u[a+32>>2],-1<>2];qh=0;b:{if(!q[ph+80>>2]){break b}qh=q[q[ph>>2]>>2]+q[ph+48>>2]|0}if(!oh){ph=1;break a}zh=(rh|0)<1;Ah=a+28|0;Bh=a+8|0;a=0;while(1){if(!zh){Ch=q[Ah>>2];Dh=u[vh>>2];ph=0;while(1){wh=ph<<2;u[wh+uh>>2]=x(Dh*x(q[(a<<2)+qh>>2]))+u[Ch+wh>>2];a=a+1|0;ph=ph+1|0;if((rh|0)!=(ph|0)){continue}break}}Cn(q[q[q[Bh>>2]- -64>>2]>>2]+xh|0,uh,th);xh=th+xh|0;ph=1;yh=yh+1|0;if((yh|0)!=(oh|0)){continue}break}}An(uh);T=sh+16|0;return ph|0}function Xg(a){a=a|0;var oh=0,Eh=0;q[a>>2]=10764;Eh=a+28|0;oh=q[Eh>>2];q[Eh>>2]=0;if(oh){An(oh)}q[a>>2]=2220;Eh=a+20|0;oh=q[Eh>>2];q[Eh>>2]=0;if(oh){n[q[q[oh>>2]+4>>2]](oh)}q[a>>2]=1908;Eh=a+16|0;oh=q[Eh>>2];q[Eh>>2]=0;if(oh){Hb(oh)}return a|0}function Yg(a){a=a|0;var Fh=0,Gh=0;q[a>>2]=10764;Gh=a+28|0;Fh=q[Gh>>2];q[Gh>>2]=0;if(Fh){An(Fh)}q[a>>2]=2220;Gh=a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Uh=Vh;Wh=Zh-(Th+(Yh>>>0>>0)|0)|0;if(((Wh|0)<0?1:(Wh|0)<=0?Yh-Xh>>>0>=Uh>>>0?0:1:0)|(Uh|0)<1){break a}Wh=Xh+q[Jh>>2]|0;q[a>>2]=Wh;Zh=Vh+ -1|0;$h=Zh+Wh|0;Yh=r[$h|0]>>>6;if((Yh|0)==3){break a}ai=a;c:{d:{switch(Yh-1|0){default:q[a+4>>2]=Zh;a=r[$h|0]&63;break c;case 0:if((Vh|0)<2){break a}q[a+4>>2]=Vh+ -2;a=(Vh+Wh|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c;case 1:break d}}if((Vh|0)<3){break a}q[a+4>>2]=Vh+ -3;a=(Vh+Wh|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0]}a=a+4096|0;q[ai+8>>2]=a;if(a>>>0>1048575){break a}a=Uh+Xh|0;if(a>>>0>>0){Th=Th+1|0}q[Jh+16>>2]=a;q[Jh+20>>2]=Th;bi=1}T=_h+16|0;return bi}function ch(a,Jh,ci){var di=0,ei=0,fi=0,gi=0;a:{if(a>>>0>5){break a}fi=q[ci+16>>2];di=q[ci+12>>2];ei=q[ci+20>>2];if((di|0)<(ei|0)?1:(di|0)<=(ei|0)?t[ci+8>>2]>fi>>>0?0:1:0){break a}di=r[fi+q[ci>>2]|0];fi=fi+1|0;if(fi>>>0<1){ei=ei+1|0}q[ci+16>>2]=fi;q[ci+20>>2]=ei;ei=Jh;if(di&128){if(!ch(a+1|0,Jh,ci)){break a}a=q[Jh>>2]<<7;q[Jh>>2]=a;di=a|di&127}q[ei>>2]=di;gi=1}return gi}function dh(a){var Jh=0,ci=0,hi=0,ii=0,ji=0;hi=0-r[a+12|0]|0;ci=q[a+8>>2];a:{if(ci>>>0>4095){break a}Jh=q[a+4>>2];if((Jh|0)<1){break a}Jh=Jh+ -1|0;q[a+4>>2]=Jh;ci=r[Jh+q[a>>2]|0]|ci<<8;q[a+8>>2]=ci}hi=hi&255;Jh=w(hi,ci>>>8);ii=ci&255;ji=ii>>>0>>0;q[a+8>>2]=ji?Jh+ii|0:(ci-hi|0)-Jh|0;return ji}function eh(a,ki,li){var mi=0,ni=0,oi=0,pi=0,qi=0,ri=0;if(!ki){q[li>>2]=0;return}pi=0-r[a+12|0]&255;ni=q[a+8>>2];while(1){qi=mi<<1;a:{if(ni>>>0>4095){break a}mi=q[a+4>>2];if((mi|0)<1){break a}mi=mi+ -1|0;q[a+4>>2]=mi;ni=r[mi+q[a>>2]|0]|ni<<8;q[a+8>>2]=ni}oi=ni&255;mi=oi>>>0>>0;ri=oi;oi=w(ni>>>8,pi);ni=mi?ri+oi|0:(ni-pi|0)-oi|0;q[a+8>>2]=ni;mi=mi|qi;ki=ki+ -1|0;if(ki){continue}break}q[li>>2]=mi}function fh(a,ki){var li=0,si=0,ti=0;ti=T-32|0;T=ti;a:{if(ki>>>0<=1){if(ki-1){li=Mm(44);ki=li;q[ki>>2]=0;q[ki+4>>2]=0;q[ki+40>>2]=0;q[ki+32>>2]=0;q[ki+36>>2]=0;q[ki+24>>2]=0;q[ki+28>>2]=0;q[ki+16>>2]=0;q[ki+20>>2]=0;q[ki+8>>2]=0;q[ki+12>>2]=0;Ij(ki);q[ki>>2]=13760;q[a+8>>2]=0;q[a+12>>2]=0;q[a>>2]=0;q[a+4>>2]=0;q[a+16>>2]=ki;break a}li=Mm(44);ki=li;q[ki>>2]=0;q[ki+4>>2]=0;q[ki+40>>2]=0;q[ki+32>>2]=0;q[ki+36>>2]=0;q[ki+24>>2]=0;q[ki+28>>2]=0;q[ki+16>>2]=0;q[ki+20>>2]=0;q[ki+8>>2]=0;q[ki+12>>2]=0;Ij(ki);q[ki>>2]=13668;q[a+8>>2]=0;q[a+12>>2]=0;q[a>>2]=0;q[a+4>>2]=0;q[a+16>>2]=ki;break a}ki=Mm(32);q[ti>>2]=ki;q[ti+4>>2]=28;q[ti+8>>2]=-2147483616;o[ki+28|0]=0;li=r[10912]|r[10913]<<8|(r[10914]<<16|r[10915]<<24);o[ki+24|0]=li;o[ki+25|0]=li>>>8;o[ki+26|0]=li>>>16;o[ki+27|0]=li>>>24;li=r[10908]|r[10909]<<8|(r[10910]<<16|r[10911]<<24);si=r[10904]|r[10905]<<8|(r[10906]<<16|r[10907]<<24);o[ki+16|0]=si;o[ki+17|0]=si>>>8;o[ki+18|0]=si>>>16;o[ki+19|0]=si>>>24;o[ki+20|0]=li;o[ki+21|0]=li>>>8;o[ki+22|0]=li>>>16;o[ki+23|0]=li>>>24;li=r[10900]|r[10901]<<8|(r[10902]<<16|r[10903]<<24);si=r[10896]|r[10897]<<8|(r[10898]<<16|r[10899]<<24);o[ki+8|0]=si;o[ki+9|0]=si>>>8;o[ki+10|0]=si>>>16;o[ki+11|0]=si>>>24;o[ki+12|0]=li;o[ki+13|0]=li>>>8;o[ki+14|0]=li>>>16;o[ki+15|0]=li>>>24;li=r[10892]|r[10893]<<8|(r[10894]<<16|r[10895]<<24);si=r[10888]|r[10889]<<8|(r[10890]<<16|r[10891]<<24);o[ki|0]=si;o[ki+1|0]=si>>>8;o[ki+2|0]=si>>>16;o[ki+3|0]=si>>>24;o[ki+4|0]=li;o[ki+5|0]=li>>>8;o[ki+6|0]=li>>>16;o[ki+7|0]=li>>>24;q[ti+16>>2]=-1;ki=Rm(ti+16|4,ti);q[a>>2]=q[ti+16>>2];Rm(a+4|0,ki);q[a+16>>2]=0;if(o[ki+11|0]<=-1){An(q[ki>>2])}if(o[ti+11|0]>-1){break a}An(q[ti>>2])}T=ti+32|0}function gh(a,ki){var ui=0,vi=0,wi=0;wi=T-32|0;T=wi;a:{if(ki>>>0<=1){if(ki-1){ki=Mm(48);Rh(ki);q[ki>>2]=13064;q[a+8>>2]=0;q[a+12>>2]=0;q[a>>2]=0;q[a+4>>2]=0;q[a+16>>2]=ki;break a}ki=Mm(52);Rh(ki);q[ki+48>>2]=0;q[ki>>2]=11164;q[a+8>>2]=0;q[a+12>>2]=0;q[a>>2]=0;q[a+4>>2]=0;q[a+16>>2]=ki;break a}ki=Mm(32);q[wi>>2]=ki;q[wi+4>>2]=28;q[wi+8>>2]=-2147483616;o[ki+28|0]=0;ui=r[10912]|r[10913]<<8|(r[10914]<<16|r[10915]<<24);o[ki+24|0]=ui;o[ki+25|0]=ui>>>8;o[ki+26|0]=ui>>>16;o[ki+27|0]=ui>>>24;ui=r[10908]|r[10909]<<8|(r[10910]<<16|r[10911]<<24);vi=r[10904]|r[10905]<<8|(r[10906]<<16|r[10907]<<24);o[ki+16|0]=vi;o[ki+17|0]=vi>>>8;o[ki+18|0]=vi>>>16;o[ki+19|0]=vi>>>24;o[ki+20|0]=ui;o[ki+21|0]=ui>>>8;o[ki+22|0]=ui>>>16;o[ki+23|0]=ui>>>24;ui=r[10900]|r[10901]<<8|(r[10902]<<16|r[10903]<<24);vi=r[10896]|r[10897]<<8|(r[10898]<<16|r[10899]<<24);o[ki+8|0]=vi;o[ki+9|0]=vi>>>8;o[ki+10|0]=vi>>>16;o[ki+11|0]=vi>>>24;o[ki+12|0]=ui;o[ki+13|0]=ui>>>8;o[ki+14|0]=ui>>>16;o[ki+15|0]=ui>>>24;ui=r[10892]|r[10893]<<8|(r[10894]<<16|r[10895]<<24);vi=r[10888]|r[10889]<<8|(r[10890]<<16|r[10891]<<24);o[ki|0]=vi;o[ki+1|0]=vi>>>8;o[ki+2|0]=vi>>>16;o[ki+3|0]=vi>>>24;o[ki+4|0]=ui;o[ki+5|0]=ui>>>8;o[ki+6|0]=ui>>>16;o[ki+7|0]=ui>>>24;q[wi+16>>2]=-1;ki=Rm(wi+16|4,wi);q[a>>2]=q[wi+16>>2];Rm(a+4|0,ki);q[a+16>>2]=0;if(o[ki+11|0]<=-1){An(q[ki>>2])}if(o[wi+11|0]>-1){break a}An(q[wi>>2])}T=wi+32|0}function hh(a,ki){var xi=0,yi=0,zi=0;xi=T-80|0;T=xi;yi=q[ki+36>>2];q[xi+72>>2]=q[ki+32>>2];q[xi+76>>2]=yi;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0]=Ai>>>24;Ai=r[10937]|r[10938]<<8|(r[10939]<<16|r[10940]<<24);Bi=r[10933]|r[10934]<<8|(r[10935]<<16|r[10936]<<24);o[ki+16|0]=Bi;o[ki+17|0]=Bi>>>8;o[ki+18|0]=Bi>>>16;o[ki+19|0]=Bi>>>24;o[ki+20|0]=Ai;o[ki+21|0]=Ai>>>8;o[ki+22|0]=Ai>>>16;o[ki+23|0]=Ai>>>24;Ai=r[10929]|r[10930]<<8|(r[10931]<<16|r[10932]<<24);Bi=r[10925]|r[10926]<<8|(r[10927]<<16|r[10928]<<24);o[ki+8|0]=Bi;o[ki+9|0]=Bi>>>8;o[ki+10|0]=Bi>>>16;o[ki+11|0]=Bi>>>24;o[ki+12|0]=Ai;o[ki+13|0]=Ai>>>8;o[ki+14|0]=Ai>>>16;o[ki+15|0]=Ai>>>24;Ai=r[10921]|r[10922]<<8|(r[10923]<<16|r[10924]<<24);Bi=r[10917]|r[10918]<<8|(r[10919]<<16|r[10920]<<24);o[ki|0]=Bi;o[ki+1|0]=Bi>>>8;o[ki+2|0]=Bi>>>16;o[ki+3|0]=Bi>>>24;o[ki+4|0]=Ai;o[ki+5|0]=Ai>>>8;o[ki+6|0]=Ai>>>16;o[ki+7|0]=Ai>>>24;q[a>>2]=-1;Rm(Ei,Ci);if(o[Ci+11|0]>-1){break a}An(q[Ci>>2]);break a}fh(Ci,o[Ci+32|0]);Di=q[Ci>>2];b:{if(Di){q[a>>2]=Di;Rm(Ei,Ci|4);break b}Di=q[Ci+16>>2];q[Ci+16>>2]=0;Mj(a,Di,ki,Ai,Bi);if(!q[a>>2]){if(o[Ei+11|0]<=-1){An(q[Ei>>2])}q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0}if(!Di){break b}n[q[q[Di>>2]+4>>2]](Di)}a=q[Ci+16>>2];q[Ci+16>>2]=0;if(a){n[q[q[a>>2]+4>>2]](a)}if(o[Ci+15|0]>-1){break a}An(q[Ci+4>>2])}T=Ci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;o[ki+6|0]=Ai>>>16;o[ki+7|0]=Ai>>>24;q[a>>2]=-1;Rm(Gi,Fi);if(o[Fi+11|0]>-1){break a}An(q[Fi>>2]);break a}gh(Fi,r[Fi+32|0]);Hi=q[Fi>>2];b:{if(Hi){q[a>>2]=Hi;Rm(Gi,Fi|4);break b}Hi=q[Fi+16>>2];q[Fi+16>>2]=0;q[Hi+44>>2]=Bi;Mj(a,Hi,ki,Ai,Bi);if(!q[a>>2]){if(o[Gi+11|0]<=-1){An(q[Gi>>2])}q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0}if(!Hi){break b}n[q[q[Hi>>2]+4>>2]](Hi)}a=q[Fi+16>>2];q[Fi+16>>2]=0;if(a){n[q[q[a>>2]+4>>2]](a)}if(o[Fi+15|0]>-1){break a}An(q[Fi+4>>2])}T=Fi+80|0}function kh(a,ki){var Ai=0,Bi=0,Ii=0;Ii=T-16|0;T=Ii;q[Ii+12>>2]=ki;ki=Mm(32);q[Ii>>2]=ki;q[Ii+4>>2]=24;q[Ii+8>>2]=-2147483616;o[ki+24|0]=0;Ai=r[10986]|r[10987]<<8|(r[10988]<<16|r[10989]<<24);Bi=r[10982]|r[10983]<<8|(r[10984]<<16|r[10985]<<24);o[ki+16|0]=Bi;o[ki+17|0]=Bi>>>8;o[ki+18|0]=Bi>>>16;o[ki+19|0]=Bi>>>24;o[ki+20|0]=Ai;o[ki+21|0]=Ai>>>8;o[ki+22|0]=Ai>>>16;o[ki+23|0]=Ai>>>24;Ai=r[10978]|r[10979]<<8|(r[10980]<<16|r[10981]<<24);Bi=r[10974]|r[10975]<<8|(r[10976]<<16|r[10977]<<24);o[ki+8|0]=Bi;o[ki+9|0]=Bi>>>8;o[ki+10|0]=Bi>>>16;o[ki+11|0]=Bi>>>24;o[ki+12|0]=Ai;o[ki+13|0]=Ai>>>8;o[ki+14|0]=Ai>>>16;o[ki+15|0]=Ai>>>24;Ai=r[10970]|r[10971]<<8|(r[10972]<<16|r[10973]<<24);Bi=r[10966]|r[10967]<<8|(r[10968]<<16|r[10969]<<24);o[ki|0]=Bi;o[ki+1|0]=Bi>>>8;o[ki+2|0]=Bi>>>16;o[ki+3|0]=Bi>>>24;o[ki+4|0]=Ai;o[ki+5|0]=Ai>>>8;o[ki+6|0]=Ai>>>16;o[ki+7|0]=Ai>>>24;ek(lh(a,Ii+12|0),Ii);if(o[Ii+11|0]<=-1){An(q[Ii>>2])}T=Ii+16|0}function lh(a,ki){var Ji=0,Ki=0,Li=0,Mi=0,Ni=0,Oi=0,Pi=0,Qi=0;Li=T-32|0;T=Li;Mi=a+16|0;Ki=q[Mi>>2];a:{b:{if(!Ki){break b}Oi=q[ki>>2];Ji=Mi;while(1){Ni=q[Ki+16>>2]<(Oi|0);Ji=Ni?Ji:Ki;Ki=q[(Ni<<2)+Ki>>2];if(Ki){continue}break}if((Ji|0)==(Mi|0)){break b}if((Oi|0)>=q[Ji+16>>2]){break a}}Oi=ck(Li+16|0);ki=q[ki>>2];Ni=Li+8|0;q[Ni>>2]=0;q[Ni+4>>2]=0;q[Li>>2]=ki;q[Li+4>>2]=Ni;Ji=q[Oi>>2];Pi=Oi+4|0;if((Ji|0)!=(Pi|0)){Qi=Li|4;while(1){ki=Ji;Ki=Ji+16|0;mh(Qi,Ni,Ki,Ki);Ki=q[Ji+4>>2];c:{if(!Ki){Ji=q[ki+8>>2];if((ki|0)==q[Ji>>2]){break c}ki=ki+8|0;while(1){Ki=q[ki>>2];ki=Ki+8|0;Ji=q[Ki+8>>2];if((Ki|0)!=q[Ji>>2]){continue}break}break c}while(1){Ji=Ki;Ki=q[Ji>>2];if(Ki){continue}break}}if((Ji|0)!=(Pi|0)){continue}break}}ki=a+16|0;Ki=q[ki>>2];d:{if(Ki){Mi=q[Li>>2];while(1){Ji=q[Ki+16>>2];e:{if((Mi|0)<(Ji|0)){Ji=q[Ki>>2];if(Ji){break e}ki=Ki;break d}if((Ji|0)>=(Mi|0)){break d}ki=Ki+4|0;Ji=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Xi+11|0];aj=$i<<24>>24;bj=(aj|0)<0;cj=Zi?q[ki+20>>2]:_i;$i=bj?q[Xi+4>>2]:$i;dj=cj>>>0<$i>>>0;g:{_i=dj?cj:$i;if(_i){bj=bj?q[Xi>>2]:Xi;Zi=Zi?q[Yi>>2]:Yi;gj=cm(bj,Zi,_i);if(gj){break g}}if($i>>>0>>0){break f}if(!_i){break d}bj=(aj|0)<0?q[Xi>>2]:Xi;Zi=(fj|0)<0?q[Yi>>2]:Yi;break e}if((gj|0)>-1){break e}}_i=q[ki>>2];h:{i:{if(q[a>>2]==(ki|0)){Yi=ki;break i}j:{if(!_i){Wi=ki;while(1){Yi=q[Wi+8>>2];$i=q[Yi>>2]==(Wi|0);Wi=Yi;if($i){continue}break}break j}Wi=_i;while(1){Yi=Wi;Wi=q[Yi+4>>2];if(Wi){continue}break}}Zi=r[Xi+11|0];Wi=Zi<<24>>24<0;aj=r[Yi+27|0];$i=aj<<24>>24<0;k:{Zi=Wi?q[Xi+4>>2]:Zi;aj=$i?q[Yi+20>>2]:aj;bj=Zi>>>0>>0?Zi:aj;if(bj){cj=Yi+16|0;Wi=cm($i?q[cj>>2]:cj,Wi?q[Xi>>2]:Xi,bj);if(Wi){break k}}if(aj>>>0>>0){break i}break h}if((Wi|0)>-1){break h}}if(!_i){q[Vi>>2]=ki;return ki}q[Vi>>2]=Yi;return Yi+4|0}return ph(a,Vi,Xi)}Yi=cm(Zi,bj,_i);if(Yi){break c}}if(dj){break b}break a}if((Yi|0)>-1){break a}}bj=ki+4|0;_i=q[bj>>2];l:{if(_i){Yi=_i;while(1){Wi=Yi;Yi=q[Yi>>2];if(Yi){continue}break}break l}Wi=q[ki+8>>2];if(q[Wi>>2]==(ki|0)){break l}Yi=ki+8|0;while(1){Zi=q[Yi>>2];Yi=Zi+8|0;Wi=q[Zi+8>>2];if((Zi|0)!=q[Wi>>2]){continue}break}}m:{n:{if((Wi|0)==(ej|0)){break n}Zi=r[Wi+27|0];Yi=Zi<<24>>24<0;o:{Zi=Yi?q[Wi+20>>2]:Zi;cj=Zi>>>0<$i>>>0?Zi:$i;if(cj){dj=(aj|0)<0?q[Xi>>2]:Xi;aj=Wi+16|0;Yi=cm(dj,Yi?q[aj>>2]:aj,cj);if(Yi){break o}}if($i>>>0>>0){break n}break m}if((Yi|0)>-1){break m}}if(!_i){q[Vi>>2]=ki;return bj}q[Vi>>2]=Wi;return Wi}return ph(a,Vi,Xi)}q[Vi>>2]=ki;q[Wi>>2]=ki;return Wi}function ph(a,ki,Vi){var Wi=0,Xi=0,hj=0,ij=0,jj=0,kj=0,lj=0,mj=0,nj=0;a:{Wi=a+4|0;a=q[Wi>>2];if(a){hj=r[Vi+11|0];ij=hj<<24>>24<0;hj=ij?q[Vi+4>>2]:hj;lj=ij?q[Vi>>2]:Vi;while(1){Vi=a+16|0;Xi=r[a+27|0];ij=Xi<<24>>24<0;jj=ij?q[a+20>>2]:Xi;mj=jj>>>0>>0;b:{c:{d:{e:{f:{g:{h:{Xi=mj?jj:hj;if(Xi){kj=ij?q[Vi>>2]:Vi;nj=cm(lj,kj,Xi);if(nj){break h}}if(hj>>>0>>0){break g}if(!Xi){break e}kj=ij?q[Vi>>2]:Vi;break f}if((nj|0)>-1){break f}}Vi=q[a>>2];if(Vi){break b}q[ki>>2]=a;return a}Vi=cm(kj,lj,Xi);if(Vi){break d}}if(mj){break c}break a}if((Vi|0)>-1){break a}}Wi=a+4|0;Vi=q[a+4>>2];if(!Vi){break a}a=Wi}Wi=a;a=Vi;continue}}q[ki>>2]=Wi;return Wi}q[ki>>2]=a;return Wi}function qh(a,ki,Vi,oj){var pj=0,qj=0,rj=0,sj=0,tj=0;if(!a){return 1}pj=q[Vi+16>>2];sj=q[Vi+12>>2];rj=q[Vi+20>>2];qj=rj;a:{if((sj|0)<(qj|0)?1:(sj|0)<=(qj|0)?t[Vi+8>>2]>pj>>>0?0:1:0){break a}qj=r[pj+q[Vi>>2]|0];pj=pj+1|0;if(pj>>>0<1){rj=rj+1|0}q[Vi+16>>2]=pj;q[Vi+20>>2]=rj;if(qj>>>0>1){break a}if(qj-1){return rh(a,ki,Vi,oj)}tj=sh(a,Vi,oj)}return tj}function rh(a,ki,Vi,oj){var uj=0,vj=0,wj=0,xj=0,yj=0,zj=0,Aj=0,Bj=0,Cj=0,Dj=0,Ej=0,Fj=0,Gj=0,Hj=0,Ij=0,Jj=0;uj=T+ -64|0;T=uj;q[uj+56>>2]=0;q[uj+48>>2]=0;q[uj+52>>2]=0;q[uj+40>>2]=0;q[uj+44>>2]=0;q[uj+32>>2]=0;q[uj+36>>2]=0;q[uj+24>>2]=0;q[uj+28>>2]=0;q[uj+16>>2]=0;q[uj+20>>2]=0;q[uj+8>>2]=0;q[uj+12>>2]=0;a:{if(!th(uj+8|0,Vi)){break a}if(!uh(uj+8|0,Vi)|(q[uj+20>>2]?0:a)){break a}_j(Vi,0,0);if(a){xj=q[uj+56>>2];Fj=q[uj+36>>2];Gj=q[uj+48>>2];Hj=q[uj+24>>2];while(1){b:{if(xj>>>0>16383){break b}vj=q[uj+52>>2];while(1){if((vj|0)<1){break b}vj=vj+ -1|0;q[uj+52>>2]=vj;xj=r[vj+Gj|0]|xj<<8;q[uj+56>>2]=xj;if(xj>>>0<16384){continue}break}}wj=xj&4095;Dj=q[(wj<<2)+Hj>>2];yj=(Dj<<3)+Fj|0;xj=(w(q[yj>>2],xj>>>12)+wj|0)-q[yj+4>>2]|0;q[uj+56>>2]=xj;if((ki|0)>=1){if(!r[Vi+36|0]){wj=0;break a}yj=ki+zj|0;while(1){c:{if((Dj|0)<1){Bj=0;break c}wj=q[Vi+32>>2];Ij=q[Vi+28>>2];Jj=q[Vi+24>>2];vj=0;Bj=0;while(1){Aj=(wj>>>3)+Jj|0;d:{if(Aj>>>0>=Ij>>>0){Cj=0;break d}Cj=r[Aj|0];Aj=wj+1|0;q[Vi+32>>2]=Aj;Cj=Cj>>>(wj&7)&1;wj=Aj}Bj=Cj<>2]=Bj;zj=zj+1|0;if((yj|0)!=(zj|0)){continue}break}zj=yj}Ej=ki+Ej|0;if(Ej>>>0>>0){continue}break}}ak(Vi);wj=1}a=q[uj+36>>2];if(a){q[uj+40>>2]=a;An(a)}a=q[uj+24>>2];if(a){q[uj+28>>2]=a;An(a)}a=q[uj+8>>2];if(a){q[uj+12>>2]=a;An(a)}T=uj- -64|0;return wj}function sh(a,ki,Vi){var oj=0,Kj=0,Lj=0,Mj=0;a:{b:{Kj=q[ki+16>>2];Lj=q[ki+12>>2];oj=q[ki+20>>2];c:{if((Lj|0)<(oj|0)?1:(Lj|0)<=(oj|0)?t[ki+8>>2]>Kj>>>0?0:1:0){break c}Lj=r[Kj+q[ki>>2]|0];Kj=Kj+1|0;if(Kj>>>0<1){oj=oj+1|0}q[ki+16>>2]=Kj;q[ki+20>>2]=oj;oj=Lj+ -1|0;if(oj>>>0>17){break c}d:{e:{switch(oj-1|0){case 7:return wh(a,ki,Vi);case 8:return xh(a,ki,Vi);case 9:return yh(a,ki,Vi);case 10:return zh(a,ki,Vi);case 12:case 13:case 14:case 15:break a;case 16:break d;case 11:break e;default:break b}}return Ah(a,ki,Vi)}Mj=Bh(a,ki,Vi)}return Mj}return vh(a,ki,Vi)}return Bh(a,ki,Vi)}function th(a,ki){var Vi=0,Nj=0,Oj=0,Pj=0,Qj=0,Rj=0,Sj=0,Tj=0,Uj=0,Vj=0,Wj=0,Xj=0,Yj=0;a:{Vi=s[ki+38>>1];if(!Vi){break a}Sj=a+12|0;b:{if(Vi>>>0<=511){Nj=q[ki+12>>2];Vi=q[ki+20>>2];Oj=q[ki+16>>2];Qj=Oj+4|0;if(Qj>>>0<4){Vi=Vi+1|0}if((Nj|0)<(Vi|0)?1:(Nj|0)<=(Vi|0)?t[ki+8>>2]>=Qj>>>0?0:1:0){break a}Vi=Oj+q[ki>>2]|0;Oj=r[Vi|0]|r[Vi+1|0]<<8|(r[Vi+2|0]<<16|r[Vi+3|0]<<24);q[Sj>>2]=Oj;Nj=q[ki+20>>2];Qj=q[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nj|0);break h}if((Vi|0)==16384){break h}q[a+20>>2]=ki+16384}i:{ki=a+28|0;Vi=q[ki>>2];Nj=q[a+32>>2]-Vi>>3;if(Oj>>>0>Nj>>>0){Dh(ki,Oj-Nj|0);Vi=q[ki>>2];break i}if(Oj>>>0>>0){q[a+32>>2]=(Oj<<3)+Vi}if(Oj){break i}return 0}ki=0;Nj=0;while(1){a=Sj+(ki<<2)|0;Qj=q[a>>2];Pj=(ki<<3)+Vi|0;q[Pj+4>>2]=Nj;q[Pj>>2]=Qj;a=q[a>>2]+Nj|0;if(a>>>0>4096){break a}if(Nj>>>0>>0){Qj=q[Rj>>2];while(1){q[Qj+(Nj<<2)>>2]=ki;Nj=Nj+1|0;if((a|0)!=(Nj|0)){continue}break}}Nj=a;ki=ki+1|0;if((Oj|0)!=(ki|0)){continue}break}return(a|0)==4096}return Yj}function uh(a,ki){var Zj=0,_j=0,$j=0,ak=0,bk=0,ck=0,dk=0,ek=0,fk=0;bk=T-16|0;T=bk;a:{b:{if(s[ki+38>>1]<=511){_j=q[ki+12>>2];ek=_j;Zj=q[ki+20>>2];$j=q[ki+16>>2];ak=$j+8|0;if(ak>>>0<8){Zj=Zj+1|0}ck=q[ki+8>>2];if((_j|0)<(Zj|0)?1:(_j|0)<=(Zj|0)?ck>>>0>=ak>>>0?0:1:0){break a}_j=$j+q[ki>>2]|0;$j=r[_j+4|0]|r[_j+5|0]<<8|(r[_j+6|0]<<16|r[_j+7|0]<<24);_j=r[_j|0]|r[_j+1|0]<<8|(r[_j+2|0]<<16|r[_j+3|0]<<24);q[bk+8>>2]=_j;q[bk+12>>2]=$j;q[ki+16>>2]=ak;q[ki+20>>2]=Zj;break b}if(!Eh(1,bk+8|0,ki)){break a}ak=q[ki+16>>2];Zj=q[ki+20>>2];ck=q[ki+8>>2];ek=q[ki+12>>2];_j=q[bk+8>>2];$j=q[bk+12>>2]}dk=ck-ak|0;ck=ek-(Zj+(ck>>>0>>0)|0)|0;if((ck|0)==($j|0)&_j>>>0>dk>>>0|$j>>>0>ck>>>0){break a}$j=Zj+$j|0;Zj=ak;dk=Zj+_j|0;if(dk>>>0>>0){$j=$j+1|0}q[ki+16>>2]=dk;q[ki+20>>2]=$j;Zj=_j;if((Zj|0)<1){break a}ak=ak+q[ki>>2]|0;q[a+40>>2]=ak;ki=a;c:{d:{e:{f:{g:{_j=Zj+ -1|0;$j=ak+_j|0;switch((r[$j|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=_j;a=r[$j|0]&63;break c}if((Zj|0)<2){break a}q[a+44>>2]=Zj+ -2;a=(Zj+ak|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((Zj|0)<3){break a}q[a+44>>2]=Zj+ -3;a=(Zj+ak|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=Zj+ -4;a=(Zj+ak|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a+16384|0;q[ki+48>>2]=a;fk=a>>>0<4194304}T=bk+16|0;return fk}function vh(a,ki,gk){var hk=0,ik=0,jk=0,kk=0,lk=0,mk=0,nk=0,ok=0;hk=T+ -64|0;T=hk;q[hk+56>>2]=0;q[hk+48>>2]=0;q[hk+52>>2]=0;q[hk+40>>2]=0;q[hk+44>>2]=0;q[hk+32>>2]=0;q[hk+36>>2]=0;q[hk+24>>2]=0;q[hk+28>>2]=0;q[hk+16>>2]=0;q[hk+20>>2]=0;q[hk+8>>2]=0;q[hk+12>>2]=0;a:{if(!th(hk+8|0,ki)|(q[hk+20>>2]?0:a)){break a}ik=uh(hk+8|0,ki);if(!a|!ik){break a}ki=q[hk+56>>2];mk=q[hk+36>>2];nk=q[hk+48>>2];ok=q[hk+24>>2];while(1){b:{if(ki>>>0>16383){break b}ik=q[hk+52>>2];while(1){if((ik|0)<1){break b}ik=ik+ -1|0;q[hk+52>>2]=ik;ki=r[ik+nk|0]|ki<<8;q[hk+56>>2]=ki;if(ki>>>0<16384){continue}break}}ik=ki&4095;kk=q[(ik<<2)+ok>>2];lk=(kk<<3)+mk|0;ki=(w(q[lk>>2],ki>>>12)+ik|0)-q[lk+4>>2]|0;q[hk+56>>2]=ki;q[(jk<<2)+gk>>2]=kk;ik=1;jk=jk+1|0;if((jk|0)!=(a|0)){continue}break}}a=q[hk+36>>2];if(a){q[hk+40>>2]=a;An(a)}a=q[hk+24>>2];if(a){q[hk+28>>2]=a;An(a)}a=q[hk+8>>2];if(a){q[hk+12>>2]=a;An(a)}T=hk- -64|0;return ik}function wh(a,ki,gk){var pk=0,qk=0,rk=0,sk=0,tk=0,uk=0,vk=0,wk=0;pk=T+ -64|0;T=pk;q[pk+56>>2]=0;q[pk+48>>2]=0;q[pk+52>>2]=0;q[pk+40>>2]=0;q[pk+44>>2]=0;q[pk+32>>2]=0;q[pk+36>>2]=0;q[pk+24>>2]=0;q[pk+28>>2]=0;q[pk+16>>2]=0;q[pk+20>>2]=0;q[pk+8>>2]=0;q[pk+12>>2]=0;a:{if(!Fh(pk+8|0,ki)|(q[pk+20>>2]?0:a)){break a}qk=Gh(pk+8|0,ki);if(!a|!qk){break a}ki=q[pk+56>>2];uk=q[pk+36>>2];vk=q[pk+48>>2];wk=q[pk+24>>2];while(1){b:{if(ki>>>0>32767){break b}qk=q[pk+52>>2];while(1){if((qk|0)<1){break b}qk=qk+ -1|0;q[pk+52>>2]=qk;ki=r[qk+vk|0]|ki<<8;q[pk+56>>2]=ki;if(ki>>>0<32768){continue}break}}qk=ki&8191;sk=q[(qk<<2)+wk>>2];tk=(sk<<3)+uk|0;ki=(w(q[tk>>2],ki>>>13)+qk|0)-q[tk+4>>2]|0;q[pk+56>>2]=ki;q[(rk<<2)+gk>>2]=sk;qk=1;rk=rk+1|0;if((rk|0)!=(a|0)){continue}break}}a=q[pk+36>>2];if(a){q[pk+40>>2]=a;An(a)}a=q[pk+24>>2];if(a){q[pk+28>>2]=a;An(a)}a=q[pk+8>>2];if(a){q[pk+12>>2]=a;An(a)}T=pk- -64|0;return qk}function xh(a,ki,gk){var xk=0,yk=0,zk=0,Ak=0,Bk=0,Ck=0,Dk=0,Ek=0;xk=T+ -64|0;T=xk;q[xk+56>>2]=0;q[xk+48>>2]=0;q[xk+52>>2]=0;q[xk+40>>2]=0;q[xk+44>>2]=0;q[xk+32>>2]=0;q[xk+36>>2]=0;q[xk+24>>2]=0;q[xk+28>>2]=0;q[xk+16>>2]=0;q[xk+20>>2]=0;q[xk+8>>2]=0;q[xk+12>>2]=0;a:{if(!Hh(xk+8|0,ki)|(q[xk+20>>2]?0:a)){break a}yk=Ih(xk+8|0,ki);if(!a|!yk){break a}ki=q[xk+56>>2];Ck=q[xk+36>>2];Dk=q[xk+48>>2];Ek=q[xk+24>>2];while(1){b:{if(ki>>>0>131071){break b}yk=q[xk+52>>2];while(1){if((yk|0)<1){break b}yk=yk+ -1|0;q[xk+52>>2]=yk;ki=r[yk+Dk|0]|ki<<8;q[xk+56>>2]=ki;if(ki>>>0<131072){continue}break}}yk=ki&32767;Ak=q[(yk<<2)+Ek>>2];Bk=(Ak<<3)+Ck|0;ki=(w(q[Bk>>2],ki>>>15)+yk|0)-q[Bk+4>>2]|0;q[xk+56>>2]=ki;q[(zk<<2)+gk>>2]=Ak;yk=1;zk=zk+1|0;if((zk|0)!=(a|0)){continue}break}}a=q[xk+36>>2];if(a){q[xk+40>>2]=a;An(a)}a=q[xk+24>>2];if(a){q[xk+28>>2]=a;An(a)}a=q[xk+8>>2];if(a){q[xk+12>>2]=a;An(a)}T=xk- -64|0;return yk}function yh(a,ki,gk){var Fk=0,Gk=0,Hk=0,Ik=0,Jk=0,Kk=0,Lk=0,Mk=0;Fk=T+ -64|0;T=Fk;q[Fk+56>>2]=0;q[Fk+48>>2]=0;q[Fk+52>>2]=0;q[Fk+40>>2]=0;q[Fk+44>>2]=0;q[Fk+32>>2]=0;q[Fk+36>>2]=0;q[Fk+24>>2]=0;q[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nk+24>>2];while(1){b:{if(ki>>>0>1048575){break b}Ok=q[Nk+52>>2];while(1){if((Ok|0)<1){break b}Ok=Ok+ -1|0;q[Nk+52>>2]=Ok;ki=r[Ok+Tk|0]|ki<<8;q[Nk+56>>2]=ki;if(ki>>>0<1048576){continue}break}}Ok=ki&262143;Qk=q[(Ok<<2)+Uk>>2];Rk=(Qk<<3)+Sk|0;ki=(w(q[Rk>>2],ki>>>18)+Ok|0)-q[Rk+4>>2]|0;q[Nk+56>>2]=ki;q[(Pk<<2)+gk>>2]=Qk;Ok=1;Pk=Pk+1|0;if((Pk|0)!=(a|0)){continue}break}}a=q[Nk+36>>2];if(a){q[Nk+40>>2]=a;An(a)}a=q[Nk+24>>2];if(a){q[Nk+28>>2]=a;An(a)}a=q[Nk+8>>2];if(a){q[Nk+12>>2]=a;An(a)}T=Nk- -64|0;return Ok}function Ah(a,ki,gk){var Vk=0,Wk=0,Xk=0,Yk=0,Zk=0,_k=0,$k=0,al=0;Vk=T+ -64|0;T=Vk;q[Vk+56>>2]=0;q[Vk+48>>2]=0;q[Vk+52>>2]=0;q[Vk+40>>2]=0;q[Vk+44>>2]=0;q[Vk+32>>2]=0;q[Vk+36>>2]=0;q[Vk+24>>2]=0;q[Vk+28>>2]=0;q[Vk+16>>2]=0;q[Vk+20>>2]=0;q[Vk+8>>2]=0;q[Vk+12>>2]=0;a:{if(!Nh(Vk+8|0,ki)|(q[Vk+20>>2]?0:a)){break a}Wk=Oh(Vk+8|0,ki);if(!a|!Wk){break a}ki=q[Vk+56>>2];_k=q[Vk+36>>2];$k=q[Vk+48>>2];al=q[Vk+24>>2];while(1){b:{if(ki>>>0>2097151){break b}Wk=q[Vk+52>>2];while(1){if((Wk|0)<1){break b}Wk=Wk+ -1|0;q[Vk+52>>2]=Wk;ki=r[Wk+$k|0]|ki<<8;q[Vk+56>>2]=ki;if(ki>>>0<2097152){continue}break}}Wk=ki&524287;Yk=q[(Wk<<2)+al>>2];Zk=(Yk<<3)+_k|0;ki=(w(q[Zk>>2],ki>>>19)+Wk|0)-q[Zk+4>>2]|0;q[Vk+56>>2]=ki;q[(Xk<<2)+gk>>2]=Yk;Wk=1;Xk=Xk+1|0;if((Xk|0)!=(a|0)){continue}break}}a=q[Vk+36>>2];if(a){q[Vk+40>>2]=a;An(a)}a=q[Vk+24>>2];if(a){q[Vk+28>>2]=a;An(a)}a=q[Vk+8>>2];if(a){q[Vk+12>>2]=a;An(a)}T=Vk- -64|0;return Wk}function Bh(a,ki,gk){var bl=0,cl=0,dl=0,el=0,fl=0,gl=0,hl=0,il=0;bl=T+ -64|0;T=bl;q[bl+56>>2]=0;q[bl+48>>2]=0;q[bl+52>>2]=0;q[bl+40>>2]=0;q[bl+44>>2]=0;q[bl+32>>2]=0;q[bl+36>>2]=0;q[bl+24>>2]=0;q[bl+28>>2]=0;q[bl+16>>2]=0;q[bl+20>>2]=0;q[bl+8>>2]=0;q[bl+12>>2]=0;a:{if(!Ph(bl+8|0,ki)|(q[bl+20>>2]?0:a)){break a}cl=Qh(bl+8|0,ki);if(!a|!cl){break a}ki=q[bl+56>>2];gl=q[bl+36>>2];hl=q[bl+48>>2];il=q[bl+24>>2];while(1){b:{if(ki>>>0>4194303){break b}cl=q[bl+52>>2];while(1){if((cl|0)<1){break b}cl=cl+ -1|0;q[bl+52>>2]=cl;ki=r[cl+hl|0]|ki<<8;q[bl+56>>2]=ki;if(ki>>>0<4194304){continue}break}}cl=ki&1048575;el=q[(cl<<2)+il>>2];fl=(el<<3)+gl|0;ki=(w(q[fl>>2],ki>>>20)+cl|0)-q[fl+4>>2]|0;q[bl+56>>2]=ki;q[(dl<<2)+gk>>2]=el;cl=1;dl=dl+1|0;if((dl|0)!=(a|0)){continue}break}}a=q[bl+36>>2];if(a){q[bl+40>>2]=a;An(a)}a=q[bl+24>>2];if(a){q[bl+28>>2]=a;An(a)}a=q[bl+8>>2];if(a){q[bl+12>>2]=a;An(a)}T=bl- -64|0;return cl}function Ch(a,ki,gk){var jl=0,kl=0,ll=0,ml=0;a:{if(a>>>0>5){break a}ll=q[gk+16>>2];jl=q[gk+12>>2];kl=q[gk+20>>2];if((jl|0)<(kl|0)?1:(jl|0)<=(kl|0)?t[gk+8>>2]>ll>>>0?0:1:0){break a}jl=r[ll+q[gk>>2]|0];ll=ll+1|0;if(ll>>>0<1){kl=kl+1|0}q[gk+16>>2]=ll;q[gk+20>>2]=kl;kl=ki;if(jl&128){if(!Ch(a+1|0,ki,gk)){break a}a=q[ki>>2]<<7;q[ki>>2]=a;jl=a|jl&127}q[kl>>2]=jl;ml=1}return ml}function Dh(a,ki){var gk=0,nl=0,ol=0,pl=0,ql=0,rl=0,sl=0;a:{b:{ol=q[a+8>>2];gk=a+4|0;nl=q[gk>>2];c:{if(ol-nl>>3>>>0>=ki>>>0){while(1){q[nl>>2]=0;q[nl+4>>2]=0;nl=q[gk>>2]+8|0;q[gk>>2]=nl;ki=ki+ -1|0;if(ki){continue}break c}}pl=q[a>>2];ql=nl-pl|0;gk=ql>>3;nl=gk+ki|0;if(nl>>>0>=536870912){break b}sl=gk<<3;ol=ol-pl|0;gk=ol>>2;ol=ol>>3>>>0<268435455?gk>>>0>>0?nl:gk:536870911;gk=0;d:{if(!ol){break d}if(ol>>>0>=536870912){break a}rl=Mm(ol<<3);gk=rl}nl=sl+gk|0;Dn(nl,0,ki<<3);ol=gk+(ol<<3)|0;while(1){nl=nl+8|0;ki=ki+ -1|0;if(ki){continue}break}if((ql|0)>=1){Cn(rl,pl,ql)}q[a>>2]=gk;q[a+8>>2]=ol;q[a+4>>2]=nl;if(!pl){break c}An(pl)}return}bn();F()}ab(10991);F()}function Eh(a,ki,tl){var ul=0,vl=0,wl=0,xl=0,yl=0,zl=0;a:{if(a>>>0>10){break a}wl=q[tl+16>>2];ul=q[tl+12>>2];vl=q[tl+20>>2];xl=vl;if((ul|0)<(xl|0)?1:(ul|0)<=(xl|0)?t[tl+8>>2]>wl>>>0?0:1:0){break a}yl=o[wl+q[tl>>2]|0];ul=wl+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Cl>>>0<1){tl=tl+1|0}q[ki+16>>2]=Cl;q[ki+20>>2]=tl;Hl=Gl>>>2;d:{e:{f:{Il=Gl&3;if(Il>>>0>3){Al=0;break f}Al=0;g:{switch(Il-1|0){case 0:case 1:break f;case 2:break g;default:break e}}tl=El+Hl|0;if(tl>>>0>=Bl>>>0){return 0}Dn(q[a>>2]+(El<<2)|0,0,(Gl&252)+4|0);El=tl;break d}while(1){if((Dl|0)<(tl|0)?1:(Dl|0)<=(tl|0)?Jl>>>0>Cl>>>0?0:1:0){return 0}Gl=r[Cl+Kl|0];Cl=Cl+1|0;if(Cl>>>0<1){tl=tl+1|0}q[ki+16>>2]=Cl;q[ki+20>>2]=tl;Hl=Gl<<(Al<<3|6)|Hl;Al=Al+1|0;if((Il|0)!=(Al|0)){continue}break}}q[q[a>>2]+(El<<2)>>2]=Hl}El=El+1|0;Bl=q[Fl>>2];if(El>>>0>>0){continue}break}El=a+16|0;Fl=q[a>>2];ki=q[a+16>>2];tl=q[a+20>>2]-ki|0;Al=tl>>2;h:{if(Al>>>0<=8191){Fa(El,8192-Al|0);break h}if((tl|0)==32768){break h}q[a+20>>2]=ki+32768}i:{ki=a+28|0;tl=q[ki>>2];Al=q[a+32>>2]-tl>>3;if(Bl>>>0>Al>>>0){Dh(ki,Bl-Al|0);tl=q[ki>>2];break i}if(Bl>>>0>>0){q[a+32>>2]=(Bl<<3)+tl}if(Bl){break i}return 0}ki=0;Al=0;while(1){a=Fl+(ki<<2)|0;Dl=q[a>>2];Cl=(ki<<3)+tl|0;q[Cl+4>>2]=Al;q[Cl>>2]=Dl;a=q[a>>2]+Al|0;if(a>>>0>8192){break a}if(Al>>>0>>0){Dl=q[El>>2];while(1){q[Dl+(Al<<2)>>2]=ki;Al=Al+1|0;if((a|0)!=(Al|0)){continue}break}}Al=a;ki=ki+1|0;if((Bl|0)!=(ki|0)){continue}break}return(a|0)==8192}return Ll}function Gh(a,ki){var Ml=0,Nl=0,Ol=0,Pl=0,Ql=0,R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=Vl;bm=am>>>2;d:{e:{f:{cm=am&3;if(cm>>>0>3){Wl=0;break f}Wl=0;g:{switch(cm-1|0){case 0:case 1:break f;case 2:break g;default:break e}}Vl=_l+bm|0;if(Vl>>>0>=Xl>>>0){return 0}Dn(q[a>>2]+(_l<<2)|0,0,(am&252)+4|0);_l=Vl;break d}while(1){if((Zl|0)<(Vl|0)?1:(Zl|0)<=(Vl|0)?dm>>>0>Yl>>>0?0:1:0){return 0}am=r[Yl+em|0];Yl=Yl+1|0;if(Yl>>>0<1){Vl=Vl+1|0}q[ki+16>>2]=Yl;q[ki+20>>2]=Vl;bm=am<<(Wl<<3|6)|bm;Wl=Wl+1|0;if((cm|0)!=(Wl|0)){continue}break}}q[q[a>>2]+(_l<<2)>>2]=bm}_l=_l+1|0;Xl=q[$l>>2];if(_l>>>0>>0){continue}break}_l=a+16|0;$l=q[a>>2];ki=q[a+16>>2];Vl=q[a+20>>2]-ki|0;Wl=Vl>>2;h:{if(Wl>>>0<=32767){Fa(_l,32768-Wl|0);break h}if((Vl|0)==131072){break h}q[a+20>>2]=ki+131072}i:{ki=a+28|0;Vl=q[ki>>2];Wl=q[a+32>>2]-Vl>>3;if(Xl>>>0>Wl>>>0){Dh(ki,Xl-Wl|0);Vl=q[ki>>2];break i}if(Xl>>>0>>0){q[a+32>>2]=(Xl<<3)+Vl}if(Xl){break i}return 0}ki=0;Wl=0;while(1){a=$l+(ki<<2)|0;Zl=q[a>>2];Yl=(ki<<3)+Vl|0;q[Yl+4>>2]=Wl;q[Yl>>2]=Zl;a=q[a>>2]+Wl|0;if(a>>>0>32768){break a}if(Wl>>>0>>0){Zl=q[_l>>2];while(1){q[Zl+(Wl<<2)>>2]=ki;Wl=Wl+1|0;if((a|0)!=(Wl|0)){continue}break}}Wl=a;ki=ki+1|0;if((Xl|0)!=(ki|0)){continue}break}return(a|0)==32768}return fm}function Ih(a,ki){var gm=0,hm=0,im=0,jm=0,km=0,lm=0,mm=0,nm=0,om=0;km=T-16|0;T=km;a:{b:{if(s[ki+38>>1]<=511){hm=q[ki+12>>2];nm=hm;gm=q[ki+20>>2];im=q[ki+16>>2];jm=im+8|0;if(jm>>>0<8){gm=gm+1|0}lm=q[ki+8>>2];if((hm|0)<(gm|0)?1:(hm|0)<=(gm|0)?lm>>>0>=jm>>>0?0:1:0){break a}hm=im+q[ki>>2]|0;im=r[hm+4|0]|r[hm+5|0]<<8|(r[hm+6|0]<<16|r[hm+7|0]<<24);hm=r[hm|0]|r[hm+1|0]<<8|(r[hm+2|0]<<16|r[hm+3|0]<<24);q[km+8>>2]=hm;q[km+12>>2]=im;q[ki+16>>2]=jm;q[ki+20>>2]=gm;break b}if(!Eh(1,km+8|0,ki)){break a}jm=q[ki+16>>2];gm=q[ki+20>>2];lm=q[ki+8>>2];nm=q[ki+12>>2];hm=q[km+8>>2];im=q[km+12>>2]}mm=lm-jm|0;lm=nm-(gm+(lm>>>0>>0)|0)|0;if((lm|0)==(im|0)&hm>>>0>mm>>>0|im>>>0>lm>>>0){break a}im=gm+im|0;gm=jm;mm=gm+hm|0;if(mm>>>0>>0){im=im+1|0}q[ki+16>>2]=mm;q[ki+20>>2]=im;gm=hm;if((gm|0)<1){break a}jm=jm+q[ki>>2]|0;q[a+40>>2]=jm;ki=a;c:{d:{e:{f:{g:{hm=gm+ -1|0;im=jm+hm|0;switch((r[im|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=hm;a=r[im|0]&63;break c}if((gm|0)<2){break a}q[a+44>>2]=gm+ -2;a=(gm+jm|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((gm|0)<3){break a}q[a+44>>2]=gm+ -3;a=(gm+jm|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=gm+ -4;a=(gm+jm|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a+131072|0;q[ki+48>>2]=a;om=a>>>0<33554432}T=km+16|0;return om}function Jh(a,ki){var pm=0,qm=0,rm=0,sm=0,tm=0,um=0,vm=0,wm=0,xm=0,ym=0,zm=0,Am=0,Bm=0;a:{pm=s[ki+38>>1];if(!pm){break a}vm=a+12|0;b:{if(pm>>>0<=511){qm=q[ki+12>>2];pm=q[ki+20>>2];rm=q[ki+16>>2];tm=rm+4|0;if(tm>>>0<4){pm=pm+1|0}if((qm|0)<(pm|0)?1:(qm|0)<=(pm|0)?t[ki+8>>2]>=tm>>>0?0:1:0){break a}pm=rm+q[ki>>2]|0;rm=r[pm|0]|r[pm+1|0]<<8|(r[pm+2|0]<<16|r[pm+3|0]<<24);q[vm>>2]=rm;qm=q[ki+20>>2];tm=q[ki+16>>2]+4|0;if(tm>>>0<4){qm=qm+1|0}pm=ki;q[pm+16>>2]=tm;q[pm+20>>2]=qm;break b}if(!Ch(1,vm,ki)){break a}rm=q[vm>>2]}qm=q[a>>2];pm=q[a+4>>2]-qm>>2;c:{if(rm>>>0>pm>>>0){Fa(a,rm-pm|0);rm=q[a+12>>2];break c}if(rm>>>0>=pm>>>0){break c}q[a+4>>2]=qm+(rm<<2)}if(!rm){Bm=1;break a}zm=q[ki+8>>2];tm=q[ki+12>>2];while(1){sm=q[ki+16>>2];pm=q[ki+20>>2];if((tm|0)<(pm|0)?1:(tm|0)<=(pm|0)?zm>>>0>sm>>>0?0:1:0){break a}Am=q[ki>>2];wm=r[Am+sm|0];sm=sm+1|0;if(sm>>>0<1){pm=pm+1|0}q[ki+16>>2]=sm;q[ki+20>>2]=pm;xm=wm>>>2;d:{e:{f:{ym=wm&3;if(ym>>>0>3){qm=0;break f}qm=0;g:{switch(ym-1|0){case 0:case 1:break f;case 2:break g;default:break e}}pm=um+xm|0;if(pm>>>0>=rm>>>0){return 0}Dn(q[a>>2]+(um<<2)|0,0,(wm&252)+4|0);um=pm;break d}while(1){if((tm|0)<(pm|0)?1:(tm|0)<=(pm|0)?zm>>>0>sm>>>0?0:1:0){return 0}wm=r[sm+Am|0];sm=sm+1|0;if(sm>>>0<1){pm=pm+1|0}q[ki+16>>2]=sm;q[ki+20>>2]=pm;xm=wm<<(qm<<3|6)|xm;qm=qm+1|0;if((ym|0)!=(qm|0)){continue}break}}q[q[a>>2]+(um<<2)>>2]=xm}um=um+1|0;rm=q[vm>>2];if(um>>>0>>0){continue}break}um=a+16|0;vm=q[a>>2];ki=q[a+16>>2];pm=q[a+20>>2]-ki|0;qm=pm>>2;h:{if(qm>>>0<=65535){Fa(um,65536-qm|0);break h}if((pm|0)==262144){break h}q[a+20>>2]=ki+262144}i:{ki=a+28|0;pm=q[ki>>2];qm=q[a+32>>2]-pm>>3;if(rm>>>0>qm>>>0){Dh(ki,rm-qm|0);pm=q[ki>>2];break i}if(rm>>>0>>0){q[a+32>>2]=(rm<<3)+pm}if(rm){break i}return 0}ki=0;qm=0;while(1){a=vm+(ki<<2)|0;tm=q[a>>2];sm=(ki<<3)+pm|0;q[sm+4>>2]=qm;q[sm>>2]=tm;a=q[a>>2]+qm|0;if(a>>>0>65536){break a}if(qm>>>0>>0){tm=q[um>>2];while(1){q[tm+(qm<<2)>>2]=ki;qm=qm+1|0;if((a|0)!=(qm|0)){continue}break}}qm=a;ki=ki+1|0;if((rm|0)!=(ki|0)){continue}break}return(a|0)==65536}return Bm}function Kh(a,ki){var Cm=0,Dm=0,Em=0,Fm=0,Gm=0,Hm=0,Im=0,Jm=0,Km=0;Gm=T-16|0;T=Gm;a:{b:{if(s[ki+38>>1]<=511){Dm=q[ki+12>>2];Jm=Dm;Cm=q[ki+20>>2];Em=q[ki+16>>2];Fm=Em+8|0;if(Fm>>>0<8){Cm=Cm+1|0}Hm=q[ki+8>>2];if((Dm|0)<(Cm|0)?1:(Dm|0)<=(Cm|0)?Hm>>>0>=Fm>>>0?0:1:0){break a}Dm=Em+q[ki>>2]|0;Em=r[Dm+4|0]|r[Dm+5|0]<<8|(r[Dm+6|0]<<16|r[Dm+7|0]<<24);Dm=r[Dm|0]|r[Dm+1|0]<<8|(r[Dm+2|0]<<16|r[Dm+3|0]<<24);q[Gm+8>>2]=Dm;q[Gm+12>>2]=Em;q[ki+16>>2]=Fm;q[ki+20>>2]=Cm;break b}if(!Eh(1,Gm+8|0,ki)){break a}Fm=q[ki+16>>2];Cm=q[ki+20>>2];Hm=q[ki+8>>2];Jm=q[ki+12>>2];Dm=q[Gm+8>>2];Em=q[Gm+12>>2]}Im=Hm-Fm|0;Hm=Jm-(Cm+(Hm>>>0>>0)|0)|0;if((Hm|0)==(Em|0)&Dm>>>0>Im>>>0|Em>>>0>Hm>>>0){break a}Em=Cm+Em|0;Cm=Fm;Im=Cm+Dm|0;if(Im>>>0>>0){Em=Em+1|0}q[ki+16>>2]=Im;q[ki+20>>2]=Em;Cm=Dm;if((Cm|0)<1){break a}Fm=Fm+q[ki>>2]|0;q[a+40>>2]=Fm;ki=a;c:{d:{e:{f:{g:{Dm=Cm+ -1|0;Em=Fm+Dm|0;switch((r[Em|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=Dm;a=r[Em|0]&63;break c}if((Cm|0)<2){break a}q[a+44>>2]=Cm+ -2;a=(Cm+Fm|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((Cm|0)<3){break a}q[a+44>>2]=Cm+ -3;a=(Cm+Fm|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=Cm+ -4;a=(Cm+Fm|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a+262144|0;q[ki+48>>2]=a;Km=a>>>0<67108864}T=Gm+16|0;return Km}function Lh(a,ki){var Lm=0,Mm=0,Nm=0,Om=0,Pm=0,Qm=0,Rm=0,Sm=0,Tm=0,Um=0,Vm=0,Wm=0,Xm=0;a:{Lm=s[ki+38>>1];if(!Lm){break a}Rm=a+12|0;b:{if(Lm>>>0<=511){Mm=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+20>>2]=Lm;Tm=Sm<<(Mm<<3|6)|Tm;Mm=Mm+1|0;if((Um|0)!=(Mm|0)){continue}break}}q[q[a>>2]+(Qm<<2)>>2]=Tm}Qm=Qm+1|0;Nm=q[Rm>>2];if(Qm>>>0>>0){continue}break}Qm=a+16|0;Rm=q[a>>2];ki=q[a+16>>2];Lm=q[a+20>>2]-ki|0;Mm=Lm>>2;h:{if(Mm>>>0<=262143){Fa(Qm,262144-Mm|0);break h}if((Lm|0)==1048576){break h}q[a+20>>2]=ki- -1048576}i:{ki=a+28|0;Lm=q[ki>>2];Mm=q[a+32>>2]-Lm>>3;if(Nm>>>0>Mm>>>0){Dh(ki,Nm-Mm|0);Lm=q[ki>>2];break i}if(Nm>>>0>>0){q[a+32>>2]=(Nm<<3)+Lm}if(Nm){break i}return 0}ki=0;Mm=0;while(1){a=Rm+(ki<<2)|0;Pm=q[a>>2];Om=(ki<<3)+Lm|0;q[Om+4>>2]=Mm;q[Om>>2]=Pm;a=q[a>>2]+Mm|0;if(a>>>0>262144){break a}if(Mm>>>0>>0){Pm=q[Qm>>2];while(1){q[Pm+(Mm<<2)>>2]=ki;Mm=Mm+1|0;if((a|0)!=(Mm|0)){continue}break}}Mm=a;ki=ki+1|0;if((Nm|0)!=(ki|0)){continue}break}return(a|0)==262144}return Xm}function Mh(a,ki){var Ym=0,Zm=0,_m=0,$m=0,an=0,bn=0,cn=0,dn=0,en=0;an=T-16|0;T=an;a:{b:{if(s[ki+38>>1]<=511){Zm=q[ki+12>>2];dn=Zm;Ym=q[ki+20>>2];_m=q[ki+16>>2];$m=_m+8|0;if($m>>>0<8){Ym=Ym+1|0}bn=q[ki+8>>2];if((Zm|0)<(Ym|0)?1:(Zm|0)<=(Ym|0)?bn>>>0>=$m>>>0?0:1:0){break a}Zm=_m+q[ki>>2]|0;_m=r[Zm+4|0]|r[Zm+5|0]<<8|(r[Zm+6|0]<<16|r[Zm+7|0]<<24);Zm=r[Zm|0]|r[Zm+1|0]<<8|(r[Zm+2|0]<<16|r[Zm+3|0]<<24);q[an+8>>2]=Zm;q[an+12>>2]=_m;q[ki+16>>2]=$m;q[ki+20>>2]=Ym;break b}if(!Eh(1,an+8|0,ki)){break a}$m=q[ki+16>>2];Ym=q[ki+20>>2];bn=q[ki+8>>2];dn=q[ki+12>>2];Zm=q[an+8>>2];_m=q[an+12>>2]}cn=bn-$m|0;bn=dn-(Ym+(bn>>>0<$m>>>0)|0)|0;if((bn|0)==(_m|0)&Zm>>>0>cn>>>0|_m>>>0>bn>>>0){break a}_m=Ym+_m|0;Ym=$m;cn=Ym+Zm|0;if(cn>>>0>>0){_m=_m+1|0}q[ki+16>>2]=cn;q[ki+20>>2]=_m;Ym=Zm;if((Ym|0)<1){break a}$m=$m+q[ki>>2]|0;q[a+40>>2]=$m;ki=a;c:{d:{e:{f:{g:{Zm=Ym+ -1|0;_m=$m+Zm|0;switch((r[_m|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=Zm;a=r[_m|0]&63;break c}if((Ym|0)<2){break a}q[a+44>>2]=Ym+ -2;a=(Ym+$m|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((Ym|0)<3){break a}q[a+44>>2]=Ym+ -3;a=(Ym+$m|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=Ym+ -4;a=(Ym+$m|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a- -1048576|0;q[ki+48>>2]=a;en=a>>>0<268435456}T=an+16|0;return en}function Nh(a,ki){var fn=0,gn=0,hn=0,jn=0,kn=0,ln=0,mn=0,nn=0,on=0,pn=0,qn=0,rn=0,sn=0;a:{fn=s[ki+38>>1];if(!fn){break a}mn=a+12|0;b:{if(fn>>>0<=511){gn=q[ki+12>>2];fn=q[ki+20>>2];hn=q[ki+16>>2];kn=hn+4|0;if(kn>>>0<4){fn=fn+1|0}if((gn|0)<(fn|0)?1:(gn|0)<=(fn|0)?t[ki+8>>2]>=kn>>>0?0:1:0){break a}fn=hn+q[ki>>2]|0;hn=r[fn|0]|r[fn+1|0]<<8|(r[fn+2|0]<<16|r[fn+3|0]<<24);q[mn>>2]=hn;gn=q[ki+20>>2];kn=q[ki+16>>2]+4|0;if(kn>>>0<4){gn=gn+1|0}fn=ki;q[fn+16>>2]=kn;q[fn+20>>2]=gn;break b}if(!Ch(1,mn,ki)){break a}hn=q[mn>>2]}gn=q[a>>2];fn=q[a+4>>2]-gn>>2;c:{if(hn>>>0>fn>>>0){Fa(a,hn-fn|0);hn=q[a+12>>2];break c}if(hn>>>0>=fn>>>0){break c}q[a+4>>2]=gn+(hn<<2)}if(!hn){sn=1;break a}qn=q[ki+8>>2];kn=q[ki+12>>2];while(1){jn=q[ki+16>>2];fn=q[ki+20>>2];if((kn|0)<(fn|0)?1:(kn|0)<=(fn|0)?qn>>>0>jn>>>0?0:1:0){break a}rn=q[ki>>2];nn=r[rn+jn|0];jn=jn+1|0;if(jn>>>0<1){fn=fn+1|0}q[ki+16>>2]=jn;q[ki+20>>2]=fn;on=nn>>>2;d:{e:{f:{pn=nn&3;if(pn>>>0>3){gn=0;break f}gn=0;g:{switch(pn-1|0){case 0:case 1:break f;case 2:break g;default:break e}}fn=ln+on|0;if(fn>>>0>=hn>>>0){return 0}Dn(q[a>>2]+(ln<<2)|0,0,(nn&252)+4|0);ln=fn;break d}while(1){if((kn|0)<(fn|0)?1:(kn|0)<=(fn|0)?qn>>>0>jn>>>0?0:1:0){return 0}nn=r[jn+rn|0];jn=jn+1|0;if(jn>>>0<1){fn=fn+1|0}q[ki+16>>2]=jn;q[ki+20>>2]=fn;on=nn<<(gn<<3|6)|on;gn=gn+1|0;if((pn|0)!=(gn|0)){continue}break}}q[q[a>>2]+(ln<<2)>>2]=on}ln=ln+1|0;hn=q[mn>>2];if(ln>>>0>>0){continue}break}ln=a+16|0;mn=q[a>>2];ki=q[a+16>>2];fn=q[a+20>>2]-ki|0;gn=fn>>2;h:{if(gn>>>0<=524287){Fa(ln,524288-gn|0);break h}if((fn|0)==2097152){break h}q[a+20>>2]=ki+2097152}i:{ki=a+28|0;fn=q[ki>>2];gn=q[a+32>>2]-fn>>3;if(hn>>>0>gn>>>0){Dh(ki,hn-gn|0);fn=q[ki>>2];break i}if(hn>>>0>>0){q[a+32>>2]=(hn<<3)+fn}if(hn){break i}return 0}ki=0;gn=0;while(1){a=mn+(ki<<2)|0;kn=q[a>>2];jn=(ki<<3)+fn|0;q[jn+4>>2]=gn;q[jn>>2]=kn;a=q[a>>2]+gn|0;if(a>>>0>524288){break a}if(gn>>>0>>0){kn=q[ln>>2];while(1){q[kn+(gn<<2)>>2]=ki;gn=gn+1|0;if((a|0)!=(gn|0)){continue}break}}gn=a;ki=ki+1|0;if((hn|0)!=(ki|0)){continue}break}return(a|0)==524288}return sn}function Oh(a,ki){var tn=0,un=0,vn=0,wn=0,xn=0,yn=0,zn=0,An=0,Bn=0;xn=T-16|0;T=xn;a:{b:{if(s[ki+38>>1]<=511){un=q[ki+12>>2];An=un;tn=q[ki+20>>2];vn=q[ki+16>>2];wn=vn+8|0;if(wn>>>0<8){tn=tn+1|0}yn=q[ki+8>>2];if((un|0)<(tn|0)?1:(un|0)<=(tn|0)?yn>>>0>=wn>>>0?0:1:0){break a}un=vn+q[ki>>2]|0;vn=r[un+4|0]|r[un+5|0]<<8|(r[un+6|0]<<16|r[un+7|0]<<24);un=r[un|0]|r[un+1|0]<<8|(r[un+2|0]<<16|r[un+3|0]<<24);q[xn+8>>2]=un;q[xn+12>>2]=vn;q[ki+16>>2]=wn;q[ki+20>>2]=tn;break b}if(!Eh(1,xn+8|0,ki)){break a}wn=q[ki+16>>2];tn=q[ki+20>>2];yn=q[ki+8>>2];An=q[ki+12>>2];un=q[xn+8>>2];vn=q[xn+12>>2]}zn=yn-wn|0;yn=An-(tn+(yn>>>0>>0)|0)|0;if((yn|0)==(vn|0)&un>>>0>zn>>>0|vn>>>0>yn>>>0){break a}vn=tn+vn|0;tn=wn;zn=tn+un|0;if(zn>>>0>>0){vn=vn+1|0}q[ki+16>>2]=zn;q[ki+20>>2]=vn;tn=un;if((tn|0)<1){break a}wn=wn+q[ki>>2]|0;q[a+40>>2]=wn;ki=a;c:{d:{e:{f:{g:{un=tn+ -1|0;vn=wn+un|0;switch((r[vn|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=un;a=r[vn|0]&63;break c}if((tn|0)<2){break a}q[a+44>>2]=tn+ -2;a=(tn+wn|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((tn|0)<3){break a}q[a+44>>2]=tn+ -3;a=(tn+wn|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=tn+ -4;a=(tn+wn|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a+2097152|0;q[ki+48>>2]=a;Bn=a>>>0<536870912}T=xn+16|0;return Bn}function Ph(a,ki){var Cn=0,En=0,Fn=0,Gn=0,Hn=0,In=0,Jn=0,Kn=0,Ln=0,Mn=0,Nn=0,On=0,Pn=0;a:{Cn=s[ki+38>>1];if(!Cn){break a}Jn=a+12|0;b:{if(Cn>>>0<=511){En=q[ki+12>>2];Cn=q[ki+20>>2];Fn=q[ki+16>>2];Hn=Fn+4|0;if(Hn>>>0<4){Cn=Cn+1|0}if((En|0)<(Cn|0)?1:(En|0)<=(Cn|0)?t[ki+8>>2]>=Hn>>>0?0:1:0){break a}Cn=Fn+q[ki>>2]|0;Fn=r[Cn|0]|r[Cn+1|0]<<8|(r[Cn+2|0]<<16|r[Cn+3|0]<<24);q[Jn>>2]=Fn;En=q[ki+20>>2];Hn=q[ki+16>>2]+4|0;if(Hn>>>0<4){En=En+1|0}Cn=ki;q[Cn+16>>2]=Hn;q[Cn+20>>2]=En;break b}if(!Ch(1,Jn,ki)){break a}Fn=q[Jn>>2]}En=q[a>>2];Cn=q[a+4>>2]-En>>2;c:{if(Fn>>>0>Cn>>>0){Fa(a,Fn-Cn|0);Fn=q[a+12>>2];break c}if(Fn>>>0>=Cn>>>0){break c}q[a+4>>2]=En+(Fn<<2)}if(!Fn){Pn=1;break a}Nn=q[ki+8>>2];Hn=q[ki+12>>2];while(1){Gn=q[ki+16>>2];Cn=q[ki+20>>2];if((Hn|0)<(Cn|0)?1:(Hn|0)<=(Cn|0)?Nn>>>0>Gn>>>0?0:1:0){break a}On=q[ki>>2];Kn=r[On+Gn|0];Gn=Gn+1|0;if(Gn>>>0<1){Cn=Cn+1|0}q[ki+16>>2]=Gn;q[ki+20>>2]=Cn;Ln=Kn>>>2;d:{e:{f:{Mn=Kn&3;if(Mn>>>0>3){En=0;break f}En=0;g:{switch(Mn-1|0){case 0:case 1:break f;case 2:break g;default:break e}}Cn=In+Ln|0;if(Cn>>>0>=Fn>>>0){return 0}Dn(q[a>>2]+(In<<2)|0,0,(Kn&252)+4|0);In=Cn;break d}while(1){if((Hn|0)<(Cn|0)?1:(Hn|0)<=(Cn|0)?Nn>>>0>Gn>>>0?0:1:0){return 0}Kn=r[Gn+On|0];Gn=Gn+1|0;if(Gn>>>0<1){Cn=Cn+1|0}q[ki+16>>2]=Gn;q[ki+20>>2]=Cn;Ln=Kn<<(En<<3|6)|Ln;En=En+1|0;if((Mn|0)!=(En|0)){continue}break}}q[q[a>>2]+(In<<2)>>2]=Ln}In=In+1|0;Fn=q[Jn>>2];if(In>>>0>>0){continue}break}In=a+16|0;Jn=q[a>>2];ki=q[a+16>>2];Cn=q[a+20>>2]-ki|0;En=Cn>>2;h:{if(En>>>0<=1048575){Fa(In,1048576-En|0);break h}if((Cn|0)==4194304){break h}q[a+20>>2]=ki+4194304}i:{ki=a+28|0;Cn=q[ki>>2];En=q[a+32>>2]-Cn>>3;if(Fn>>>0>En>>>0){Dh(ki,Fn-En|0);Cn=q[ki>>2];break i}if(Fn>>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ki+20>>2]=Rn;Dn=Qn;if((Dn|0)<1){break a}Sn=Sn+q[ki>>2]|0;q[a+40>>2]=Sn;ki=a;c:{d:{e:{f:{g:{Qn=Dn+ -1|0;Rn=Sn+Qn|0;switch((r[Rn|0]>>>6)-1|0){case 2:break d;case 1:break e;case 0:break f;default:break g}}q[a+44>>2]=Qn;a=r[Rn|0]&63;break c}if((Dn|0)<2){break a}q[a+44>>2]=Dn+ -2;a=(Dn+Sn|0)+ -2|0;a=r[a+1|0]<<8&16128|r[a|0];break c}if((Dn|0)<3){break a}q[a+44>>2]=Dn+ -3;a=(Dn+Sn|0)+ -3|0;a=r[a+1|0]<<8|r[a+2|0]<<16&4128768|r[a|0];break c}q[a+44>>2]=Dn+ -4;a=(Dn+Sn|0)+ -4|0;a=r[a+2|0]<<16|r[a+3|0]<<24&1056964608|r[a+1|0]<<8|r[a|0]}a=a+4194304|0;q[ki+48>>2]=a;Xn=a>>>0<1073741824}T=Tn+16|0;return Xn}function Rh(a){Ij(a);q[a+44>>2]=0;q[a>>2]=11068}function Sh(a){a=a|0;if(q[a+44>>2]){return n[q[q[a>>2]+48>>2]](a)|0}return 0}function Th(a){a=a|0;var ki=0,Yn=0,Zn=0,_n=0,$n=0;q[a>>2]=13300;ki=q[a+20>>2];if(ki){q[a+24>>2]=ki;An(ki)}Zn=q[a+8>>2];if(Zn){ki=Zn;$n=a+12|0;Yn=q[$n>>2];_n=ki;a:{if((ki|0)==(Yn|0)){break a}while(1){Yn=Yn+ -4|0;ki=q[Yn>>2];q[Yn>>2]=0;if(ki){n[q[q[ki>>2]+4>>2]](ki)}if((Yn|0)!=(Zn|0)){continue}break}_n=q[a+8>>2]}ki=_n;q[$n>>2]=Zn;An(ki)}return a|0}function Uh(a,ao){a=a|0;ao=ao|0;a=q[a+48>>2];return n[q[q[a>>2]+20>>2]](a,ao)|0}function Vh(a){a=a|0;var ao=0,bo=0,co=0,eo=0;ao=q[a+32>>2];co=q[ao+16>>2];eo=q[ao+12>>2];bo=q[ao+20>>2];if((eo|0)>(bo|0)?1:(eo|0)>=(bo|0)?t[ao+8>>2]<=co>>>0?0:1:0){eo=r[co+q[ao>>2]|0];co=co+1|0;if(co>>>0<1){bo=bo+1|0}q[ao+16>>2]=co;q[ao+20>>2]=bo;ao=q[a+48>>2];q[a+48>>2]=0;if(ao){n[q[q[ao>>2]+4>>2]](ao)}a:{b:{if(eo>>>0>2){break b}c:{switch(eo-1|0){default:bo=Mm(384);bi(bo);ao=q[a+48>>2];q[a+48>>2]=bo;if(!ao){break a}n[q[q[ao>>2]+4>>2]](ao);break b;case 0:bo=Mm(424);Ei(bo);ao=q[a+48>>2];q[a+48>>2]=bo;if(!ao){break a}n[q[q[ao>>2]+4>>2]](ao);break b;case 1:break c}}bo=Mm(440);Ji(bo);ao=q[a+48>>2];q[a+48>>2]=bo;if(!ao){break a}n[q[q[ao>>2]+4>>2]](ao)}bo=q[a+48>>2];if(bo){break a}return 0}a=n[q[q[bo>>2]+8>>2]](bo,a)|0}else{a=0}return a|0}function Wh(a){a=a|0;a=q[a+48>>2];return n[q[q[a>>2]+24>>2]](a)|0}function Xh(a){a=a|0;a=q[a+48>>2];return n[q[q[a>>2]+28>>2]](a)|0}function Yh(a){a=a|0;var fo=0,go=0,ho=0,io=0,jo=0;q[a>>2]=11164;fo=a+48|0;go=q[fo>>2];q[fo>>2]=0;if(go){n[q[q[go>>2]+4>>2]](go)}q[a>>2]=13300;fo=q[a+20>>2];if(fo){q[a+24>>2]=fo;An(fo)}go=q[a+8>>2];if(go){fo=go;jo=a+12|0;ho=q[jo>>2];io=fo;a:{if((fo|0)==(ho|0)){break a}while(1){ho=ho+ -4|0;fo=q[ho>>2];q[ho>>2]=0;if(fo){n[q[q[fo>>2]+4>>2]](fo)}if((go|0)!=(ho|0)){continue}break}io=q[a+8>>2]}fo=io;q[jo>>2]=go;An(fo)}return a|0}function Zh(a){a=a|0;var ko=0,lo=0,mo=0,no=0,oo=0;q[a>>2]=11164;ko=a+48|0;lo=q[ko>>2];q[ko>>2]=0;if(lo){n[q[q[lo>>2]+4>>2]](lo)}q[a>>2]=13300;ko=q[a+20>>2];if(ko){q[a+24>>2]=ko;An(ko)}lo=q[a+8>>2];if(lo){ko=lo;oo=a+12|0;mo=q[oo>>2];no=ko;a:{if((ko|0)==(mo|0)){break a}while(1){mo=mo+ -4|0;ko=q[mo>>2];q[mo>>2]=0;if(ko){n[q[q[ko>>2]+4>>2]](ko)}if((lo|0)!=(mo|0)){continue}break}no=q[a+8>>2]}ko=no;q[oo>>2]=lo;An(ko)}An(a)}function _h(a){a=a|0;a=q[a+48>>2];return n[q[q[a>>2]+36>>2]](a)|0}function $h(a,po){a=a|0;po=po|0;a=q[a+48>>2];return n[q[q[a>>2]+12>>2]](a,po)|0}function ai(a,po){a=a|0;po=po|0;a=q[a+48>>2];return n[q[q[a>>2]+16>>2]](a,po)|0}function bi(a){q[a>>2]=11272;Dn(a+4|0,0,80);q[a+96>>2]=0;q[a+100>>2]=0;q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+104>>2]=0;q[a+108>>2]=0;q[a+112>>2]=0;q[a+116>>2]=0;q[a+120>>2]=0;q[a+124>>2]=0;q[a+128>>2]=0;q[a+132>>2]=0;q[a+136>>2]=0;q[a+140>>2]=0;q[a+144>>2]=0;q[a+148>>2]=0;q[a+156>>2]=0;q[a+160>>2]=0;q[a+152>>2]=1065353216;q[a+164>>2]=0;q[a+168>>2]=0;q[a+172>>2]=0;q[a+176>>2]=0;q[a+180>>2]=0;q[a+184>>2]=0;q[a+188>>2]=0;q[a+192>>2]=0;q[a+196>>2]=0;q[a+200>>2]=0;q[a+204>>2]=0;q[a+208>>2]=0;q[a+212>>2]=-1;q[a+216>>2]=0;q[a+220>>2]=0;q[a+224>>2]=0;ci(a+232|0)}function ci(a){Yj(a);Yj(a+40|0);ah(a+80|0);Yj(a+96|0);q[a+144>>2]=0;q[a+136>>2]=0;q[a+140>>2]=0}function di(a,po){a=a|0;po=po|0;q[a+4>>2]=po;return 1}function ei(a,po){a=a|0;po=po|0;var qo=0,ro=0,so=0,to=0,uo=0;qo=q[a+216>>2];to=a+220|0;if((qo|0)!=q[to>>2]){while(1){a:{qo=q[w(so,144)+qo>>2];if((qo|0)<0){break a}uo=q[a+4>>2];ro=q[uo+8>>2];if((qo|0)>=q[uo+12>>2]-ro>>2){break a}qo=q[ro+(qo<<2)>>2];if((n[q[q[qo>>2]+24>>2]](qo)|0)<1){break a}ro=0;while(1){if((n[q[q[qo>>2]+20>>2]](qo,ro)|0)!=(po|0)){ro=ro+1|0;if((ro|0)<(n[q[q[qo>>2]+24>>2]](qo)|0)){continue}break a}break}a=q[a+216>>2]+w(so,144)|0;return(r[a+100|0]?a+4|0:0)|0}so=so+1|0;qo=q[a+216>>2];if(so>>>0<(q[to>>2]-qo|0)/144>>>0){continue}break}}return 0}function fi(a,po){a=a|0;po=po|0;var vo=0,wo=0,xo=0,yo=0,zo=0;vo=q[a+216>>2];yo=a+220|0;if((vo|0)!=q[yo>>2]){while(1){a:{vo=q[w(xo,144)+vo>>2];if((vo|0)<0){break a}zo=q[a+4>>2];wo=q[zo+8>>2];if((vo|0)>=q[zo+12>>2]-wo>>2){break a}vo=q[wo+(vo<<2)>>2];if((n[q[q[vo>>2]+24>>2]](vo)|0)<1){break a}wo=0;while(1){if((n[q[q[vo>>2]+20>>2]](vo,wo)|0)!=(po|0)){wo=wo+1|0;if((wo|0)<(n[q[q[vo>>2]+24>>2]](vo)|0)){continue}break a}break}return(q[a+216>>2]+w(xo,144)|0)+104|0}xo=xo+1|0;vo=q[a+216>>2];if(xo>>>0<(q[yo>>2]-vo|0)/144>>>0){continue}break}}return a+184|0}function gi(a,po){a=a|0;po=po|0;var Ao=0,Bo=0,Co=0,Do=0,Eo=0,Fo=0,Go=0,Ho=0,Io=0,Jo=0,Ko=0,Lo=0,Mo=0,No=0,Oo=0;Do=T-80|0;T=Do;a:{b:{Mo=q[a+4>>2];Ao=q[Mo+32>>2];Io=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>>0)/3|0,Qo+63|0);Vo=q[Qo+4>>2];Yo=q[Vo+28>>2];Vo=q[Vo+24>>2];o[Qo+63|0]=0;bb(Qo+36|0,Yo-Vo>>2,Qo+63|0);q[Qo+20>>2]=Ro;q[$o>>2]=So;So=Qo+12|0;q[So>>2]=Po;q[Qo+8>>2]=po;q[Zo>>2]=Ro;po=q[So+4>>2];q[Xo>>2]=q[So>>2];q[Xo+4>>2]=po;po=q[Qo+8>>2];q[To>>2]=q[Qo+4>>2];q[To+4>>2]=po;a:{b:{Po=Ro;po=q[Qo+28>>2];if(po){So=Ro+32|0;c:{if(po>>>0<=q[Ro+40>>2]<<5>>>0){To=po+ -1>>>5;po=q[So>>2];break c}So=q[So>>2];if(So){An(So);q[Ro+40>>2]=0;q[Ro+32>>2]=0;q[Ro+36>>2]=0;po=q[Qo+28>>2]}if((po|0)<=-1){break b}To=po+ -1>>>5;So=To+1|0;po=Mm(So<<2);q[Ro+40>>2]=So;q[Ro+36>>2]=0;q[Ro+32>>2]=po}En(po,q[Qo+24>>2],(To<<2)+4|0);po=q[Qo+28>>2]}else{po=0}q[Po+36>>2]=po;Xo=Ro;po=q[Wo>>2];if(po){d:{if(po>>>0<=q[Ro+52>>2]<<5>>>0){Po=po+ -1>>>5;po=q[Uo>>2];break d}Po=q[Uo>>2];if(Po){An(Po);q[Ro+52>>2]=0;q[Ro+44>>2]=0;q[Ro+48>>2]=0;po=q[Qo+40>>2]}if((po|0)<=-1){break a}Po=po+ -1>>>5;To=Po+1|0;po=Mm(To<<2);q[Ro+52>>2]=To;q[Ro+48>>2]=0;q[Ro+44>>2]=po}En(po,q[Qo+36>>2],(Po<<2)+4|0);po=q[Qo+40>>2]}else{po=0}q[Xo+48>>2]=po;vd(_o,q[Qo+48>>2],q[Qo+52>>2]);q[a>>2]=Ro;q[Qo>>2]=12756;a=q[Qo+48>>2];if(a){q[Qo+52>>2]=a;An(a)}q[Qo>>2]=12572;a=q[Qo+36>>2];if(a){An(a)}a=q[Qo+24>>2];if(a){An(a)}T=Qo- -64|0;return}bn();F()}bn();F()}function ii(a,po,Po){var ap=0,bp=0,cp=0,dp=0,ep=0,fp=0,gp=0;ap=T-112|0;T=ap;gp=q[q[po+4>>2]+44>>2];bp=Mm(120);q[bp>>2]=12124;q[bp+116>>2]=0;q[bp+112>>2]=Po;q[bp+108>>2]=gp;q[bp+12>>2]=0;q[bp+16>>2]=0;q[bp+4>>2]=0;q[bp+20>>2]=0;q[bp+24>>2]=0;q[bp+28>>2]=0;q[bp+32>>2]=0;q[bp+36>>2]=0;q[bp+40>>2]=0;q[bp+44>>2]=0;q[bp+48>>2]=0;q[bp+52>>2]=0;q[bp+56>>2]=0;q[bp+60>>2]=0;q[bp+8>>2]=12336;ep=bp- -64|0;q[ep>>2]=0;q[ep+4>>2]=0;q[bp+72>>2]=0;q[bp+76>>2]=0;q[bp+80>>2]=0;q[bp+84>>2]=0;q[bp+88>>2]=0;q[bp+104>>2]=0;q[bp+96>>2]=0;q[bp+100>>2]=0;po=q[po+8>>2];q[ap+48>>2]=0;q[ap+52>>2]=0;q[ap+40>>2]=0;q[ap+44>>2]=0;ep=ap+24|0;cp=ep;q[cp>>2]=0;q[cp+4>>2]=0;cp=ap- -64|0;q[cp>>2]=0;q[cp+4>>2]=0;q[ap+72>>2]=0;q[ap+76>>2]=0;cp=ap+80|0;q[cp>>2]=0;q[cp+4>>2]=0;q[ap+88>>2]=0;q[ap+104>>2]=0;q[ap+32>>2]=0;q[ap+36>>2]=0;q[ap+16>>2]=0;q[ap+20>>2]=0;q[ap+56>>2]=0;q[ap+60>>2]=0;q[ap+8>>2]=12336;q[ap+96>>2]=0;q[ap+100>>2]=0;q[ap+12>>2]=po;dp=q[po>>2];fp=q[po+4>>2];o[ap+111|0]=0;bb(ap+32|0,(fp-dp>>2>>>0)/3|0,ap+111|0);dp=q[ap+12>>2];fp=q[dp+28>>2];dp=q[dp+24>>2];o[ap+111|0]=0;bb(ap+44|0,fp-dp>>2,ap+111|0);q[ap+28>>2]=bp;q[ep>>2]=gp;q[ap+20>>2]=Po;q[ap+16>>2]=po;ki(bp,ap+8|0);q[a>>2]=bp;q[ap+8>>2]=12336;a=q[ap+96>>2];if(a){q[ap+100>>2]=a;An(a)}a=q[cp>>2];if(a){q[ap+84>>2]=a;An(a)}a=q[ap+68>>2];if(a){q[ap+72>>2]=a;An(a)}a=q[ap+56>>2];if(a){q[ap+60>>2]=a;An(a)}q[ap+8>>2]=12572;a=q[ap+44>>2];if(a){An(a)}a=q[ap+32>>2];if(a){An(a)}T=ap+112|0}function ji(a,po){var Po=0,hp=0,ip=0,jp=0,kp=0,lp=0,mp=0,np=0,op=0;hp=q[a+8>>2];ip=a+4|0;Po=q[ip>>2];if(hp-Po>>2>>>0>=po>>>0){a=po<<2;np=ip,op=Dn(Po,0,a)+a|0,q[np>>2]=op;return}a:{ip=q[a>>2];jp=Po-ip>>2;kp=jp+po|0;if(kp>>>0<1073741824){jp=jp<<2;hp=hp-ip|0;mp=hp>>1;hp=hp>>2>>>0<536870911?mp>>>0>>0?kp:mp:1073741823;if(hp){if(hp>>>0>=1073741824){break a}lp=Mm(hp<<2)}jp=jp+lp|0;Dn(jp,0,po<<2);po=(kp<<2)+lp|0;kp=(hp<<2)+lp|0;if((Po|0)!=(ip|0)){while(1){Po=Po+ -4|0;hp=q[Po>>2];q[Po>>2]=0;jp=jp+ -4|0;q[jp>>2]=hp;if((Po|0)!=(ip|0)){continue}break}ip=q[a>>2];Po=q[a+4>>2]}q[a>>2]=jp;q[a+8>>2]=kp;q[a+4>>2]=po;if((Po|0)!=(ip|0)){while(1){Po=Po+ -4|0;a=q[Po>>2];q[Po>>2]=0;if(a){n[q[q[a>>2]+4>>2]](a)}if((Po|0)!=(ip|0)){continue}break}}if(ip){An(ip)}return}bn();F()}ab(12024);F()}function ki(a,po){var pp=0;pp=q[po+8>>2];q[a+12>>2]=q[po+4>>2];q[a+16>>2]=pp;q[a+28>>2]=q[po+20>>2];pp=q[po+16>>2];q[a+20>>2]=q[po+12>>2];q[a+24>>2]=pp;$i(a+32|0,po+24|0);$i(a+44|0,po+36|0);if((a+8|0)==(po|0)){q[a+92>>2]=q[po+84>>2];return}vd(a+56|0,q[po+48>>2],q[po+52>>2]);vd(a+68|0,q[po+60>>2],q[po- -64>>2]);vd(a+80|0,q[po+72>>2],q[po+76>>2]);q[a+92>>2]=q[po+84>>2];hd(a+96|0,q[po+88>>2],q[po+92>>2])}function li(a,po,qp){a=a|0;po=po|0;qp=qp|0;var rp=0,sp=0;rp=T-16|0;T=rp;q[a+4>>2]=po;po=q[po+64>>2];sp=q[po+4>>2];po=q[po>>2];o[rp+15|0]=0;bb(a+24|0,(sp-po>>2>>>0)/3|0,rp+15|0);po=q[a+4>>2];sp=q[po+56>>2];po=q[po+52>>2];o[rp+14|0]=0;bb(a+36|0,sp-po>>2,rp+14|0);po=q[qp+12>>2];q[a+16>>2]=q[qp+8>>2];q[a+20>>2]=po;po=q[qp+4>>2];q[a+8>>2]=q[qp>>2];q[a+12>>2]=po;T=rp+16|0}function mi(a){a=a|0;var po=0;q[a>>2]=11760;po=q[a+48>>2];if(po){q[a+52>>2]=po;An(po)}q[a>>2]=12012;po=q[a+36>>2];if(po){An(po)}po=q[a+24>>2];if(po){An(po)}return a|0}function ni(a){a=a|0;var qp=0,tp=0,up=0,vp=0,wp=0,xp=0,yp=0,zp=0,Ap=0,Bp=0,Cp=0,Dp=0,Ep=0,Fp=0,Gp=0;zp=T+ -64|0;T=zp;q[a+132>>2]=0;if(q[a+148>>2]){up=a+144|0;tp=q[up>>2];if(tp){while(1){qp=q[tp>>2];An(tp);tp=qp;if(qp){continue}break}}q[up>>2]=0;qp=q[a+140>>2];if(qp){up=a+136|0;tp=0;while(1){q[q[up>>2]+(tp<<2)>>2]=0;tp=tp+1|0;if((qp|0)!=(tp|0)){continue}break}}q[a+148>>2]=0}a:{b:{c:{d:{e:{f:{tp=q[a+4>>2];up=r[tp+36|0];qp=up<<8|r[tp+37|0];g:{if(qp>>>0>513){break g}xp=q[tp+32>>2];if(qp>>>0<=511){wp=q[xp+12>>2];qp=q[xp+20>>2];yp=q[xp+16>>2];vp=yp+4|0;if(vp>>>0<4){qp=qp+1|0}Ap=vp;vp=qp;if((wp|0)<(qp|0)?1:(wp|0)<=(qp|0)?t[xp+8>>2]>=Ap>>>0?0:1:0){break f}qp=yp+q[xp>>2]|0;qp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp>>2]=qp;q[xp+16>>2]=Ap;q[xp+20>>2]=vp;q[a+132>>2]=qp;break g}if(!oi(1,zp,xp)){break f}tp=q[a+4>>2];up=r[tp+36|0];q[a+132>>2]=q[zp>>2]}tp=q[tp+32>>2];h:{i:{j:{if((up&255)>>>0<=1){up=0;xp=q[tp+12>>2];qp=q[tp+20>>2];wp=q[tp+16>>2];vp=wp+4|0;if(vp>>>0<4){qp=qp+1|0}yp=vp;vp=qp;if((xp|0)<(qp|0)?1:(xp|0)<=(qp|0)?t[tp+8>>2]>=yp>>>0?0:1:0){break a}qp=wp+q[tp>>2]|0;qp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp+60>>2]=qp;q[tp+16>>2]=yp;q[tp+20>>2]=vp;q[a+156>>2]=qp;Dp=a+156|0;break j}up=0;if(!oi(1,zp+60|0,tp)){break a}qp=q[a+4>>2];tp=q[qp+32>>2];qp=r[qp+36|0];q[a+156>>2]=q[zp+60>>2];Dp=a+156|0;if(qp>>>0>1){break i}}xp=q[tp+12>>2];qp=q[tp+20>>2];wp=q[tp+16>>2];vp=wp+4|0;if(vp>>>0<4){qp=qp+1|0}Ap=vp;vp=qp;if((xp|0)<(qp|0)?1:(xp|0)<=(qp|0)?t[tp+8>>2]>=Ap>>>0?0:1:0){break a}qp=wp+q[tp>>2]|0;yp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp+56>>2]=yp;q[tp+16>>2]=Ap;q[tp+20>>2]=vp;break h}if(!oi(1,zp+56|0,tp)){break a}yp=q[zp+56>>2]}if(yp>>>0>1431655765|t[Dp>>2]>w(yp,3)>>>0){break a}Bp=q[a+4>>2];vp=q[Bp+32>>2];Fp=q[vp+8>>2];Cp=q[vp+16>>2];xp=q[vp+12>>2];qp=xp;tp=q[vp+20>>2];if((qp|0)<(tp|0)?1:(qp|0)<=(tp|0)?Fp>>>0>Cp>>>0?0:1:0){break a}Gp=q[vp>>2];Ap=r[Gp+Cp|0];qp=tp;Ep=Cp+1|0;if(Ep>>>0<1){qp=qp+1|0}q[vp+16>>2]=Ep;q[vp+20>>2]=qp;k:{if(r[Bp+36|0]<=1){qp=tp;tp=Cp+5|0;if(tp>>>0<5){qp=qp+1|0}wp=tp;tp=qp;if((xp|0)<(qp|0)?1:(xp|0)<=(qp|0)?Fp>>>0>=wp>>>0?0:1:0){break a}qp=Ep+Gp|0;xp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp+52>>2]=xp;q[vp+16>>2]=wp;q[vp+20>>2]=tp;break k}if(!oi(1,zp+52|0,vp)){break a}xp=q[zp+52>>2]}if(yp>>>0>>0|yp>>>0>((xp>>>0)/3|0)+xp>>>0){break a}qp=q[a+4>>2];vp=q[qp+32>>2];l:{if(r[qp+36|0]<=1){wp=q[vp+12>>2];qp=q[vp+20>>2];Cp=q[vp+16>>2];tp=Cp+4|0;if(tp>>>0<4){qp=qp+1|0}Bp=tp;tp=qp;if((wp|0)<(qp|0)?1:(wp|0)<=(qp|0)?t[vp+8>>2]>=Bp>>>0?0:1:0){break a}qp=Cp+q[vp>>2]|0;wp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp+48>>2]=wp;q[vp+16>>2]=Bp;q[vp+20>>2]=tp;break l}if(!oi(1,zp+48|0,vp)){break a}wp=q[zp+48>>2]}if(wp>>>0>xp>>>0){break a}q[a+28>>2]=q[a+24>>2];tp=Mm(88);jk(tp);qp=q[a+8>>2];q[a+8>>2]=tp;vp=a+8|0;if(qp){wa(vp,qp);if(!q[vp>>2]){break a}}qp=q[a+160>>2];q[a+164>>2]=qp;m:{if(q[a+168>>2]-qp>>2>>>0>=yp>>>0){break m}if(yp>>>0>=1073741824){break e}up=yp<<2;tp=Mm(up);q[a+164>>2]=tp;q[a+160>>2]=tp;q[a+168>>2]=tp+up;if(!qp){break m}An(qp)}qp=q[a+172>>2];q[a+176>>2]=qp;n:{if(q[a+180>>2]-qp>>2>>>0>=yp>>>0){break n}if(yp>>>0>=1073741824){break d}up=yp<<2;tp=Mm(up);q[a+176>>2]=tp;q[a+172>>2]=tp;q[a+180>>2]=tp+up;if(!qp){break n}An(qp)}q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+40>>2]=q[a+36>>2];q[a- -64>>2]=0;q[a+52>>2]=q[a+48>>2];q[a+76>>2]=q[a+72>>2];Cp=a+216|0;tp=q[a+220>>2];up=q[a+216>>2];if((tp|0)==(up|0)){break c}while(1){qp=q[tp+ -12>>2];if(qp){q[tp+ -8>>2]=qp;An(qp)}qp=q[tp+ -28>>2];if(qp){q[tp+ -24>>2]=qp;An(qp)}qp=tp+ -144|0;Bp=q[tp+ -40>>2];if(Bp){q[tp+ -36>>2]=Bp;An(Bp)}pi(tp+ -140|0);tp=qp;if((up|0)!=(qp|0)){continue}break}qp=q[Cp>>2];break b}up=0;break a}ab(12024);F()}ab(12024);F()}qp=up}q[a+220>>2]=up;tp=(up-qp|0)/144|0;o:{if(tp>>>0>>0){qi(Cp,Ap-tp|0);break o}if(tp>>>0<=Ap>>>0){break o}tp=qp+w(Ap,144)|0;if((tp|0)!=(up|0)){while(1){qp=q[up+ -12>>2];if(qp){q[up+ -8>>2]=qp;An(qp)}qp=q[up+ -28>>2];if(qp){q[up+ -24>>2]=qp;An(qp)}qp=up+ -144|0;Bp=q[up+ -40>>2];if(Bp){q[up+ -36>>2]=Bp;An(Bp)}pi(up+ -140|0);up=qp;if((qp|0)!=(tp|0)){continue}break}}q[a+220>>2]=tp}up=0;if(!tk(q[vp>>2],yp,q[Dp>>2]+wp|0)){break a}qp=q[a+156>>2];o[zp|0]=1;bb(a+120|0,qp+wp|0,zp);tp=q[a+4>>2];qp=s[tp+36>>1];qp=(qp<<24|qp<<8&16711680)>>>16;p:{if(qp>>>0<=513){wp=q[tp+32>>2];q:{if(qp>>>0<=511){yp=q[wp+12>>2];qp=q[wp+20>>2];Dp=q[wp+16>>2];tp=Dp+4|0;if(tp>>>0<4){qp=qp+1|0}Bp=tp;tp=qp;if((yp|0)<(qp|0)?1:(yp|0)<=(qp|0)?t[wp+8>>2]>=Bp>>>0?0:1:0){break a}qp=Dp+q[wp>>2]|0;yp=r[qp|0]|r[qp+1|0]<<8|(r[qp+2|0]<<16|r[qp+3|0]<<24);q[zp+44>>2]=yp;q[wp+16>>2]=Bp;q[wp+20>>2]=tp;break q}if(!oi(1,zp+44|0,wp)){break a}yp=q[zp+44>>2]}if(!yp){break a}qp=q[q[a+4>>2]+32>>2];tp=q[qp+8>>2];wp=q[qp+16>>2];qp=q[qp+12>>2]-(q[qp+20>>2]+(tp>>>0>>0)|0)|0;if((qp|0)<0?1:(qp|0)<=0?tp-wp>>>0>=yp>>>0?0:1:0){break a}wp=Yj(zp);tp=q[q[a+4>>2]+32>>2];qp=q[tp+16>>2];Dp=q[tp+8>>2];Zj(wp,(qp+q[tp>>2]|0)+yp|0,(Dp-qp|0)-yp|0,s[tp+38>>1]);tp=ri(a,wp);if((tp|0)==-1){break a}qp=tp;wp=qp>>31;break p}qp=-1;wp=-1;if((ri(a,q[tp+32>>2])|0)==-1){break a}}q[a+376>>2]=a;Dp=a+232|0;tp=q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2];Bp=q[tp>>2]+q[tp+16>>2]|0;yp=q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2];tp=q[yp+8>>2];up=q[yp+16>>2];Zj(Dp,Bp,tp-up|0,s[q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2]+38>>1]);q[a+372>>2]=Ap;up=0;tp=Yj(zp);r:{if(!si(Dp,tp)){break r}yp=ti(a,xp);if((yp|0)==-1){break r}xp=q[q[a+4>>2]+32>>2];up=q[tp+16>>2];Ap=up+q[tp>>2]|0;tp=q[tp+8>>2];Zj(xp,Ap,tp-up|0,s[xp+38>>1]);tp=q[a+4>>2];up=s[tp+36>>1];xp=(up<<24|up<<8&16711680)>>>16;if(xp>>>0<=513){up=q[tp+32>>2];Ap=up;Bp=up;tp=wp+q[up+20>>2]|0;up=qp+q[up+16>>2]|0;if(up>>>0>>0){tp=tp+1|0}q[Bp+16>>2]=up;q[Ap+20>>2]=tp}s:{if(q[a+220>>2]==q[a+216>>2]){break s}tp=q[vp>>2];qp=q[tp+4>>2];tp=q[tp>>2];t:{if(xp>>>0>=513){if((qp|0)==(tp|0)){break s}tp=0;break t}if((qp|0)==(tp|0)){break s}tp=0;while(1){if(ui(a,tp)){tp=tp+3|0;qp=q[vp>>2];if(tp>>>0>2]-q[qp>>2]>>2>>>0){continue}break s}break}up=0;break r}while(1){if(vi(a,tp)){tp=tp+3|0;qp=q[vp>>2];if(tp>>>0>2]-q[qp>>2]>>2>>>0){continue}break s}break}up=0;break r}if(r[a+308|0]){ak(a+272|0)}if(s[a+270>>1]<=513){ak(a+328|0)}tp=q[a+216>>2];wp=a+220|0;if((tp|0)!=q[wp>>2]){xp=0;while(1){qp=w(xp,144);Ek((qp+tp|0)+4|0,q[vp>>2]);up=q[Cp>>2];Ap=qp+up|0;tp=q[Ap+132>>2];Ap=q[Ap+136>>2];if((tp|0)!=(Ap|0)){while(1){Gk((qp+up|0)+4|0,q[tp>>2]);up=q[Cp>>2];tp=tp+4|0;if((Ap|0)!=(tp|0)){continue}break}}Fk((qp+up|0)+4|0);xp=xp+1|0;tp=q[a+216>>2];if(xp>>>0<(q[wp>>2]-tp|0)/144>>>0){continue}break}}qp=q[a+8>>2];wi(a+184|0,q[qp+28>>2]-q[qp+24>>2]>>2);up=q[a+216>>2];if((up|0)!=q[wp>>2]){tp=0;xp=a+220|0;while(1){qp=w(tp,144)+up|0;up=q[qp+60>>2]-q[qp+56>>2]>>2;Ap=qp+104|0;qp=q[vp>>2];qp=q[qp+28>>2]-q[qp+24>>2]>>2;wi(Ap,(up|0)<(qp|0)?qp:up);tp=tp+1|0;up=q[a+216>>2];if(tp>>>0<(q[xp>>2]-up|0)/144>>>0){continue}break}}up=xi(a,yp)}}T=zp- -64|0;return up|0}function oi(a,Hp,Ip){var Jp=0,Kp=0,Lp=0,Mp=0;a:{if(a>>>0>5){break a}Lp=q[Ip+16>>2];Jp=q[Ip+12>>2];Kp=q[Ip+20>>2];if((Jp|0)<(Kp|0)?1:(Jp|0)<=(Kp|0)?t[Ip+8>>2]>Lp>>>0?0:1:0){break a}Jp=r[Lp+q[Ip>>2]|0];Lp=Lp+1|0;if(Lp>>>0<1){Kp=Kp+1|0}q[Ip+16>>2]=Lp;q[Ip+20>>2]=Kp;Kp=Hp;if(Jp&128){if(!oi(a+1|0,Hp,Ip)){break a}a=q[Hp>>2]<<7;q[Hp>>2]=a;Jp=a|Jp&127}q[Kp>>2]=Jp;Mp=1}return Mp}function pi(a){var Hp=0;Hp=q[a+84>>2];if(Hp){q[a+88>>2]=Hp;An(Hp)}Hp=q[a+72>>2];if(Hp){q[a+76>>2]=Hp;An(Hp)}Hp=q[a+52>>2];if(Hp){q[a+56>>2]=Hp;An(Hp)}Hp=q[a+40>>2];if(Hp){q[a+44>>2]=Hp;An(Hp)}Hp=q[a+28>>2];if(Hp){q[a+32>>2]=Hp;An(Hp)}Hp=q[a+12>>2];if(Hp){An(Hp)}a=q[a>>2];if(a){An(a)}}function qi(a,Ip){var Np=0,Op=0,Pp=0,Qp=0,Rp=0,Sp=0;Op=T-32|0;T=Op;a:{b:{Pp=q[a+8>>2];Qp=a+4|0;Np=q[Qp>>2];c:{if((Pp-Np|0)/144>>>0>=Ip>>>0){while(1){q[Np>>2]=-1;Dk(Np+4|0);q[Np+104>>2]=0;q[Np+108>>2]=0;o[Np+100|0]=1;q[Np+112>>2]=0;q[Np+116>>2]=0;q[Np+120>>2]=0;q[Np+124>>2]=0;q[Np+128>>2]=0;q[Np+132>>2]=0;q[Np+136>>2]=0;q[Np+140>>2]=0;Np=q[Qp>>2]+144|0;q[Qp>>2]=Np;Ip=Ip+ -1|0;if(Ip){continue}break c}}Rp=q[a>>2];Sp=(Np-Rp|0)/144|0;Np=Sp+Ip|0;if(Np>>>0>=29826162){break b}q[Op+24>>2]=a+8;Qp=0;q[Op+20>>2]=0;Pp=(Pp-Rp|0)/144|0;Rp=Pp<<1;Pp=Pp>>>0<14913080?Rp>>>0>>0?Np:Rp:29826161;if(Pp){if(Pp>>>0>=29826162){break a}Qp=Mm(w(Pp,144))}q[Op+8>>2]=Qp;Np=w(Sp,144)+Qp|0;q[Op+16>>2]=Np;q[Op+20>>2]=w(Pp,144)+Qp;q[Op+12>>2]=Np;while(1){q[Np>>2]=-1;Dk(Np+4|0);q[Np+104>>2]=0;q[Np+108>>2]=0;o[Np+100|0]=1;q[Np+112>>2]=0;q[Np+116>>2]=0;q[Np+120>>2]=0;q[Np+124>>2]=0;q[Np+128>>2]=0;q[Np+132>>2]=0;q[Np+136>>2]=0;q[Np+140>>2]=0;Np=q[Op+16>>2]+144|0;q[Op+16>>2]=Np;Ip=Ip+ -1|0;if(Ip){continue}break}Ip=q[a+4>>2];Pp=q[a>>2];d:{if((Ip|0)==(Pp|0)){Qp=q[Op+12>>2];break d}Qp=q[Op+12>>2];while(1){Ip=Ip+ -144|0;Qp=vj(Qp+ -144|0,Ip);if((Ip|0)!=(Pp|0)){continue}break}q[Op+12>>2]=Qp;Ip=q[a+4>>2];Pp=q[a>>2]}q[a>>2]=Qp;q[Op+12>>2]=Pp;q[a+4>>2]=Np;q[Op+16>>2]=Ip;a=a+8|0;Ip=q[a>>2];q[a>>2]=q[Op+20>>2];q[Op+8>>2]=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8>>2];if((oq|0)==(iq|0)&hq>>>0<=lq>>>0|oq>>>0>>0){break d}}hq=0;break a}kq=mq+oq|0;jq=hq+jq|0;if(jq>>>0>>0){kq=kq+1|0}q[a+16>>2]=jq;q[a+20>>2]=kq;break c}hq=0;if(!bh(a+80|0,a)){break a}}hq=0;if(!Ai(a)){break a}hq=q[a+4>>2];q[Ip>>2]=q[a>>2];q[Ip+4>>2]=hq;hq=q[a+36>>2];q[Ip+32>>2]=q[a+32>>2];q[Ip+36>>2]=hq;hq=q[a+28>>2];q[Ip+24>>2]=q[a+24>>2];q[Ip+28>>2]=hq;hq=q[a+20>>2];q[Ip+16>>2]=q[a+16>>2];q[Ip+20>>2]=hq;hq=q[a+12>>2];q[Ip+8>>2]=q[a+8>>2];q[Ip+12>>2]=hq;hq=1}T=nq+16|0;return hq}function ti(a,Ip){var pq=0,qq=0,rq=0,sq=0,tq=0,uq=0,vq=0,wq=0,xq=0,yq=0,zq=0,Aq=0,Bq=0,Cq=0,Dq=0,Eq=0,Fq=0,Gq=0,Hq=0,Iq=0,Jq=0,Kq=0,Lq=0;sq=T-96|0;T=sq;q[sq+72>>2]=0;q[sq+64>>2]=0;q[sq+68>>2]=0;q[sq+48>>2]=0;q[sq+52>>2]=0;q[sq+40>>2]=0;q[sq+44>>2]=0;q[sq+56>>2]=1065353216;q[sq+32>>2]=0;q[sq+24>>2]=0;q[sq+28>>2]=0;Jq=q[a+124>>2];a:{b:{c:{d:{if((Ip|0)>=1){Iq=a+8|0;Fq=q[a+216>>2]!=q[a+220>>2];Gq=a+40|0;while(1){e:{f:{g:{h:{i:{j:{k:{if(!r[a+308|0]){break k}l:{m:{wq=q[a+296>>2];yq=q[a+304>>2];pq=wq+(yq>>>3)|0;uq=q[a+300>>2];if(pq>>>0>=uq>>>0){break m}pq=r[pq|0];qq=yq+1|0;q[a+304>>2]=qq;if(!(pq>>>(yq&7)&1)){break m}pq=qq>>>3;rq=wq+pq|0;n:{if(rq>>>0>=uq>>>0){rq=qq;qq=0;break n}vq=r[rq|0];rq=yq+2|0;q[a+304>>2]=rq;pq=rq>>>3;qq=vq>>>(qq&7)&1}pq=pq+wq|0;if(pq>>>0>>0){pq=r[pq|0];q[a+304>>2]=rq+1;pq=pq>>>(rq&7)<<1&2}else{pq=0}pq=(qq|pq)<<1|1;switch(pq+ -2|0){case 0:case 2:case 4:break h;case 5:break j;case 1:case 3:break l;default:break k}}qq=q[sq+68>>2];if((qq|0)==q[sq+64>>2]){break d}wq=-1;Aq=q[Iq>>2];uq=q[Aq+24>>2];rq=uq;vq=qq+ -4|0;Dq=q[vq>>2];pq=-1;o:{if((Dq|0)==-1){break o}qq=Dq+1|0;qq=(qq>>>0)%3|0?qq:Dq+ -2|0;pq=-1;if((qq|0)==-1){break o}pq=q[q[Aq>>2]+(qq<<2)>>2]}rq=q[rq+(pq<<2)>>2];if((rq|0)!=-1){qq=rq+1|0;wq=(qq>>>0)%3|0?qq:rq+ -2|0}rq=q[Aq+12>>2];Bq=w(tq,3);qq=Bq+1|0;q[rq+(Dq<<2)>>2]=qq;qq=qq<<2;q[qq+rq>>2]=Dq;zq=Bq+2|0;q[rq+(wq<<2)>>2]=zq;yq=zq<<2;q[yq+rq>>2]=wq;Cq=q[Aq>>2];q[Cq+(Bq<<2)>>2]=pq;rq=qq+Cq|0;xq=-1;p:{if((wq|0)==-1){break p}qq=wq+1|0;qq=(qq>>>0)%3|0?qq:wq+ -2|0;xq=-1;if((qq|0)==-1){break p}xq=q[Cq+(qq<<2)>>2]}q[rq>>2]=xq;q:{r:{if((Dq|0)!=-1){qq=Dq+((Dq>>>0)%3|0?-1:2)|0;if((qq|0)!=-1){break r}}q[yq+Cq>>2]=-1;break q}qq=q[Cq+(qq<<2)>>2];q[yq+Cq>>2]=qq;if((qq|0)==-1){break q}q[uq+(qq<<2)>>2]=zq}rq=q[a+120>>2]+(pq>>>3&536870908)|0;qq=q[rq>>2];Kq=rq,Lq=eo(pq)&qq,q[Kq>>2]=Lq;q[vq>>2]=Bq;break e}rq=q[sq+68>>2];if((rq|0)==q[sq+64>>2]){break d}yq=q[Iq>>2];qq=q[yq+12>>2];zq=w(tq,3);wq=(pq|0)==5;uq=zq+(wq?2:1)|0;pq=uq<<2;Cq=q[rq+ -4>>2];q[qq+pq>>2]=Cq;q[qq+(Cq<<2)>>2]=uq;vq=yq+24|0;rq=yq+28|0;qq=q[rq>>2];s:{if((qq|0)!=q[yq+32>>2]){q[qq>>2]=-1;Aq=qq+4|0;q[rq>>2]=Aq;break s}zi(vq,11312);Aq=q[rq>>2]}rq=-1;qq=q[Iq>>2];yq=q[qq+24>>2];if(q[qq+28>>2]-yq>>2>(Jq|0)){break c}rq=zq+2|0;Bq=q[qq>>2];xq=Bq+pq|0;qq=Aq-q[vq>>2]|0;pq=(qq>>2)+ -1|0;q[xq>>2]=pq;if(qq){q[yq+(pq<<2)>>2]=uq}rq=wq?zq:rq;qq=Bq+(wq+zq<<2)|0;t:{u:{v:{if((Cq|0)!=-1){pq=Cq+((Cq>>>0)%3|0?-1:2)|0;if((pq|0)==-1){break v}pq=q[Bq+(pq<<2)>>2];q[Bq+(rq<<2)>>2]=pq;if((pq|0)==-1){break u}q[yq+(pq<<2)>>2]=rq;break u}q[Bq+(rq<<2)>>2]=-1;rq=-1;break t}q[Bq+(rq<<2)>>2]=-1}pq=Cq+1|0;pq=(pq>>>0)%3|0?pq:Cq+ -2|0;rq=-1;if((pq|0)==-1){break t}rq=q[Bq+(pq<<2)>>2]}q[qq>>2]=rq;q[q[sq+68>>2]+ -4>>2]=zq;break i}rq=-1;pq=q[sq+68>>2];Aq=q[sq+64>>2];if((pq|0)==(Aq|0)){break c}qq=pq+ -4|0;Eq=q[qq>>2];q[sq+68>>2]=qq;zq=q[sq+44>>2];w:{if(!zq){pq=qq;break w}uq=q[sq+40>>2];yq=co(zq)>>>0>1;vq=zq+2147483647&tq;x:{if(!yq){break x}vq=tq;if(tq>>>0>>0){break x}vq=(tq>>>0)%(zq>>>0)|0}uq=q[uq+(vq<<2)>>2];if(!uq){pq=qq;break w}xq=q[uq>>2];if(!xq){pq=qq;break w}uq=zq+ -1|0;y:{while(1){wq=q[xq+4>>2];z:{if((wq|0)!=(tq|0)){A:{if(!yq){wq=wq&uq;break A}if(wq>>>0>>0){break A}wq=(wq>>>0)%(zq>>>0)|0}if((wq|0)==(vq|0)){break z}pq=qq;break w}if(q[xq+8>>2]==(tq|0)){break y}}xq=q[xq>>2];if(xq){continue}break}pq=qq;break w}vq=xq+12|0;if((qq|0)!=q[sq+72>>2]){q[qq>>2]=q[vq>>2];q[sq+68>>2]=pq;break w}zi(sq- -64|0,vq);pq=q[sq+68>>2];Aq=q[sq+64>>2]}if((pq|0)==(Aq|0)){break c}Dq=q[pq+ -4>>2];vq=(Dq|0)==-1;Hq=q[Iq>>2];if(q[q[Hq+12>>2]+(Dq<<2)>>2]!=-1?!vq:0){break c}yq=(Eq|0)==-1;zq=Hq+12|0;uq=q[zq>>2];if(q[uq+(Eq<<2)>>2]!=-1?!yq:0){break c}Cq=w(tq,3);Aq=Cq+2|0;q[uq+(Dq<<2)>>2]=Aq;Bq=Aq<<2;q[Bq+uq>>2]=Dq;qq=Cq+1|0;q[uq+(Eq<<2)>>2]=qq;wq=uq;uq=qq<<2;q[wq+uq>>2]=Eq;if(vq){break g}wq=-1;vq=q[Hq>>2];xq=vq+(Cq<<2)|0;qq=Dq+((Dq>>>0)%3|0?-1:2)|0;if((qq|0)!=-1){wq=q[(qq<<2)+vq>>2]}q[xq>>2]=wq;qq=Dq+1|0;qq=(qq>>>0)%3|0?qq:Dq+ -2|0;if((qq|0)==-1){break f}rq=q[(qq<<2)+vq>>2];break f}q[sq>>2]=w(tq,3);pq=q[Iq>>2];rq=pq+24|0;uq=q[pq+32>>2];qq=pq+28|0;pq=q[qq>>2];B:{if((uq|0)!=(pq|0)){q[pq>>2]=-1;pq=pq+4|0;q[qq>>2]=pq;break B}zi(rq,11312);pq=q[qq>>2]}Aq=q[Iq>>2];wq=q[Aq>>2];qq=q[sq>>2];yq=pq-q[rq>>2]|0;zq=yq>>2;rq=zq+ -1|0;q[wq+(qq<<2)>>2]=rq;qq=qq+1|0;uq=Aq+24|0;vq=Aq+28|0;pq=q[vq>>2];C:{if((pq|0)!=q[Aq+32>>2]){q[pq>>2]=-1;pq=pq+4|0;q[vq>>2]=pq;break C}zi(uq,11312);pq=q[vq>>2];wq=q[Aq>>2]}q[(qq<<2)+wq>>2]=(pq-q[uq>>2]>>2)+ -1;pq=q[sq>>2]+2|0;uq=q[Iq>>2];qq=uq+28|0;vq=q[qq>>2];D:{if((vq|0)!=q[uq+32>>2]){q[vq>>2]=-1;wq=vq+4|0;q[qq>>2]=wq;break D}zi(uq+24|0,11312);wq=q[qq>>2]}q[q[uq>>2]+(pq<<2)>>2]=(wq-q[uq+24>>2]>>2)+ -1;pq=q[Iq>>2];qq=q[pq+24>>2];if(q[pq+28>>2]-qq>>2>(Jq|0)){break d}pq=q[sq>>2];E:{F:{if(!yq){wq=1;q[qq+(zq<<2)>>2]=pq+1;break F}q[qq+(rq<<2)>>2]=pq;wq=0;if((yq|0)==-4){break F}q[qq+(zq<<2)>>2]=q[sq>>2]+1;wq=zq+1|0;if((wq|0)==-1){break E}}q[qq+(wq<<2)>>2]=q[sq>>2]+2}pq=q[sq+68>>2];if((pq|0)!=q[sq+72>>2]){q[pq>>2]=q[sq>>2];q[sq+68>>2]=pq+4;break i}zi(sq- -64|0,sq)}xq=q[Gq>>2];if((xq|0)==q[a+36>>2]){break e}uq=(tq^-1)+Ip|0;while(1){rq=-1;pq=q[xq+ -8>>2];if(pq>>>0>uq>>>0){break c}if((pq|0)!=(uq|0)){break e}qq=r[xq+ -4|0];pq=xq+ -12|0;vq=q[pq>>2];q[Gq>>2]=pq;if((vq|0)<0){break c}rq=q[q[sq+68>>2]+ -4>>2];q[sq+20>>2]=(vq^-1)+Ip;q[sq+88>>2]=sq+20;Bi(sq,sq+40|0,sq+20|0,sq+88|0);vq=q[sq>>2];G:{if(qq&1){pq=-1;if((rq|0)==-1){break G}pq=rq+1|0;pq=(pq>>>0)%3|0?pq:rq+ -2|0;break G}pq=-1;if((rq|0)==-1){break G}pq=rq+ -1|0;if((rq>>>0)%3){break G}pq=rq+2|0}q[vq+12>>2]=pq;xq=q[Gq>>2];if((xq|0)!=q[a+36>>2]){continue}break}break e}F()}wq=-1;vq=q[Hq>>2];q[vq+(Cq<<2)>>2]=-1}q[uq+vq>>2]=rq;H:{I:{J:{if(!yq){qq=Eq+((Eq>>>0)%3|0?-1:2)|0;if((qq|0)==-1){break J}qq=q[(qq<<2)+vq>>2];q[vq+Bq>>2]=qq;if((qq|0)==-1){break I}q[q[Hq+24>>2]+(qq<<2)>>2]=Aq;break I}q[vq+Bq>>2]=-1;xq=-1;rq=-1;break H}q[vq+Bq>>2]=-1}xq=-1;qq=Eq+1|0;qq=(qq>>>0)%3|0?qq:Eq+ -2|0;rq=-1;if((qq|0)==-1){break H}xq=q[(qq<<2)+vq>>2];rq=qq}q[sq>>2]=xq;uq=q[Hq+24>>2];if((wq|0)!=-1){q[uq+(wq<<2)>>2]=q[uq+(xq<<2)>>2]}K:{if((rq|0)==-1){break K}vq=q[Hq>>2];while(1){q[vq+(rq<<2)>>2]=wq;qq=rq+1|0;qq=(qq>>>0)%3|0?qq:rq+ -2|0;if((qq|0)==-1){break K}rq=q[q[zq>>2]+(qq<<2)>>2];if((rq|0)==-1){break K}qq=rq+1|0;rq=(qq>>>0)%3|0?qq:rq+ -2|0;if((rq|0)!=-1){continue}break}}q[uq+(q[sq>>2]<<2)>>2]=-1;L:{if(Fq){break L}qq=q[sq+28>>2];if((qq|0)!=q[sq+32>>2]){q[qq>>2]=q[sq>>2];q[sq+28>>2]=qq+4;break L}zi(sq+24|0,sq);pq=q[sq+68>>2]}q[pq+ -4>>2]=Cq}tq=tq+1|0;if((tq|0)!=(Ip|0)){continue}break}wq=Ip}rq=-1;xq=q[a+8>>2];if(q[xq+28>>2]-q[xq+24>>2]>>2>(Jq|0)){break c}tq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pq>>2];Kq=pq,Lq=eo(tq)&Ip,q[Kq>>2]=Lq;Ip=q[Hq>>2];if((Ip|0)!=q[Jq>>2]){q[Ip>>2]=q[sq>>2];q[Hq>>2]=Ip+4;break M}zi(Dq,sq)}tq=q[sq+68>>2];if((tq|0)!=q[sq+64>>2]){continue}break}xq=q[a+8>>2]}if(((q[xq+4>>2]-q[xq>>2]>>2>>>0)/3|0)!=(wq|0)){break c}rq=q[xq+28>>2]-q[xq+24>>2]>>2;Fq=q[sq+24>>2];uq=q[sq+28>>2];if((Fq|0)==(uq|0)){break b}vq=a+8|0;while(1){zq=q[Fq>>2];wq=q[xq+24>>2];tq=rq+ -1|0;T:{if(q[wq+(tq<<2)>>2]!=-1){pq=rq;break T}wq=q[xq+24>>2];while(1){tq=rq+ -2|0;pq=rq+ -1|0;rq=pq;if(q[(tq<<2)+wq>>2]==-1){continue}break}}if(!(tq>>>0>>0)){q[sq>>2]=xq;Ip=tq<<2;rq=q[Ip+wq>>2];o[sq+12|0]=1;q[sq+8>>2]=rq;q[sq+4>>2]=rq;if((rq|0)!=-1){while(1){q[q[xq>>2]+(rq<<2)>>2]=zq;lg(sq);xq=q[vq>>2];rq=q[sq+8>>2];if((rq|0)!=-1){continue}break}}qq=Ip;Ip=q[xq+24>>2];qq=qq+Ip|0;if((zq|0)!=-1){q[Ip+(zq<<2)>>2]=q[qq>>2]}q[qq>>2]=-1;yq=1<<(zq&31);Ip=q[a+120>>2];rq=Ip+(zq>>>3&536870908)|0;qq=rq;wq=Ip+(tq>>>3&536870908)|0;Ip=1<<(tq&31);tq=yq|q[rq>>2];U:{if(q[wq>>2]&Ip){break U}tq=q[rq>>2]&(yq^-1)}q[qq>>2]=tq;q[wq>>2]=q[wq>>2]&(Ip^-1);pq=pq+ -1|0}rq=pq;Fq=Fq+4|0;if((uq|0)!=(Fq|0)){continue}break}break c}rq=-1}Fq=q[sq+24>>2]}if(Fq){q[sq+28>>2]=Fq;An(Fq)}tq=q[sq+48>>2];if(tq){while(1){a=q[tq>>2];An(tq);tq=a;if(tq){continue}break}}a=q[sq+40>>2];q[sq+40>>2]=0;if(a){An(a)}a=q[sq+64>>2];if(a){q[sq+68>>2]=a;An(a)}T=sq+96|0;return rq}bn();F()}function ui(a,Ip){var Mq=0,Nq=0,Oq=0,Pq=0,Qq=0,Rq=0,Sq=0,Tq=0,Uq=0,Vq=0,Wq=0;Nq=T-32|0;T=Nq;q[Nq+16>>2]=Ip;Mq=-1;a:{if((Ip|0)==-1){q[Nq+20>>2]=-1;break a}Mq=Ip+1|0;q[Nq+20>>2]=(Mq>>>0)%3|0?Mq:Ip+ -2|0;if((Ip>>>0)%3){Mq=Ip+ -1|0;break a}Mq=Ip+2|0}q[Nq+24>>2]=Mq;Rq=a+220|0;Vq=a+8|0;Wq=a+368|0;while(1){b:{if(!((Ip|0)==-1|q[q[q[Vq>>2]+12>>2]+(Ip<<2)>>2]==-1)){Mq=0;if(q[Rq>>2]==q[a+216>>2]){break b}while(1){c:{if(!dh(q[Wq>>2]+(Mq<<4)|0)){break c}Oq=q[a+216>>2];q[Nq+12>>2]=Ip;Oq=Oq+w(Mq,144)|0;Qq=Oq+136|0;Pq=q[Qq>>2];if(Pq>>>0>2]){q[Pq>>2]=Ip;q[Qq>>2]=Pq+4;break c}ya(Oq+132|0,Nq+12|0)}Mq=Mq+1|0;if(Mq>>>0<(q[Rq>>2]-q[a+216>>2]|0)/144>>>0){continue}break}break b}Mq=0;Oq=q[a+216>>2];Pq=q[Rq>>2];if((Oq|0)==(Pq|0)){break b}while(1){q[Nq+12>>2]=Ip;Qq=w(Mq,144)+Oq|0;Uq=Qq+136|0;Sq=q[Uq>>2];d:{if(Sq>>>0>2]){q[Sq>>2]=Ip;q[Uq>>2]=Sq+4;break d}ya(Qq+132|0,Nq+12|0);Pq=q[Rq>>2];Oq=q[a+216>>2]}Mq=Mq+1|0;if(Mq>>>0<(Pq-Oq|0)/144>>>0){continue}break}}Tq=Tq+1|0;if((Tq|0)!=3){Ip=q[(Nq+16|0)+(Tq<<2)>>2];continue}break}T=Nq+32|0;return 1}function vi(a,Ip){var Xq=0,Yq=0,Zq=0,_q=0,$q=0,ar=0,br=0,cr=0,dr=0,er=0,fr=0,gr=0;Yq=T-32|0;T=Yq;q[Yq+16>>2]=Ip;Xq=-1;a:{if((Ip|0)==-1){q[Yq+20>>2]=-1;break a}Xq=Ip+1|0;q[Yq+20>>2]=(Xq>>>0)%3|0?Xq:Ip+ -2|0;if((Ip>>>0)%3){Xq=Ip+ -1|0;break a}Xq=Ip+2|0}q[Yq+24>>2]=Xq;er=(Ip|0)==-1?-1:(Ip>>>0)/3|0;ar=a+220|0;fr=a+8|0;gr=a+368|0;while(1){b:{c:{if((Ip|0)!=-1){Xq=q[q[q[fr>>2]+12>>2]+(Ip<<2)>>2];if((Xq|0)!=-1){break c}}Xq=0;Zq=q[a+216>>2];_q=q[ar>>2];if((Zq|0)==(_q|0)){break b}while(1){q[Yq+12>>2]=Ip;$q=w(Xq,144)+Zq|0;dr=$q+136|0;br=q[dr>>2];d:{if(br>>>0>2]){q[br>>2]=Ip;q[dr>>2]=br+4;break d}ya($q+132|0,Yq+12|0);_q=q[ar>>2];Zq=q[a+216>>2]}Xq=Xq+1|0;if(Xq>>>0<(_q-Zq|0)/144>>>0){continue}break}break b}if((Xq>>>0)/3>>>0>>0){break b}Xq=0;if(q[ar>>2]==q[a+216>>2]){break b}while(1){e:{if(!dh(q[gr>>2]+(Xq<<4)|0)){break e}Zq=q[a+216>>2];q[Yq+12>>2]=Ip;Zq=Zq+w(Xq,144)|0;$q=Zq+136|0;_q=q[$q>>2];if(_q>>>0>2]){q[_q>>2]=Ip;q[$q>>2]=_q+4;break e}ya(Zq+132|0,Yq+12|0)}Xq=Xq+1|0;if(Xq>>>0<(q[ar>>2]-q[a+216>>2]|0)/144>>>0){continue}break}}cr=cr+1|0;if((cr|0)!=3){Ip=q[(Yq+16|0)+(cr<<2)>>2];continue}break}T=Yq+32|0;return 1}function wi(a,Ip){var hr=0,ir=0,jr=0,kr=0,lr=0;ir=q[a+12>>2];hr=q[a+16>>2]-ir>>2;a:{if(hr>>>0>>0){Fa(a+12|0,Ip-hr|0);break a}if(hr>>>0<=Ip>>>0){break a}q[a+16>>2]=ir+(Ip<<2)}b:{hr=q[a>>2];c:{if(q[a+8>>2]-hr>>2>>>0>=Ip>>>0){break c}if(Ip>>>0>=1073741824){break b}kr=a+4|0;ir=q[kr>>2];jr=Ip<<2;Ip=Mm(jr);jr=Ip+jr|0;ir=ir-hr|0;lr=ir+Ip|0;if((ir|0)>=1){Cn(Ip,hr,ir)}q[a>>2]=Ip;q[a+8>>2]=jr;q[kr>>2]=lr;if(!hr){break c}An(hr)}return}ab(12024);F()}function xi(a,Ip){var mr=0,nr=0,or=0,pr=0,qr=0,rr=0,sr=0,tr=0,ur=0,vr=0,wr=0,xr=0,yr=0,zr=0,Ar=0,Br=0;nr=T-48|0;T=nr;mr=q[a+8>>2];or=q[mr>>2];qr=q[mr+4>>2];mr=q[q[a+4>>2]+44>>2];q[nr+40>>2]=0;q[nr+32>>2]=0;q[nr+36>>2]=0;or=(qr-or>>2>>>0)/3|0;pr=q[mr+96>>2];qr=(q[mr+100>>2]-pr|0)/12|0;a:{if(or>>>0>qr>>>0){Ci(mr+96|0,or-qr|0,nr+32|0);break a}if(or>>>0>=qr>>>0){break a}q[mr+100>>2]=pr+w(or,12)}b:{if(q[a+216>>2]==q[a+220>>2]){ur=q[a+4>>2];mr=q[ur+44>>2];or=q[mr+100>>2];sr=q[mr+96>>2];if((or|0)!=(sr|0)){vr=(or-sr|0)/12|0;wr=nr+40|0;mr=0;while(1){q[wr>>2]=0;q[nr+32>>2]=0;q[nr+36>>2]=0;qr=nr;c:{d:{e:{pr=w(mr,3);if((pr|0)==-1){or=-1;q[nr+32>>2]=-1;rr=0;break e}or=q[q[q[a+8>>2]>>2]+(pr<<2)>>2];q[nr+32>>2]=or;rr=pr+1|0;if((rr|0)!=-1){break e}q[nr+36>>2]=-1;pr=0;break d}q[nr+36>>2]=q[q[q[a+8>>2]>>2]+(rr<<2)>>2];pr=pr+2|0;xr=-1;if((pr|0)==-1){break c}}xr=q[q[q[a+8>>2]>>2]+(pr<<2)>>2]}q[qr+40>>2]=xr;qr=sr+w(mr,12)|0;q[qr>>2]=or;q[qr+4>>2]=q[nr+36>>2];q[qr+8>>2]=q[nr+40>>2];mr=mr+1|0;if(mr>>>0>>0){continue}break}}q[q[ur+4>>2]+80>>2]=Ip;mr=1;break b}q[nr+40>>2]=0;q[nr+32>>2]=0;q[nr+36>>2]=0;pr=q[a+8>>2];Ip=q[pr>>2];mr=q[pr+4>>2];q[nr+24>>2]=0;q[nr+16>>2]=0;q[nr+20>>2]=0;f:{g:{h:{Ip=mr-Ip|0;if(Ip){or=Ip>>2;if(or>>>0>=1073741824){break h}mr=Mm(Ip);q[nr+16>>2]=mr;q[nr+24>>2]=mr+(or<<2);Ar=nr,Br=Dn(mr,0,Ip)+Ip|0,q[Ar+20>>2]=Br}if((q[pr+28>>2]-q[pr+24>>2]|0)<1){break g}ur=a+220|0;vr=a+8|0;while(1){or=q[q[pr+24>>2]+(sr<<2)>>2];i:{if((or|0)==-1){break i}j:{if(q[q[a+120>>2]+(sr>>>3&536870908)>>2]>>>(sr&31)&1){break j}Ip=q[ur>>2];wr=q[a+216>>2];if((Ip|0)==(wr|0)){break j}xr=(Ip-wr|0)/144|0;yr=((or>>>0)%3|0?-1:2)+or|0;rr=0;while(1){zr=or<<2;tr=wr+w(rr,144)|0;Ip=q[zr+q[q[tr+68>>2]>>2]>>2];k:{if(!(q[q[tr+16>>2]+(Ip>>>3&536870908)>>2]>>>(Ip&31)&1)){break k}Ip=or;mr=-1;l:{if((yr|0)==-1){break l}qr=q[q[pr+12>>2]+(yr<<2)>>2];mr=-1;if((qr|0)==-1){break l}mr=qr+ -1|0;if((qr>>>0)%3){break l}mr=qr+2|0}if((Ip|0)==(mr|0)){break k}tr=q[tr+32>>2];zr=q[tr+zr>>2];while(1){Ip=0;if((mr|0)==-1){break f}if((zr|0)!=q[tr+(mr<<2)>>2]){or=mr;break j}qr=or;mr=((mr>>>0)%3|0?-1:2)+mr|0;Ip=-1;m:{if((mr|0)==-1){break m}mr=q[q[pr+12>>2]+(mr<<2)>>2];Ip=-1;if((mr|0)==-1){break m}Ip=mr+ -1|0;if((mr>>>0)%3){break m}Ip=mr+2|0}mr=Ip;if((qr|0)!=(mr|0)){continue}break}}rr=rr+1|0;if(rr>>>0>>0){continue}break}}Ip=q[nr+36>>2];q[q[nr+16>>2]+(or<<2)>>2]=Ip-q[nr+32>>2]>>2;q[nr>>2]=or;n:{if(t[nr+40>>2]>Ip>>>0){q[Ip>>2]=or;q[nr+36>>2]=Ip+4;break n}ya(nr+32|0,nr);pr=q[vr>>2]}if((or|0)==-1){break i}Ip=((or>>>0)%3|0?-1:2)+or|0;if((Ip|0)==-1){break i}Ip=q[q[pr+12>>2]+(Ip<<2)>>2];if((Ip|0)==-1){break i}mr=Ip+((Ip>>>0)%3|0?-1:2)|0;if((mr|0)==-1){break i}qr=or;if((mr|0)==(or|0)){break i}while(1){Ip=mr;o:{p:{mr=q[ur>>2];rr=q[a+216>>2];if((mr|0)==(rr|0)){break p}wr=(mr-rr|0)/144|0;mr=0;while(1){yr=q[(rr+w(mr,144)|0)+32>>2];tr=Ip<<2;if(q[yr+tr>>2]==q[yr+(qr<<2)>>2]){mr=mr+1|0;if(mr>>>0>>0){continue}break p}break}mr=q[nr+36>>2];q[tr+q[nr+16>>2]>>2]=mr-q[nr+32>>2]>>2;q[nr>>2]=Ip;if(t[nr+40>>2]>mr>>>0){q[mr>>2]=Ip;q[nr+36>>2]=mr+4;break o}ya(nr+32|0,nr);pr=q[vr>>2];break o}mr=q[nr+16>>2];q[mr+(Ip<<2)>>2]=q[mr+(qr<<2)>>2]}if((Ip|0)==-1){break i}mr=Ip+((Ip>>>0)%3|0?-1:2)|0;if((mr|0)==-1){break i}mr=q[q[pr+12>>2]+(mr<<2)>>2];if((mr|0)==-1){break i}mr=mr+((mr>>>0)%3|0?-1:2)|0;if((mr|0)==-1){break i}qr=Ip;if((mr|0)!=(or|0)){continue}break}}sr=sr+1|0;if((sr|0)>2]-q[pr+24>>2]>>2){continue}break}break g}bn();F()}or=q[a+4>>2];a=q[or+44>>2];Ip=q[a+100>>2];a=q[a+96>>2];if((Ip|0)!=(a|0)){qr=(Ip-a|0)/12|0;mr=0;pr=q[nr+16>>2];while(1){sr=nr+8|0;rr=w(mr,12);Ip=rr+pr|0;q[sr>>2]=q[Ip+8>>2];ur=q[Ip+4>>2];vr=q[Ip>>2];q[nr>>2]=vr;q[nr+4>>2]=ur;Ip=a+rr|0;q[Ip>>2]=vr;q[Ip+4>>2]=q[nr+4>>2];q[Ip+8>>2]=q[sr>>2];mr=mr+1|0;if(mr>>>0>>0){continue}break}}q[q[or+4>>2]+80>>2]=q[nr+36>>2]-q[nr+32>>2]>>2;Ip=1}mr=Ip;a=q[nr+16>>2];if(a){q[nr+20>>2]=a;An(a)}a=q[nr+32>>2];if(!a){break b}q[nr+36>>2]=a;An(a)}T=nr+48|0;return mr}function yi(a,Ip){var Cr=0,Dr=0,Er=0,Fr=0,Gr=0,Hr=0;a:{Fr=q[a>>2];Gr=q[a+4>>2]-Fr|0;Cr=(Gr|0)/12|0;Dr=Cr+1|0;if(Dr>>>0<357913942){Hr=w(Cr,12);Er=(q[a+8>>2]-Fr|0)/12|0;Cr=Er<<1;Er=Er>>>0<178956970?Cr>>>0>>0?Dr:Cr:357913941;Cr=0;b:{if(!Er){break b}if(Er>>>0>=357913942){break a}Cr=Mm(w(Er,12))}Dr=Hr+Cr|0;Hr=q[Ip+4>>2];q[Dr>>2]=q[Ip>>2];q[Dr+4>>2]=Hr;q[Dr+8>>2]=q[Ip+8>>2];Ip=Dr+w((Gr|0)/-12|0,12)|0;Cr=Cr+w(Er,12)|0;Dr=Dr+12|0;if((Gr|0)>=1){Cn(Ip,Fr,Gr)}q[a>>2]=Ip;q[a+8>>2]=Cr;q[a+4>>2]=Dr;if(Fr){An(Fr)}return}bn();F()}ab(12024);F()}function zi(a,Ip){var Ir=0,Jr=0,Kr=0,Lr=0,Mr=0,Nr=0;a:{Kr=q[a>>2];Mr=q[a+4>>2]-Kr|0;Ir=Mr>>2;Jr=Ir+1|0;if(Jr>>>0<1073741824){Nr=Ir<<2;Ir=q[a+8>>2]-Kr|0;Lr=Ir>>1;Jr=Ir>>2>>>0<536870911?Lr>>>0>>0?Jr:Lr:1073741823;Ir=0;b:{if(!Jr){break b}if(Jr>>>0>=1073741824){break a}Ir=Mm(Jr<<2)}Lr=Nr+Ir|0;q[Lr>>2]=q[Ip>>2];Ip=Ir+(Jr<<2)|0;Jr=Lr+4|0;if((Mr|0)>=1){Cn(Ir,Kr,Mr)}q[a>>2]=Ir;q[a+8>>2]=Ip;q[a+4>>2]=Jr;if(Kr){An(Kr)}return}bn();F()}ab(12024);F()}function Ai(a){var Ip=0,Or=0,Pr=0,Qr=0;Or=1;Pr=q[a+140>>2];a:{if((Pr|0)<1){break a}Ip=Pr<<4;Or=Mm((Pr|0)!=(Pr&268435455)?-1:Ip|4);q[Or>>2]=Pr;Or=Or+4|0;Pr=Or+Ip|0;Ip=Or;while(1){Ip=ah(Ip)+16|0;if((Pr|0)!=(Ip|0)){continue}break}Qr=q[a+136>>2];q[a+136>>2]=Or;if(Qr){Pr=Qr+ -4|0;Or=q[Pr>>2];if(Or){Ip=Qr+(Or<<4)|0;while(1){Ip=Ip+ -16|0;if((Qr|0)!=(Ip|0)){continue}break}}An(Pr)}Or=1;if(q[a+140>>2]<1){break a}Or=0;Ip=0;while(1){if(!bh(q[a+136>>2]+(Ip<<4)|0,a)){break a}Ip=Ip+1|0;if((Ip|0)>2]){continue}break}Or=1}return Or}function Bi(a,Rr,Sr,Tr){var Ur=0,Vr=0,Wr=0,Xr=0,Yr=0,Zr=x(0),_r=0,$r=x(0),as=0;Ur=q[Sr>>2];as=a;a:{b:{Vr=q[Rr+4>>2];if(!Vr){break b}_r=q[Rr>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2]+1;Rr=1}o[as+4|0]=Rr;q[a>>2]=Sr}function Ci(a,Rr,Sr){var Tr=0,bs=0,cs=0,ds=0,es=0;a:{b:{ds=q[a+8>>2];bs=a+4|0;Tr=q[bs>>2];c:{if((ds-Tr|0)/12>>>0>=Rr>>>0){while(1){a=q[Sr+4>>2];q[Tr>>2]=q[Sr>>2];q[Tr+4>>2]=a;q[Tr+8>>2]=q[Sr+8>>2];Tr=q[bs>>2]+12|0;q[bs>>2]=Tr;Rr=Rr+ -1|0;if(Rr){continue}break c}}cs=q[a>>2];es=(Tr-cs|0)/12|0;bs=es+Rr|0;if(bs>>>0>=357913942){break b}ds=(ds-cs|0)/12|0;cs=ds<<1;bs=ds>>>0<178956970?cs>>>0>>0?bs:cs:357913941;Tr=0;d:{if(!bs){break d}if(bs>>>0>=357913942){break a}Tr=Mm(w(bs,12))}ds=Tr+w(bs,12)|0;bs=Tr+w(es,12)|0;Tr=bs;while(1){cs=q[Sr+4>>2];q[Tr>>2]=q[Sr>>2];q[Tr+4>>2]=cs;q[Tr+8>>2]=q[Sr+8>>2];Tr=Tr+12|0;Rr=Rr+ -1|0;if(Rr){continue}break}cs=a+4|0;Rr=q[a>>2];Sr=q[cs>>2]-Rr|0;bs=bs+w((Sr|0)/-12|0,12)|0;if((Sr|0)>=1){Cn(bs,Rr,Sr)}q[a>>2]=bs;q[a+8>>2]=ds;q[cs>>2]=Tr;if(!Rr){break c}An(Rr)}return}bn();F()}ab(12024);F()}function Di(a){a=a|0;return q[a+8>>2]}function Ei(a){q[a>>2]=11324;Dn(a+4|0,0,80);q[a+96>>2]=0;q[a+100>>2]=0;q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+104>>2]=0;q[a+108>>2]=0;q[a+112>>2]=0;q[a+116>>2]=0;q[a+120>>2]=0;q[a+124>>2]=0;q[a+128>>2]=0;q[a+132>>2]=0;q[a+136>>2]=0;q[a+140>>2]=0;q[a+144>>2]=0;q[a+148>>2]=0;q[a+156>>2]=0;q[a+160>>2]=0;q[a+152>>2]=1065353216;q[a+164>>2]=0;q[a+168>>2]=0;q[a+172>>2]=0;q[a+176>>2]=0;q[a+180>>2]=0;q[a+184>>2]=0;q[a+188>>2]=0;q[a+192>>2]=0;q[a+196>>2]=0;q[a+200>>2]=0;q[a+204>>2]=0;q[a+208>>2]=0;q[a+212>>2]=-1;q[a+216>>2]=0;q[a+220>>2]=0;q[a+224>>2]=0;ci(a+232|0);q[a+396>>2]=0;q[a+388>>2]=0;q[a+392>>2]=0;q[a+380>>2]=0;q[a+384>>2]=0;ah(a+400|0);q[a+416>>2]=-1;q[a+420>>2]=-1}function Fi(a){a=a|0;var Rr=0,Sr=0,fs=0,gs=0,hs=0,is=0,js=0,ks=0,ls=0,ms=0,ns=0,os=0,ps=0,qs=0,rs=0,ss=0,ts=0;ks=T+ -64|0;T=ks;q[a+132>>2]=0;if(q[a+148>>2]){fs=a+144|0;Sr=q[fs>>2];if(Sr){while(1){Rr=q[Sr>>2];An(Sr);Sr=Rr;if(Rr){continue}break}}q[fs>>2]=0;Rr=q[a+140>>2];if(Rr){fs=a+136|0;Sr=0;while(1){q[q[fs>>2]+(Sr<<2)>>2]=0;Sr=Sr+1|0;if((Rr|0)!=(Sr|0)){continue}break}}q[a+148>>2]=0}a:{b:{c:{d:{e:{f:{Sr=q[a+4>>2];fs=r[Sr+36|0];Rr=fs<<8|r[Sr+37|0];g:{if(Rr>>>0>513){break g}is=q[Sr+32>>2];if(Rr>>>0<=511){gs=q[is+12>>2];Rr=q[is+20>>2];js=q[is+16>>2];hs=js+4|0;if(hs>>>0<4){Rr=Rr+1|0}ls=hs;hs=Rr;if((gs|0)<(Rr|0)?1:(gs|0)<=(Rr|0)?t[is+8>>2]>=ls>>>0?0:1:0){break f}Rr=js+q[is>>2]|0;Rr=r[Rr|0]|r[Rr+1|0]<<8|(r[Rr+2|0]<<16|r[Rr+3|0]<<24);q[ks>>2]=Rr;q[is+16>>2]=ls;q[is+20>>2]=hs;q[a+132>>2]=Rr;break g}if(!oi(1,ks,is)){break f}Sr=q[a+4>>2];fs=r[Sr+36|0];q[a+132>>2]=q[ks>>2]}Sr=q[Sr+32>>2];h:{i:{j:{if((fs&255)>>>0<=1){fs=0;is=q[Sr+12>>2];Rr=q[Sr+20>>2];gs=q[Sr+16>>2];hs=gs+4|0;if(hs>>>0<4){Rr=Rr+1|0}js=hs;hs=Rr;if((is|0)<(Rr|0)?1:(is|0)<=(Rr|0)?t[Sr+8>>2]>=js>>>0?0:1:0){break a}Rr=gs+q[Sr>>2]|0;Rr=r[Rr|0]|r[Rr+1|0]<<8|(r[Rr+2|0]<<16|r[Rr+3|0]<<24);q[ks+60>>2]=Rr;q[Sr+16>>2]=js;q[Sr+20>>2]=hs;q[a+156>>2]=Rr;ns=a+156|0;break j}fs=0;if(!oi(1,ks+60|0,Sr)){break a}Rr=q[a+4>>2];Sr=q[Rr+32>>2];Rr=r[Rr+36|0];q[a+156>>2]=q[ks+60>>2];ns=a+156|0;if(Rr>>>0>1){break i}}is=q[Sr+12>>2];Rr=q[Sr+20>>2];gs=q[Sr+16>>2];hs=gs+4|0;if(hs>>>0<4){Rr=Rr+1|0}ls=hs;hs=Rr;if((is|0)<(Rr|0)?1:(is|0)<=(Rr|0)?t[Sr+8>>2]>=ls>>>0?0:1:0){break a}Rr=gs+q[Sr>>2]|0;js=r[Rr|0]|r[Rr+1|0]<<8|(r[Rr+2|0]<<16|r[Rr+3|0]<<24);q[ks+56>>2]=js;q[Sr+16>>2]=ls;q[Sr+20>>2]=hs;break h}if(!oi(1,ks+56|0,Sr)){break a}js=q[ks+56>>2]}if(js>>>0>1431655765|t[ns>>2]>w(js,3)>>>0){break a}os=q[a+4>>2];hs=q[os+32>>2];ps=q[hs+8>>2];ms=q[hs+16>>2];is=q[hs+12>>2];Rr=is;Sr=q[hs+20>>2];if((Rr|0)<(Sr|0)?1:(Rr|0)<=(Sr|0)?ps>>>0>ms>>>0?0:1:0){break a}rs=q[hs>>2];ls=r[rs+ms|0];Rr=Sr;qs=ms+1|0;if(qs>>>0<1){Rr=Rr+1|0}q[hs+16>>2]=qs;q[hs+20>>2]=Rr;k:{if(r[os+36|0]<=1){Rr=Sr;Sr=ms+5|0;if(Sr>>>0<5){Rr=Rr+1|0}gs=Sr;Sr=Rr;if((is|0)<(Rr|0)?1:(is|0)<=(Rr|0)?ps>>>0>=gs>>>0?0:1:0){break a}Rr=qs+rs|0;is=r[Rr|0]|r[Rr+1|0]<<8|(r[Rr+2|0]<<16|r[Rr+3|0]<<24);q[ks+52>>2]=is;q[hs+16>>2]=gs;q[hs+20>>2]=Sr;break k}if(!oi(1,ks+52|0,hs)){break a}is=q[ks+52>>2]}if(js>>>0>>0|js>>>0>((is>>>0)/3|0)+is>>>0){break a}Rr=q[a+4>>2];hs=q[Rr+32>>2];l:{if(r[Rr+36|0]<=1){gs=q[hs+12>>2];Rr=q[hs+20>>2];ms=q[hs+16>>2];Sr=ms+4|0;if(Sr>>>0<4){Rr=Rr+1|0}os=Sr;Sr=Rr;if((gs|0)<(Rr|0)?1:(gs|0)<=(Rr|0)?t[hs+8>>2]>=os>>>0?0:1:0){break a}Rr=ms+q[hs>>2]|0;ms=r[Rr|0]|r[Rr+1|0]<<8|(r[Rr+2|0]<<16|r[Rr+3|0]<<24);q[ks+48>>2]=ms;q[hs+16>>2]=os;q[hs+20>>2]=Sr;break l}if(!oi(1,ks+48|0,hs)){break a}ms=q[ks+48>>2]}if(ms>>>0>is>>>0){break a}q[a+28>>2]=q[a+24>>2];Sr=Mm(88);jk(Sr);Rr=q[a+8>>2];q[a+8>>2]=Sr;hs=a+8|0;if(Rr){wa(hs,Rr);if(!q[hs>>2]){break a}}Rr=q[a+160>>2];q[a+164>>2]=Rr;m:{if(q[a+168>>2]-Rr>>2>>>0>=js>>>0){break m}if(js>>>0>=1073741824){break e}fs=js<<2;Sr=Mm(fs);q[a+164>>2]=Sr;q[a+160>>2]=Sr;q[a+168>>2]=Sr+fs;if(!Rr){break m}An(Rr)}Rr=q[a+172>>2];q[a+176>>2]=Rr;n:{if(q[a+180>>2]-Rr>>2>>>0>=js>>>0){break n}if(js>>>0>=1073741824){break d}fs=js<<2;Sr=Mm(fs);q[a+176>>2]=Sr;q[a+172>>2]=Sr;q[a+180>>2]=Sr+fs;if(!Rr){break n}An(Rr)}q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+40>>2]=q[a+36>>2];q[a- -64>>2]=0;q[a+52>>2]=q[a+48>>2];q[a+76>>2]=q[a+72>>2];os=a+216|0;Sr=q[a+220>>2];fs=q[a+216>>2];if((Sr|0)==(fs|0)){break c}while(1){Rr=q[Sr+ -12>>2];if(Rr){q[Sr+ -8>>2]=Rr;An(Rr)}Rr=q[Sr+ -28>>2];if(Rr){q[Sr+ -24>>2]=Rr;An(Rr)}Rr=Sr+ -144|0;gs=q[Sr+ -40>>2];if(gs){q[Sr+ -36>>2]=gs;An(gs)}pi(Sr+ -140|0);Sr=Rr;if((fs|0)!=(Rr|0)){continue}break}Rr=q[os>>2];break b}fs=0;break a}ab(12024);F()}ab(12024);F()}Rr=fs}q[a+220>>2]=fs;Sr=(fs-Rr|0)/144|0;o:{if(Sr>>>0>>0){qi(os,ls-Sr|0);break o}if(Sr>>>0<=ls>>>0){break o}Sr=Rr+w(ls,144)|0;if((Sr|0)!=(fs|0)){while(1){Rr=q[fs+ -12>>2];if(Rr){q[fs+ -8>>2]=Rr;An(Rr)}Rr=q[fs+ -28>>2];if(Rr){q[fs+ -24>>2]=Rr;An(Rr)}Rr=fs+ -144|0;gs=q[fs+ -40>>2];if(gs){q[fs+ -36>>2]=gs;An(gs)}pi(fs+ -140|0);fs=Rr;if((Rr|0)!=(Sr|0)){continue}break}}q[a+220>>2]=Sr}fs=0;if(!tk(q[hs>>2],js,q[ns>>2]+ms|0)){break a}Rr=q[a+156>>2];o[ks|0]=1;bb(a+120|0,Rr+ms|0,ks);Sr=q[a+4>>2];Rr=s[Sr+36>>1];Rr=(Rr<<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ks);r:{if(!Gi(ns,Sr)){break r}js=Hi(a,is);if((js|0)==-1){break r}is=q[q[a+4>>2]+32>>2];fs=q[Sr+16>>2];ls=fs+q[Sr>>2]|0;Sr=q[Sr+8>>2];Zj(is,ls,Sr-fs|0,s[is+38>>1]);Sr=q[a+4>>2];fs=s[Sr+36>>1];is=(fs<<24|fs<<8&16711680)>>>16;if(is>>>0<=513){fs=q[Sr+32>>2];ls=fs;ps=fs;Sr=gs+q[fs+20>>2]|0;fs=Rr+q[fs+16>>2]|0;if(fs>>>0>>0){Sr=Sr+1|0}q[ps+16>>2]=fs;q[ls+20>>2]=Sr}s:{if(q[a+220>>2]==q[a+216>>2]){break s}Sr=q[hs>>2];Rr=q[Sr+4>>2];Sr=q[Sr>>2];t:{if(is>>>0>=513){if((Rr|0)==(Sr|0)){break s}Sr=0;break t}if((Rr|0)==(Sr|0)){break s}Sr=0;while(1){if(ui(a,Sr)){Sr=Sr+3|0;Rr=q[hs>>2];if(Sr>>>0>2]-q[Rr>>2]>>2>>>0){continue}break s}break}fs=0;break r}while(1){if(vi(a,Sr)){Sr=Sr+3|0;Rr=q[hs>>2];if(Sr>>>0>2]-q[Rr>>2]>>2>>>0){continue}break s}break}fs=0;break r}if(r[a+308|0]){ak(a+272|0)}if(s[a+270>>1]<=513){ak(a+328|0)}Sr=q[a+216>>2];gs=a+220|0;if((Sr|0)!=q[gs>>2]){is=0;while(1){Rr=w(is,144);Ek((Rr+Sr|0)+4|0,q[hs>>2]);fs=q[os>>2];ls=Rr+fs|0;Sr=q[ls+132>>2];ls=q[ls+136>>2];if((Sr|0)!=(ls|0)){while(1){Gk((Rr+fs|0)+4|0,q[Sr>>2]);fs=q[os>>2];Sr=Sr+4|0;if((ls|0)!=(Sr|0)){continue}break}}Fk((Rr+fs|0)+4|0);is=is+1|0;Sr=q[a+216>>2];if(is>>>0<(q[gs>>2]-Sr|0)/144>>>0){continue}break}}Rr=q[a+8>>2];wi(a+184|0,q[Rr+28>>2]-q[Rr+24>>2]>>2);fs=q[a+216>>2];if((fs|0)!=q[gs>>2]){Sr=0;is=a+220|0;while(1){Rr=w(Sr,144)+fs|0;fs=q[Rr+60>>2]-q[Rr+56>>2]>>2;ls=Rr+104|0;Rr=q[hs>>2];Rr=q[Rr+28>>2]-q[Rr+24>>2]>>2;wi(ls,(fs|0)<(Rr|0)?Rr:fs);Sr=Sr+1|0;fs=q[a+216>>2];if(Sr>>>0<(q[is>>2]-fs|0)/144>>>0){continue}break}}fs=xi(a,js)}}T=ks- -64|0;return fs|0}function Gi(a,us){var vs=0,ws=0,xs=0,ys=0,zs=0,As=0,Bs=0;ys=T-16|0;T=ys;a:{if(!si(a,us)){break a}zs=q[us+12>>2];vs=q[us+20>>2];As=q[us+16>>2];xs=As+4|0;if(xs>>>0<4){vs=vs+1|0}ws=xs;xs=vs;if((zs|0)<(vs|0)?1:(zs|0)<=(vs|0)?t[us+8>>2]>=ws>>>0?0:1:0){break a}vs=As+q[us>>2]|0;vs=r[vs|0]|r[vs+1|0]<<8|(r[vs+2|0]<<16|r[vs+3|0]<<24);q[us+16>>2]=ws;q[us+20>>2]=xs;if((vs|0)<0){break a}ws=q[a+152>>2];if((vs|0)>=(ws|0)){break a}q[ys+12>>2]=0;xs=q[a+156>>2];vs=q[a+160>>2]-xs>>2;b:{if(ws>>>0>vs>>>0){Ad(a+156|0,ws-vs|0,ys+12|0);break b}if(ws>>>0>=vs>>>0){break b}q[a+160>>2]=xs+(ws<<2)}Bs=bh(a+168|0,us)}T=ys+16|0;return Bs}function Hi(a,us){var Cs=0,Ds=0,Es=0,Fs=0,Gs=0,Hs=0,Is=0,Js=0,Ks=0,Ls=0,Ms=0,Ns=0,Os=0,Ps=0,Qs=0,Rs=0,Ss=0,Ts=0,Us=0,Vs=0,Ws=0,Xs=0,Ys=0,Zs=0,_s=0,$s=0,at=0;Gs=T-96|0;T=Gs;q[Gs+72>>2]=0;q[Gs+64>>2]=0;q[Gs+68>>2]=0;q[Gs+48>>2]=0;q[Gs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>>2]){q[Ds>>2]=q[Gs+88>>2];q[Ws>>2]=Ds+4;break M}zi(Ps,Gs+88|0);break M}Ds=q[a+64>>2];Fs=q[Os>>2];if((Ds|0)==Fs<<5){if((Ds+1|0)<=-1){break a}Cs=us;if(Ds>>>0<=1073741822){Ls=Ds+32&-32;Ds=Fs<<6;Ds=Ds>>>0>>0?Ls:Ds}else{Ds=2147483647}cb(Cs,Ds);Ds=q[a+64>>2]}q[a+64>>2]=Ds+1;Ls=q[a+60>>2]+(Ds>>>3&536870908)|0;Cs=q[Ls>>2];$s=Ls,at=eo(Ds)&Cs,q[$s>>2]=at;Ds=q[Ws>>2];if((Ds|0)!=q[Qs>>2]){q[Ds>>2]=q[Gs>>2];q[Ws>>2]=Ds+4;break M}zi(Ps,Gs)}Ds=q[Gs+68>>2];if((Ds|0)!=q[Gs+64>>2]){continue}break}Js=q[a+8>>2]}if(((q[Js+4>>2]-q[Js>>2]>>2>>>0)/3|0)!=(Hs|0)){break c}Es=q[Js+28>>2]-q[Js+24>>2]>>2;us=q[Gs+24>>2];Ks=q[Gs+28>>2];if((us|0)==(Ks|0)){break b}Fs=a+8|0;while(1){Is=q[us>>2];Hs=q[Js+24>>2];Ds=Es+ -1|0;T:{if(q[Hs+(Ds<<2)>>2]!=-1){Ls=Es;break T}Hs=q[Js+24>>2];while(1){Ds=Es+ -2|0;Ls=Es+ -1|0;Es=Ls;if(q[(Ds<<2)+Hs>>2]==-1){continue}break}}if(!(Ds>>>0>>0)){q[Gs>>2]=Js;Cs=Ds<<2;Es=q[Cs+Hs>>2];o[Gs+12|0]=1;q[Gs+8>>2]=Es;q[Gs+4>>2]=Es;if((Es|0)!=-1){while(1){q[q[Js>>2]+(Es<<2)>>2]=Is;lg(Gs);Js=q[Fs>>2];Es=q[Gs+8>>2];if((Es|0)!=-1){continue}break}}Es=Cs;Cs=q[Js+24>>2];Es=Es+Cs|0;if((Is|0)!=-1){q[Cs+(Is<<2)>>2]=q[Es>>2]}q[Es>>2]=-1;Ys=1<<(Is&31);Es=q[a+120>>2];Is=Es+(Is>>>3&536870908)|0;Cs=Is;Hs=Es+(Ds>>>3&536870908)|0;Ds=1<<(Ds&31);Es=Ys|q[Is>>2];U:{if(q[Hs>>2]&Ds){break U}Es=q[Is>>2]&(Ys^-1)}q[Cs>>2]=Es;q[Hs>>2]=q[Hs>>2]&(Ds^-1);Ls=Ls+ -1|0}Es=Ls;us=us+4|0;if((Ks|0)!=(us|0)){continue}break}}us=q[Gs+24>>2]}if(us){q[Gs+28>>2]=us;An(us)}Ds=q[Gs+48>>2];if(Ds){while(1){a=q[Ds>>2];An(Ds);Ds=a;if(Ds){continue}break}}a=q[Gs+40>>2];q[Gs+40>>2]=0;if(a){An(a)}a=q[Gs+64>>2];if(a){q[Gs+68>>2]=a;An(a)}T=Gs+96|0;return Es}bn();F()}function Ii(a,us){var bt=0,ct=0,dt=0,et=0,ft=0;ct=-1;ft=-1;a:{if((us|0)==-1){break a}bt=us+1|0;ct=(bt>>>0)%3|0?bt:us+ -2|0;ft=us+ -1|0;if((us>>>0)%3){break a}ft=us+2|0}bt=q[a+184>>2];b:{if(bt>>>0>7){break b}c:{d:{switch(bt-2|0){default:dt=q[a+148>>2];bt=-1;bt=(ct|0)!=-1?q[q[dt>>2]+(ct<<2)>>2]:bt;ct=1;et=bt<<2;bt=q[a+156>>2];et=et+bt|0;q[et>>2]=q[et>>2]+1;bt=(((ft|0)!=-1?q[q[dt>>2]+(ft<<2)>>2]:-1)<<2)+bt|0;break c;case 3:et=q[a+148>>2];bt=q[a+156>>2];dt=bt+(((us|0)!=-1?q[q[et>>2]+(us<<2)>>2]:-1)<<2)|0;q[dt>>2]=q[dt>>2]+1;dt=(((ct|0)!=-1?q[q[et>>2]+(ct<<2)>>2]:-1)<<2)+bt|0;q[dt>>2]=q[dt>>2]+1;ct=2;bt=(((ft|0)!=-1?q[q[et>>2]+(ft<<2)>>2]:-1)<<2)+bt|0;break c;case 1:et=q[a+148>>2];bt=q[a+156>>2];dt=bt+(((us|0)!=-1?q[q[et>>2]+(us<<2)>>2]:-1)<<2)|0;q[dt>>2]=q[dt>>2]+1;dt=(((ct|0)!=-1?q[q[et>>2]+(ct<<2)>>2]:-1)<<2)+bt|0;q[dt>>2]=q[dt>>2]+2;ct=1;bt=(((ft|0)!=-1?q[q[et>>2]+(ft<<2)>>2]:-1)<<2)+bt|0;break c;case 0:case 2:case 4:break b;case 5:break d}}et=q[a+148>>2];bt=q[a+156>>2];dt=bt+(((us|0)!=-1?q[q[et>>2]+(us<<2)>>2]:-1)<<2)|0;q[dt>>2]=q[dt>>2]+2;dt=(((ct|0)!=-1?q[q[et>>2]+(ct<<2)>>2]:-1)<<2)+bt|0;q[dt>>2]=q[dt>>2]+2;ct=2;bt=(((ft|0)!=-1?q[q[et>>2]+(ft<<2)>>2]:-1)<<2)+bt|0}q[bt>>2]=q[bt>>2]+ct;bt=q[a+184>>2]}e:{if(bt>>>0>5){break e}f:{switch(bt-1|0){case 0:case 1:case 2:case 3:break e;default:break f}}bt=a;ft=bt;bt=q[bt+156>>2];ct=-1;g:{if((us|0)==-1){break g}ct=us+1|0;us=(ct>>>0)%3|0?ct:us+ -2|0;ct=-1;if((us|0)==-1){break g}ct=q[q[q[a+148>>2]>>2]+(us<<2)>>2]}q[ft+188>>2]=q[bt+(ct<<2)>>2]>5?0:5;return}q[a+188>>2]=-1}function Ji(a){q[a>>2]=11372;Dn(a+4|0,0,80);q[a+96>>2]=0;q[a+100>>2]=0;q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+104>>2]=0;q[a+108>>2]=0;q[a+112>>2]=0;q[a+116>>2]=0;q[a+120>>2]=0;q[a+124>>2]=0;q[a+128>>2]=0;q[a+132>>2]=0;q[a+136>>2]=0;q[a+140>>2]=0;q[a+144>>2]=0;q[a+148>>2]=0;q[a+156>>2]=0;q[a+160>>2]=0;q[a+152>>2]=1065353216;q[a+164>>2]=0;q[a+168>>2]=0;q[a+172>>2]=0;q[a+176>>2]=0;q[a+180>>2]=0;q[a+184>>2]=0;q[a+188>>2]=0;q[a+192>>2]=0;q[a+196>>2]=0;q[a+200>>2]=0;q[a+204>>2]=0;q[a+208>>2]=0;q[a+212>>2]=-1;q[a+216>>2]=0;q[a+220>>2]=0;q[a+224>>2]=0;ci(a+232|0);q[a+388>>2]=0;q[a+392>>2]=0;q[a+380>>2]=0;q[a+384>>2]=0;q[a+416>>2]=0;q[a+420>>2]=0;q[a+412>>2]=7;q[a+404>>2]=-1;q[a+408>>2]=2;q[a+396>>2]=0;q[a+400>>2]=-1;q[a+424>>2]=0;q[a+428>>2]=0;q[a+432>>2]=0;q[a+436>>2]=0}function Ki(a){a=a|0;var us=0,gt=0,ht=0,it=0,jt=0,kt=0,lt=0,mt=0,nt=0,ot=0,pt=0,qt=0,rt=0,st=0,tt=0,ut=0,vt=0;mt=T+ -64|0;T=mt;q[a+132>>2]=0;if(q[a+148>>2]){ht=a+144|0;gt=q[ht>>2];if(gt){while(1){us=q[gt>>2];An(gt);gt=us;if(us){continue}break}}q[ht>>2]=0;us=q[a+140>>2];if(us){ht=a+136|0;gt=0;while(1){q[q[ht>>2]+(gt<<2)>>2]=0;gt=gt+1|0;if((us|0)!=(gt|0)){continue}break}}q[a+148>>2]=0}a:{b:{c:{d:{e:{f:{gt=q[a+4>>2];ht=r[gt+36|0];us=ht<<8|r[gt+37|0];g:{if(us>>>0>513){break g}kt=q[gt+32>>2];if(us>>>0<=511){it=q[kt+12>>2];us=q[kt+20>>2];lt=q[kt+16>>2];jt=lt+4|0;if(jt>>>0<4){us=us+1|0}nt=jt;jt=us;if((it|0)<(us|0)?1:(it|0)<=(us|0)?t[kt+8>>2]>=nt>>>0?0:1:0){break f}us=lt+q[kt>>2]|0;us=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt>>2]=us;q[kt+16>>2]=nt;q[kt+20>>2]=jt;q[a+132>>2]=us;break g}if(!oi(1,mt,kt)){break f}gt=q[a+4>>2];ht=r[gt+36|0];q[a+132>>2]=q[mt>>2]}gt=q[gt+32>>2];h:{i:{j:{if((ht&255)>>>0<=1){ht=0;kt=q[gt+12>>2];us=q[gt+20>>2];it=q[gt+16>>2];jt=it+4|0;if(jt>>>0<4){us=us+1|0}lt=jt;jt=us;if((kt|0)<(us|0)?1:(kt|0)<=(us|0)?t[gt+8>>2]>=lt>>>0?0:1:0){break a}us=it+q[gt>>2]|0;us=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt+60>>2]=us;q[gt+16>>2]=lt;q[gt+20>>2]=jt;q[a+156>>2]=us;pt=a+156|0;break j}ht=0;if(!oi(1,mt+60|0,gt)){break a}us=q[a+4>>2];gt=q[us+32>>2];us=r[us+36|0];q[a+156>>2]=q[mt+60>>2];pt=a+156|0;if(us>>>0>1){break i}}kt=q[gt+12>>2];us=q[gt+20>>2];it=q[gt+16>>2];jt=it+4|0;if(jt>>>0<4){us=us+1|0}nt=jt;jt=us;if((kt|0)<(us|0)?1:(kt|0)<=(us|0)?t[gt+8>>2]>=nt>>>0?0:1:0){break a}us=it+q[gt>>2]|0;lt=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt+56>>2]=lt;q[gt+16>>2]=nt;q[gt+20>>2]=jt;break h}if(!oi(1,mt+56|0,gt)){break a}lt=q[mt+56>>2]}if(lt>>>0>1431655765|t[pt>>2]>w(lt,3)>>>0){break a}qt=q[a+4>>2];jt=q[qt+32>>2];rt=q[jt+8>>2];ot=q[jt+16>>2];kt=q[jt+12>>2];us=kt;gt=q[jt+20>>2];if((us|0)<(gt|0)?1:(us|0)<=(gt|0)?rt>>>0>ot>>>0?0:1:0){break a}tt=q[jt>>2];nt=r[tt+ot|0];us=gt;st=ot+1|0;if(st>>>0<1){us=us+1|0}q[jt+16>>2]=st;q[jt+20>>2]=us;k:{if(r[qt+36|0]<=1){us=gt;gt=ot+5|0;if(gt>>>0<5){us=us+1|0}it=gt;gt=us;if((kt|0)<(us|0)?1:(kt|0)<=(us|0)?rt>>>0>=it>>>0?0:1:0){break a}us=st+tt|0;kt=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt+52>>2]=kt;q[jt+16>>2]=it;q[jt+20>>2]=gt;break k}if(!oi(1,mt+52|0,jt)){break a}kt=q[mt+52>>2]}if(lt>>>0>>0|lt>>>0>((kt>>>0)/3|0)+kt>>>0){break a}us=q[a+4>>2];jt=q[us+32>>2];l:{if(r[us+36|0]<=1){it=q[jt+12>>2];us=q[jt+20>>2];ot=q[jt+16>>2];gt=ot+4|0;if(gt>>>0<4){us=us+1|0}qt=gt;gt=us;if((it|0)<(us|0)?1:(it|0)<=(us|0)?t[jt+8>>2]>=qt>>>0?0:1:0){break a}us=ot+q[jt>>2]|0;ot=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt+48>>2]=ot;q[jt+16>>2]=qt;q[jt+20>>2]=gt;break l}if(!oi(1,mt+48|0,jt)){break a}ot=q[mt+48>>2]}if(ot>>>0>kt>>>0){break a}q[a+28>>2]=q[a+24>>2];gt=Mm(88);jk(gt);us=q[a+8>>2];q[a+8>>2]=gt;jt=a+8|0;if(us){wa(jt,us);if(!q[jt>>2]){break a}}us=q[a+160>>2];q[a+164>>2]=us;m:{if(q[a+168>>2]-us>>2>>>0>=lt>>>0){break m}if(lt>>>0>=1073741824){break e}ht=lt<<2;gt=Mm(ht);q[a+164>>2]=gt;q[a+160>>2]=gt;q[a+168>>2]=gt+ht;if(!us){break m}An(us)}us=q[a+172>>2];q[a+176>>2]=us;n:{if(q[a+180>>2]-us>>2>>>0>=lt>>>0){break n}if(lt>>>0>=1073741824){break d}ht=lt<<2;gt=Mm(ht);q[a+176>>2]=gt;q[a+172>>2]=gt;q[a+180>>2]=gt+ht;if(!us){break n}An(us)}q[a+92>>2]=-1;q[a+84>>2]=-1;q[a+88>>2]=-1;q[a+40>>2]=q[a+36>>2];q[a- -64>>2]=0;q[a+52>>2]=q[a+48>>2];q[a+76>>2]=q[a+72>>2];qt=a+216|0;gt=q[a+220>>2];ht=q[a+216>>2];if((gt|0)==(ht|0)){break c}while(1){us=q[gt+ -12>>2];if(us){q[gt+ -8>>2]=us;An(us)}us=q[gt+ -28>>2];if(us){q[gt+ -24>>2]=us;An(us)}us=gt+ -144|0;it=q[gt+ -40>>2];if(it){q[gt+ -36>>2]=it;An(it)}pi(gt+ -140|0);gt=us;if((ht|0)!=(us|0)){continue}break}us=q[qt>>2];break b}ht=0;break a}ab(12024);F()}ab(12024);F()}us=ht}q[a+220>>2]=ht;gt=(ht-us|0)/144|0;o:{if(gt>>>0>>0){qi(qt,nt-gt|0);break o}if(gt>>>0<=nt>>>0){break o}gt=us+w(nt,144)|0;if((gt|0)!=(ht|0)){while(1){us=q[ht+ -12>>2];if(us){q[ht+ -8>>2]=us;An(us)}us=q[ht+ -28>>2];if(us){q[ht+ -24>>2]=us;An(us)}us=ht+ -144|0;it=q[ht+ -40>>2];if(it){q[ht+ -36>>2]=it;An(it)}pi(ht+ -140|0);ht=us;if((us|0)!=(gt|0)){continue}break}}q[a+220>>2]=gt}ht=0;if(!tk(q[jt>>2],lt,q[pt>>2]+ot|0)){break a}us=q[a+156>>2];o[mt|0]=1;bb(a+120|0,us+ot|0,mt);gt=q[a+4>>2];us=s[gt+36>>1];us=(us<<24|us<<8&16711680)>>>16;p:{if(us>>>0<=513){it=q[gt+32>>2];q:{if(us>>>0<=511){lt=q[it+12>>2];us=q[it+20>>2];pt=q[it+16>>2];gt=pt+4|0;if(gt>>>0<4){us=us+1|0}rt=gt;gt=us;if((lt|0)<(us|0)?1:(lt|0)<=(us|0)?t[it+8>>2]>=rt>>>0?0:1:0){break a}us=pt+q[it>>2]|0;lt=r[us|0]|r[us+1|0]<<8|(r[us+2|0]<<16|r[us+3|0]<<24);q[mt+44>>2]=lt;q[it+16>>2]=rt;q[it+20>>2]=gt;break q}if(!oi(1,mt+44|0,it)){break a}lt=q[mt+44>>2]}if(!lt){break a}us=q[q[a+4>>2]+32>>2];gt=q[us+8>>2];it=q[us+16>>2];us=q[us+12>>2]-(q[us+20>>2]+(gt>>>0>>0)|0)|0;if((us|0)<0?1:(us|0)<=0?gt-it>>>0>=lt>>>0?0:1:0){break a}it=Yj(mt);gt=q[q[a+4>>2]+32>>2];us=q[gt+16>>2];pt=q[gt+8>>2];Zj(it,(us+q[gt>>2]|0)+lt|0,(pt-us|0)-lt|0,s[gt+38>>1]);gt=ri(a,it);if((gt|0)==-1){break a}us=gt;it=us>>31;break p}us=-1;it=-1;if((ri(a,q[gt+32>>2])|0)==-1){break a}}q[a+376>>2]=a;pt=a+232|0;gt=q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2];rt=q[gt>>2]+q[gt+16>>2]|0;lt=q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2];gt=q[lt+8>>2];ht=q[lt+16>>2];Zj(pt,rt,gt-ht|0,s[q[(n[q[q[a>>2]+32>>2]](a)|0)+32>>2]+38>>1]);ut=a,vt=n[q[q[a>>2]+36>>2]](a)|0,q[ut+380>>2]=vt;q[a+372>>2]=nt;q[a+384>>2]=q[a+156>>2]+ot;ht=0;gt=Yj(mt);r:{if(!Li(pt,gt)){break r}lt=Mi(a,kt);if((lt|0)==-1){break r}kt=q[q[a+4>>2]+32>>2];ht=q[gt+16>>2];nt=ht+q[gt>>2]|0;gt=q[gt+8>>2];Zj(kt,nt,gt-ht|0,s[kt+38>>1]);gt=q[a+4>>2];ht=s[gt+36>>1];kt=(ht<<24|ht<<8&16711680)>>>16;if(kt>>>0<=513){ht=q[gt+32>>2];nt=ht;rt=ht;gt=it+q[ht+20>>2]|0;ht=us+q[ht+16>>2]|0;if(ht>>>0>>0){gt=gt+1|0}q[rt+16>>2]=ht;q[nt+20>>2]=gt}s:{if(q[a+220>>2]==q[a+216>>2]){break s}gt=q[jt>>2];us=q[gt+4>>2];gt=q[gt>>2];t:{if(kt>>>0>=513){if((us|0)==(gt|0)){break s}gt=0;break t}if((us|0)==(gt|0)){break s}gt=0;while(1){if(ui(a,gt)){gt=gt+3|0;us=q[jt>>2];if(gt>>>0>2]-q[us>>2]>>2>>>0){continue}break s}break}ht=0;break r}while(1){if(vi(a,gt)){gt=gt+3|0;us=q[jt>>2];if(gt>>>0>2]-q[us>>2]>>2>>>0){continue}break s}break}ht=0;break r}if(r[a+308|0]){ak(a+272|0)}if(s[a+270>>1]<=513){ak(a+328|0)}gt=q[a+216>>2];it=a+220|0;if((gt|0)!=q[it>>2]){kt=0;while(1){us=w(kt,144);Ek((us+gt|0)+4|0,q[jt>>2]);ht=q[qt>>2];nt=us+ht|0;gt=q[nt+132>>2];nt=q[nt+136>>2];if((gt|0)!=(nt|0)){while(1){Gk((us+ht|0)+4|0,q[gt>>2]);ht=q[qt>>2];gt=gt+4|0;if((nt|0)!=(gt|0)){continue}break}}Fk((us+ht|0)+4|0);kt=kt+1|0;gt=q[a+216>>2];if(kt>>>0<(q[it>>2]-gt|0)/144>>>0){continue}break}}us=q[a+8>>2];wi(a+184|0,q[us+28>>2]-q[us+24>>2]>>2);ht=q[a+216>>2];if((ht|0)!=q[it>>2]){gt=0;kt=a+220|0;while(1){us=w(gt,144)+ht|0;ht=q[us+60>>2]-q[us+56>>2]>>2;nt=us+104|0;us=q[jt>>2];us=q[us+28>>2]-q[us+24>>2]>>2;wi(nt,(ht|0)<(us|0)?us:ht);gt=gt+1|0;ht=q[a+216>>2];if(gt>>>0<(q[kt>>2]-ht|0)/144>>>0){continue}break}}ht=xi(a,lt)}}T=mt- -64|0;return ht|0}function Li(a,wt){var xt=0,yt=0,zt=0,At=0,Bt=0,Ct=0,Dt=0,Et=0,Ft=0,Gt=0,Ht=0,It=0;Et=T-16|0;T=Et;xt=q[a+144>>2];xt=s[(n[q[q[xt>>2]+32>>2]](xt)|0)+36>>1];a:{if((xt<<24|xt<<8&16711680)>>>16>>>0<=513){xt=q[a+4>>2];q[a+40>>2]=q[a>>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];q[a>>2]=q[xt>>2];q[a+4>>2]=Ct;Ct=q[xt+36>>2];q[zt>>2]=q[xt+32>>2];q[zt+4>>2]=Ct;zt=q[xt+28>>2];q[yt>>2]=q[xt+24>>2];q[yt+4>>2]=zt;yt=q[xt+20>>2];Ct=yt;zt=q[xt+16>>2];q[At>>2]=zt;q[At+4>>2]=yt;yt=q[xt+12>>2];xt=q[xt+8>>2];q[Bt>>2]=xt;q[Bt+4>>2]=yt;Bt=xt-zt|0;Dt=q[Et+12>>2];yt=yt-((xt>>>0>>0)+Ct|0)|0;xt=q[Et+8>>2];if((Dt|0)==(yt|0)&xt>>>0<=Bt>>>0|Dt>>>0>>0){break d}}At=0;break a}At=Ct+Dt|0;zt=xt+zt|0;if(zt>>>0>>0){At=At+1|0}q[a+16>>2]=zt;q[a+20>>2]=At;break c}At=0;if(!bh(a+80|0,a)){break a}}At=0;if(!Ai(a)){break a}xt=q[a+4>>2];q[wt>>2]=q[a>>2];q[wt+4>>2]=xt;xt=q[a+36>>2];q[wt+32>>2]=q[a+32>>2];q[wt+36>>2]=xt;xt=q[a+28>>2];q[wt+24>>2]=q[a+24>>2];q[wt+28>>2]=xt;xt=q[a+20>>2];q[wt+16>>2]=q[a+16>>2];q[wt+20>>2]=xt;xt=q[a+12>>2];q[wt+8>>2]=q[a+8>>2];q[wt+12>>2]=xt;xt=q[a+144>>2];xt=s[(n[q[q[xt>>2]+32>>2]](xt)|0)+36>>1];e:{if((xt<<24|xt<<8&16711680)>>>16>>>0<=513){xt=q[a+144>>2];f:{if(r[(n[q[q[xt>>2]+32>>2]](xt)|0)+36|0]<=1){yt=q[wt+12>>2];xt=q[wt+20>>2];Bt=q[wt+16>>2];zt=Bt+4|0;if(zt>>>0<4){xt=xt+1|0}Ct=zt;zt=xt;if((yt|0)<(xt|0)?1:(yt|0)<=(xt|0)?t[wt+8>>2]>=Ct>>>0?0:1:0){break a}xt=Bt+q[wt>>2]|0;yt=r[xt|0]|r[xt+1|0]<<8|(r[xt+2|0]<<16|r[xt+3|0]<<24);q[Et+8>>2]=yt;q[wt+16>>2]=Ct;q[wt+20>>2]=zt;break f}if(!oi(1,Et+8|0,wt)){break a}yt=q[Et+8>>2]}xt=q[a+152>>2];if(yt>>>0>=xt>>>0){break a}Bt=q[wt+16>>2];yt=q[wt+12>>2];zt=q[wt+20>>2];if((yt|0)<(zt|0)?1:(yt|0)<=(zt|0)?t[wt+8>>2]>Bt>>>0?0:1:0){break a}Ct=r[Bt+q[wt>>2]|0];Bt=Bt+1|0;if(Bt>>>0<1){zt=zt+1|0}yt=wt;q[yt+16>>2]=Bt;q[yt+20>>2]=zt;if(Ct){break a}q[a+176>>2]=2;q[a+180>>2]=7;break e}q[a+176>>2]=2;q[a+180>>2]=7;xt=q[a+152>>2]}if((xt|0)<0){break a}q[Et+8>>2]=0;At=2;Bt=q[a+156>>2];yt=q[a+160>>2]-Bt>>2;g:{if(xt>>>0>yt>>>0){Ad(a+156|0,xt-yt|0,Et+8|0);At=q[a+176>>2];zt=q[a+180>>2];break g}zt=7;if(xt>>>0>=yt>>>0){break g}q[a+160>>2]=Bt+(xt<<2)}Bt=a+184|0;zt=(zt-At|0)+1|0;At=a+188|0;xt=q[At>>2];Ct=q[a+184>>2];yt=(xt-Ct|0)/12|0;h:{if(zt>>>0>yt>>>0){Ni(Bt,zt-yt|0);zt=q[At>>2];break h}if(zt>>>0>=yt>>>0){zt=xt;break h}zt=Ct+w(zt,12)|0;if((zt|0)!=(xt|0)){while(1){yt=xt+ -12|0;At=q[yt>>2];if(At){q[xt+ -8>>2]=At;An(At)}xt=yt;if((xt|0)!=(zt|0)){continue}break}}q[a+188>>2]=zt}Ct=a+196|0;xt=q[a+184>>2];yt=(zt-xt|0)/12|0;Dt=q[a+196>>2];At=q[a+200>>2]-Dt>>2;i:{if(yt>>>0>At>>>0){Fa(Ct,yt-At|0);zt=q[a+188>>2];xt=q[a+184>>2];break i}if(yt>>>0>=At>>>0){break i}q[a+200>>2]=Dt+(yt<<2)}At=1;if((xt|0)==(zt|0)){break a}xt=0;It=a+188|0;while(1){oi(1,Et+8|0,wt);zt=q[Et+8>>2];if(zt){yt=q[Bt>>2];Ft=w(xt,12);At=yt+Ft|0;Gt=At+4|0;Ht=q[At>>2];Dt=q[Gt>>2]-Ht>>2;j:{if(zt>>>0>Dt>>>0){Fa(At,zt-Dt|0);yt=q[Bt>>2];break j}if(zt>>>0>=Dt>>>0){break j}q[Gt>>2]=(zt<<2)+Ht}qh(zt,1,wt,q[yt+Ft>>2]);q[q[Ct>>2]+(xt<<2)>>2]=zt}At=1;xt=xt+1|0;if(xt>>>0<(q[It>>2]-q[a+184>>2]|0)/12>>>0){continue}break}}T=Et+16|0;return At} + + + +function Mi(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,p=0,u=0,v=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0,H=0,I=0;g=T-96|0;T=g;q[g+72>>2]=0;q[g+64>>2]=0;q[g+68>>2]=0;q[g+48>>2]=0;q[g+52>>2]=0;q[g+40>>2]=0;q[g+44>>2]=0;q[g+56>>2]=1065353216;q[g+32>>2]=0;q[g+24>>2]=0;q[g+28>>2]=0;C=q[a+124>>2];a:{b:{c:{if((b|0)>=1){A=a+232|0;B=a+8|0;D=a+40|0;G=a+388|0;E=q[a+216>>2]!=q[a+220>>2];while(1){h=Oi(A);d:{if(!h){d=q[g+68>>2];if((d|0)==q[g+64>>2]){e=-1;break c}n=-1;u=q[B>>2];i=q[u+24>>2];f=i;h=d+ -4|0;v=q[h>>2];c=-1;e:{if((v|0)==-1){break e}e=v+1|0;e=(e>>>0)%3|0?e:v+ -2|0;c=-1;if((e|0)==-1){break e}c=q[q[u>>2]+(e<<2)>>2]}f=q[f+(c<<2)>>2];if((f|0)!=-1){e=f+1|0;n=(e>>>0)%3|0?e:f+ -2|0}f=q[u+12>>2];x=w(j,3);e=x+1|0;q[f+(v<<2)>>2]=e;e=e<<2;q[e+f>>2]=v;y=x+2|0;q[f+(n<<2)>>2]=y;k=y<<2;q[k+f>>2]=n;p=q[u>>2];q[p+(x<<2)>>2]=c;m=e+p|0;f=-1;f:{if((n|0)==-1){break f}e=n+1|0;e=(e>>>0)%3|0?e:n+ -2|0;f=-1;if((e|0)==-1){break f}f=q[p+(e<<2)>>2]}q[m>>2]=f;g:{h:{if((v|0)!=-1){e=v+((v>>>0)%3|0?-1:2)|0;if((e|0)!=-1){break h}}q[k+p>>2]=-1;break g}e=q[p+(e<<2)>>2];q[k+p>>2]=e;if((e|0)==-1){break g}q[i+(e<<2)>>2]=y}f=q[a+120>>2]+(c>>>3&536870908)|0;e=q[f>>2];H=f,I=eo(c)&e,q[H>>2]=I;q[h>>2]=x;c=0;break d}e=-1;d=h+ -1|0;if(d>>>0>6){break c}i:{j:{k:{l:{switch(d-1|0){case 1:case 3:f=q[g+68>>2];if((f|0)==q[g+64>>2]){break c}e=q[B>>2];c=q[e+12>>2];y=w(j,3);i=(h|0)==5;h=y+(i?2:1)|0;d=h<<2;p=q[f+ -4>>2];q[c+d>>2]=p;q[c+(p<<2)>>2]=h;f=e+24|0;m=q[e+32>>2];e=e+28|0;c=q[e>>2];m:{if((m|0)!=(c|0)){q[c>>2]=-1;u=c+4|0;q[e>>2]=u;break m}zi(f,11312);u=q[e>>2]}e=-1;c=q[B>>2];k=q[c+24>>2];if(q[c+28>>2]-k>>2>(C|0)){break c}e=y+2|0;x=q[c>>2];m=x+d|0;c=u-q[f>>2]|0;d=(c>>2)+ -1|0;q[m>>2]=d;if(c){q[k+(d<<2)>>2]=h}e=i?y:e;f=x+(i+y<<2)|0;n:{o:{p:{if((p|0)!=-1){d=p+((p>>>0)%3|0?-1:2)|0;if((d|0)==-1){break p}d=q[x+(d<<2)>>2];q[x+(e<<2)>>2]=d;if((d|0)==-1){break o}q[k+(d<<2)>>2]=e;break o}q[x+(e<<2)>>2]=-1;c=-1;break n}q[x+(e<<2)>>2]=-1}d=p+1|0;d=(d>>>0)%3|0?d:p+ -2|0;c=-1;if((d|0)==-1){break n}c=q[x+(d<<2)>>2]}q[f>>2]=c;d=q[g+68>>2];q[d+ -4>>2]=y;break k;default:d=q[g+68>>2];u=q[g+64>>2];if((d|0)==(u|0)){break c}c=d+ -4|0;z=q[c>>2];q[g+68>>2]=c;k=q[g+44>>2];q:{if(!k){d=c;break q}i=co(k)>>>0>1;r:{if(!i){f=k+2147483647&j;break r}f=j;if(f>>>0>>0){break r}f=(j>>>0)%(k>>>0)|0}h=q[q[g+40>>2]+(f<<2)>>2];if(!h){d=c;break q}l=q[h>>2];if(!l){d=c;break q}h=k+ -1|0;s:{while(1){n=q[l+4>>2];t:{if((j|0)!=(n|0)){u:{if(!i){n=h&n;break u}if(n>>>0>>0){break u}n=(n>>>0)%(k>>>0)|0}if((f|0)==(n|0)){break t}d=c;break q}if(q[l+8>>2]==(j|0)){break s}}l=q[l>>2];if(l){continue}break}d=c;break q}f=l+12|0;if((c|0)!=q[g+72>>2]){q[c>>2]=q[f>>2];q[g+68>>2]=d;break q}zi(g- -64|0,f);d=q[g+68>>2];u=q[g+64>>2]}if((d|0)==(u|0)){break c}p=q[d+ -4>>2];f=(p|0)==-1;v=q[B>>2];if(q[q[v+12>>2]+(p<<2)>>2]!=-1?!f:0){break c}i=(z|0)==-1;k=v+12|0;h=q[k>>2];if(q[h+(z<<2)>>2]!=-1?!i:0){break c}x=w(j,3);y=x+2|0;q[h+(p<<2)>>2]=y;u=y<<2;q[u+h>>2]=p;c=x+1|0;q[h+(z<<2)>>2]=c;m=h;h=c<<2;q[m+h>>2]=z;if(f){break j}n=-1;m=q[v>>2];f=m+(x<<2)|0;c=p+((p>>>0)%3|0?-1:2)|0;if((c|0)!=-1){n=q[(c<<2)+m>>2]}q[f>>2]=n;c=p+1|0;c=(c>>>0)%3|0?c:p+ -2|0;if((c|0)==-1){break i}e=q[(c<<2)+m>>2];break i;case 5:break l;case 0:case 2:case 4:break c}}q[g>>2]=w(j,3);d=q[B>>2];f=d+24|0;i=q[d+32>>2];c=d+28|0;d=q[c>>2];v:{if((i|0)!=(d|0)){q[d>>2]=-1;m=d+4|0;q[c>>2]=m;break v}zi(f,11312);m=q[c>>2]}u=q[B>>2];n=q[u>>2];d=q[g>>2];k=m-q[f>>2]|0;y=k>>2;c=y+ -1|0;q[n+(d<<2)>>2]=c;d=d+1|0;i=u+24|0;h=u+28|0;f=q[h>>2];w:{if((f|0)!=q[u+32>>2]){q[f>>2]=-1;m=f+4|0;q[h>>2]=m;break w}zi(i,11312);m=q[h>>2];n=q[u>>2]}q[(d<<2)+n>>2]=(m-q[i>>2]>>2)+ -1;d=q[g>>2]+2|0;i=q[B>>2];f=i+28|0;h=q[f>>2];x:{if((h|0)!=q[i+32>>2]){q[h>>2]=-1;n=h+4|0;q[f>>2]=n;break x}zi(i+24|0,11312);n=q[f>>2]}q[q[i>>2]+(d<<2)>>2]=(n-q[i+24>>2]>>2)+ -1;d=q[B>>2];f=q[d+24>>2];if(q[d+28>>2]-f>>2>(C|0)){break c}d=q[g>>2];y:{z:{if(!k){e=1;q[f+(y<<2)>>2]=d+1;break z}q[f+(c<<2)>>2]=d;e=0;if((k|0)==-4){break z}q[f+(y<<2)>>2]=q[g>>2]+1;e=y+1|0;if((e|0)==-1){break y}}q[f+(e<<2)>>2]=q[g>>2]+2}d=q[g+68>>2];if((d|0)!=q[g+72>>2]){q[d>>2]=q[g>>2];d=d+4|0;q[g+68>>2]=d;break k}zi(g- -64|0,g);d=q[g+68>>2]}c=1;break d}n=-1;m=q[v>>2];q[m+(x<<2)>>2]=-1}q[h+m>>2]=e;A:{B:{C:{if(!i){c=z+((z>>>0)%3|0?-1:2)|0;if((c|0)==-1){break C}c=q[(c<<2)+m>>2];q[u+m>>2]=c;if((c|0)==-1){break B}q[q[v+24>>2]+(c<<2)>>2]=y;break B}q[u+m>>2]=-1;l=-1;e=-1;break A}q[u+m>>2]=-1}l=-1;c=z+1|0;c=(c>>>0)%3|0?c:z+ -2|0;e=-1;if((c|0)==-1){break A}l=q[(c<<2)+m>>2];e=c}q[g>>2]=l;h=q[G>>2];f=n<<2;c=h+f|0;q[c>>2]=q[c>>2]+q[h+(l<<2)>>2];h=q[v+24>>2];if((n|0)!=-1){q[f+h>>2]=q[h+(q[g>>2]<<2)>>2]}D:{if((e|0)==-1){break D}f=q[v>>2];while(1){q[f+(e<<2)>>2]=n;c=e+1|0;c=(c>>>0)%3|0?c:e+ -2|0;if((c|0)==-1){break D}e=q[q[k>>2]+(c<<2)>>2];if((e|0)==-1){break D}c=e+1|0;e=(c>>>0)%3|0?c:e+ -2|0;if((e|0)!=-1){continue}break}}q[h+(q[g>>2]<<2)>>2]=-1;E:{if(E){break E}c=q[g+28>>2];if((c|0)!=q[g+32>>2]){q[c>>2]=q[g>>2];q[g+28>>2]=c+4;break E}zi(g+24|0,g);d=q[g+68>>2]}q[d+ -4>>2]=x;c=0}Pi(A,q[d+ -4>>2]);F:{if(!c){break F}d=q[D>>2];if((d|0)==q[a+36>>2]){break F}h=(j^-1)+b|0;while(1){e=-1;c=q[d+ -8>>2];if(c>>>0>h>>>0){break c}if((c|0)!=(h|0)){break F}c=r[d+ -4|0];d=d+ -12|0;f=q[d>>2];q[D>>2]=d;if((f|0)<0){break c}e=q[q[g+68>>2]+ -4>>2];q[g+20>>2]=(f^-1)+b;q[g+88>>2]=g+20;Bi(g,g+40|0,g+20|0,g+88|0);f=q[g>>2];G:{if(c&1){c=-1;if((e|0)==-1){break G}d=e+1|0;c=(d>>>0)%3|0?d:e+ -2|0;break G}c=-1;if((e|0)==-1){break G}c=e+ -1|0;if((e>>>0)%3){break G}c=e+2|0}q[f+12>>2]=c;d=q[D>>2];if((d|0)!=q[a+36>>2]){continue}break}}j=j+1|0;if((j|0)!=(b|0)){continue}break}h=b}e=-1;l=q[a+8>>2];if(q[l+28>>2]-q[l+24>>2]>>2>(C|0)){break c}d=q[g+68>>2];if((d|0)!=q[g+64>>2]){C=a+72|0;b=a+60|0;y=a+312|0;G=a+352|0;E=a+8|0;D=a+68|0;x=a+80|0;v=a+76|0;while(1){c=d+ -4|0;d=q[c>>2];q[g+68>>2]=c;q[g>>2]=d;H:{I:{J:{K:{if(s[a+270>>1]<=513){if(!r[a+364|0]){break J}c=q[a+360>>2];d=q[G>>2]+(c>>>3)|0;if(d>>>0>=t[a+356>>2]){break I}d=r[d|0];q[a+360>>2]=c+1;c=d>>>(c&7)&1;break K}c=dh(y)}if(!c){break I}}k=q[E>>2];z=q[k>>2];if((h|0)>=((q[k+4>>2]-z>>2>>>0)/3|0)){break c}j=-1;l=-1;i=q[k+24>>2];f=i;A=q[g>>2];d=-1;L:{if((A|0)==-1){break L}c=A+1|0;c=(c>>>0)%3|0?c:A+ -2|0;d=-1;if((c|0)==-1){break L}d=q[z+(c<<2)>>2]}f=q[f+(d<<2)>>2];M:{if((f|0)==-1){break M}c=f+1|0;c=(c>>>0)%3|0?c:f+ -2|0;if((c|0)==-1){break M}j=c+1|0;j=(j>>>0)%3|0?j:c+ -2|0;if((j|0)!=-1){l=q[z+(j<<2)>>2]}j=c}p=-1;m=-1;i=q[i+(l<<2)>>2];f=-1;N:{if((i|0)==-1){break N}c=i+1|0;c=(c>>>0)%3|0?c:i+ -2|0;f=-1;if((c|0)==-1){break N}f=c+1|0;f=(f>>>0)%3|0?f:c+ -2|0;if((f|0)!=-1){m=q[z+(f<<2)>>2]}f=c}c=w(h,3);q[g+88>>2]=c;i=q[k+12>>2];q[i+(c<<2)>>2]=A;q[i+(A<<2)>>2]=c;c=q[g+88>>2]+1|0;q[i+(c<<2)>>2]=j;q[i+(j<<2)>>2]=c;c=q[g+88>>2]+2|0;q[i+(c<<2)>>2]=f;q[i+(f<<2)>>2]=c;c=q[g+88>>2];q[z+(c<<2)>>2]=l;u=c+1|0;k=z+(u<<2)|0;q[k>>2]=m;i=c+2|0;f=z+(i<<2)|0;q[f>>2]=d;A=q[a+120>>2];j=u>>>0>>0?-1:l;c=A+(j>>>3&536870908)|0;d=q[c>>2];H=c,I=eo(j)&d,q[H>>2]=I;p=(u|0)!=-1?q[k>>2]:p;c=A+(p>>>3&536870908)|0;d=q[c>>2];H=c,I=eo(p)&d,q[H>>2]=I;d=-1;d=(i|0)!=-1?q[f>>2]:d;j=A+(d>>>3&536870908)|0;c=q[j>>2];H=j,I=eo(d)&c,q[H>>2]=I;d=q[a+64>>2];f=q[D>>2];if((d|0)==f<<5){if((d+1|0)<=-1){break a}c=b;if(d>>>0<=1073741822){j=d+32&-32;d=f<<6;d=d>>>0>>0?j:d}else{d=2147483647}cb(c,d);d=q[a+64>>2]}h=h+1|0;q[a+64>>2]=d+1;c=q[a+60>>2]+(d>>>3&536870908)|0;q[c>>2]=q[c>>2]|1<<(d&31);d=q[v>>2];if((d|0)!=q[x>>2]){q[d>>2]=q[g+88>>2];q[v>>2]=d+4;break H}zi(C,g+88|0);break H}d=q[a+64>>2];f=q[D>>2];if((d|0)==f<<5){if((d+1|0)<=-1){break a}c=b;if(d>>>0<=1073741822){j=d+32&-32;d=f<<6;d=d>>>0>>0?j:d}else{d=2147483647}cb(c,d);d=q[a+64>>2]}q[a+64>>2]=d+1;j=q[a+60>>2]+(d>>>3&536870908)|0;c=q[j>>2];H=j,I=eo(d)&c,q[H>>2]=I;d=q[v>>2];if((d|0)!=q[x>>2]){q[d>>2]=q[g>>2];q[v>>2]=d+4;break H}zi(C,g)}d=q[g+68>>2];if((d|0)!=q[g+64>>2]){continue}break}l=q[a+8>>2]}if(((q[l+4>>2]-q[l>>2]>>2>>>0)/3|0)!=(h|0)){break c}e=q[l+28>>2]-q[l+24>>2]>>2;b=q[g+24>>2];i=q[g+28>>2];if((b|0)==(i|0)){break b}f=a+8|0;while(1){k=q[b>>2];h=q[l+24>>2];d=e+ -1|0;O:{if(q[h+(d<<2)>>2]!=-1){j=e;break O}h=q[l+24>>2];while(1){d=e+ -2|0;j=e+ -1|0;e=j;if(q[(d<<2)+h>>2]==-1){continue}break}}if(d>>>0>=k>>>0){q[g>>2]=l;c=d<<2;e=q[c+h>>2];o[g+12|0]=1;q[g+8>>2]=e;q[g+4>>2]=e;if((e|0)!=-1){while(1){q[q[l>>2]+(e<<2)>>2]=k;lg(g);l=q[f>>2];e=q[g+8>>2];if((e|0)!=-1){continue}break}}e=c;c=q[l+24>>2];e=e+c|0;if((k|0)!=-1){q[c+(k<<2)>>2]=q[e>>2]}q[e>>2]=-1;E=1<<(k&31);e=q[a+120>>2];k=e+(k>>>3&536870908)|0;c=k;h=e+(d>>>3&536870908)|0;d=1<<(d&31);e=E|q[k>>2];P:{if(q[h>>2]&d){break P}e=q[k>>2]&(E^-1)}q[c>>2]=e;q[h>>2]=q[h>>2]&(d^-1);j=j+ -1|0}e=j;b=b+4|0;if((i|0)!=(b|0)){continue}break}}b=q[g+24>>2]}if(b){q[g+28>>2]=b;An(b)}d=q[g+48>>2];if(d){while(1){a=q[d>>2];An(d);d=a;if(d){continue}break}}a=q[g+40>>2];q[g+40>>2]=0;if(a){An(a)}a=q[g+64>>2];if(a){q[g+68>>2]=a;An(a)}T=g+96|0;return e}bn();F()}function Ni(a,b){var o=0,r=0,s=0,t=0,J=0,K=0,L=0,M=0,N=0;s=q[a+8>>2];t=a+4|0;o=q[t>>2];if((s-o|0)/12>>>0>=b>>>0){a=w(b,12);M=t,N=Dn(o,0,a)+a|0,q[M>>2]=N;return}a:{t=q[a>>2];r=(o-t|0)/12|0;J=r+b|0;if(J>>>0<357913942){L=w(r,12);s=(s-t|0)/12|0;r=s<<1;r=s>>>0<178956970?r>>>0>>0?J:r:357913941;if(r){if(r>>>0>=357913942){break a}K=Mm(w(r,12))}s=K+L|0;Dn(s,0,w(b,12));b=w(J,12)+K|0;J=w(r,12)+K|0;if((o|0)!=(t|0)){while(1){s=s+ -12|0;q[s>>2]=0;q[s+4>>2]=0;r=s+8|0;q[r>>2]=0;o=o+ -12|0;q[s>>2]=q[o>>2];q[s+4>>2]=q[o+4>>2];K=r;r=o+8|0;q[K>>2]=q[r>>2];q[r>>2]=0;q[o>>2]=0;q[o+4>>2]=0;if((o|0)!=(t|0)){continue}break}t=q[a>>2];o=q[a+4>>2]}q[a>>2]=s;q[a+8>>2]=J;q[a+4>>2]=b;if((o|0)!=(t|0)){while(1){a=o+ -12|0;b=q[a>>2];if(b){q[o+ -8>>2]=b;An(b)}o=a;if((o|0)!=(t|0)){continue}break}}if(t){An(t)}return}bn();F()}ab(12024);F()}function Oi(a){var b=0,F=0,O=0,P=0,Q=0,R=0,S=0;b=q[a+172>>2];if((b|0)!=-1){F=q[a+196>>2]+(b<<2)|0;O=q[F>>2];b=O+ -1|0;q[F>>2]=b;if((O|0)<1){return 9}F=a;a=q[(q[q[q[a+184>>2]+w(q[a+172>>2],12)>>2]+(b<<2)>>2]<<2)+12096>>2];q[F+168>>2]=a;return a}b=7;F=q[a+144>>2];F=s[(n[q[q[F>>2]+32>>2]](F)|0)+36>>1];a:{if((F<<24|F<<8&16711680)>>>16>>>0>513){break a}if(!r[a+76|0]){q[a+168>>2]=1;return 1}b=0;Q=q[a- -64>>2];O=q[a+72>>2];F=Q+(O>>>3)|0;R=q[a+68>>2];if(F>>>0>=R>>>0){break a}P=r[F|0];F=O+1|0;q[a+72>>2]=F;if(!(P>>>(O&7)&1)){break a}P=F>>>3;b=Q+P|0;b:{if(b>>>0>=R>>>0){b=F;F=0;break b}S=r[b|0];b=O+2|0;q[a+72>>2]=b;P=b>>>3;F=S>>>(F&7)&1}O=P+Q|0;if(O>>>0>>0){O=r[O|0];q[a+72>>2]=b+1;b=O>>>(b&7)<<1&2}else{b=0}b=(F|b)<<1|1}q[a+168>>2]=b;return b}function Pi(a,w){var T=0,U=0,V=0,W=0,X=0;W=-1;U=-1;a:{if((w|0)==-1){break a}U=w+1|0;W=(U>>>0)%3|0?U:w+ -2|0;U=w+ -1|0;if((w>>>0)%3){break a}U=w+2|0}T=q[a+168>>2];b:{if(T>>>0>7){break b}c:{d:{switch(T-2|0){default:T=q[a+148>>2];V=1;w=q[a+156>>2];X=w+(((W|0)!=-1?q[q[T>>2]+(W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(w){w=Z+(w<<4)|0;while(1){w=w+ -16|0;if((Z|0)!=(w|0)){continue}break}}An(Y)}Z=q[a+216>>2];if(Z){$=a+220|0;w=q[$>>2];Y=Z;a:{if((Z|0)==(w|0)){break a}while(1){Y=q[w+ -12>>2];if(Y){q[w+ -8>>2]=Y;An(Y)}Y=q[w+ -28>>2];if(Y){q[w+ -24>>2]=Y;An(Y)}Y=w+ -144|0;_=q[w+ -40>>2];if(_){q[w+ -36>>2]=_;An(_)}pi(w+ -140|0);w=Y;if((Z|0)!=(w|0)){continue}break}Y=q[a+216>>2]}q[$>>2]=Z;An(Y)}w=q[a+196>>2];if(w){q[a+200>>2]=w;An(w)}w=q[a+184>>2];if(w){q[a+188>>2]=w;An(w)}w=q[a+172>>2];if(w){q[a+176>>2]=w;An(w)}w=q[a+160>>2];if(w){q[a+164>>2]=w;An(w)}w=q[a+144>>2];if(w){while(1){Z=q[w>>2];An(w);w=Z;if(w){continue}break}}Z=a+136|0;w=q[Z>>2];q[Z>>2]=0;if(w){An(w)}w=q[a+120>>2];if(w){An(w)}w=q[a+108>>2];if(w){An(w)}w=q[a+96>>2];if(w){An(w)}w=q[a+72>>2];if(w){q[a+76>>2]=w;An(w)}w=q[a+60>>2];if(w){An(w)}w=q[a+48>>2];if(w){q[a+52>>2]=w;An(w)}w=q[a+36>>2];if(w){q[a+40>>2]=w;An(w)}w=q[a+24>>2];if(w){q[a+28>>2]=w;An(w)}w=q[a+12>>2];if(w){q[a+16>>2]=w;An(w)}w=q[a+8>>2];q[a+8>>2]=0;if(w){wa(a+8|0,w)}return a|0}function Ri(a){a=a|0;An(Qi(a))}function Si(a){a=a|0;var aa=0,ba=0,ca=0,da=0,ea=0;q[a>>2]=11324;aa=q[a+388>>2];if(aa){q[a+392>>2]=aa;An(aa)}aa=a+368|0;ca=q[aa>>2];q[aa>>2]=0;if(ca){ba=ca+ -4|0;aa=q[ba>>2];if(aa){aa=ca+(aa<<4)|0;while(1){aa=aa+ -16|0;if((ca|0)!=(aa|0)){continue}break}}An(ba)}ca=q[a+216>>2];if(ca){ea=a+220|0;aa=q[ea>>2];ba=ca;a:{if((ca|0)==(aa|0)){break a}while(1){ba=q[aa+ -12>>2];if(ba){q[aa+ -8>>2]=ba;An(ba)}ba=q[aa+ -28>>2];if(ba){q[aa+ -24>>2]=ba;An(ba)}ba=aa+ -144|0;da=q[aa+ -40>>2];if(da){q[aa+ -36>>2]=da;An(da)}pi(aa+ -140|0);aa=ba;if((ca|0)!=(aa|0)){continue}break}ba=q[a+216>>2]}q[ea>>2]=ca;An(ba)}aa=q[a+196>>2];if(aa){q[a+200>>2]=aa;An(aa)}aa=q[a+184>>2];if(aa){q[a+188>>2]=aa;An(aa)}aa=q[a+172>>2];if(aa){q[a+176>>2]=aa;An(aa)}aa=q[a+160>>2];if(aa){q[a+164>>2]=aa;An(aa)}aa=q[a+144>>2];if(aa){while(1){ca=q[aa>>2];An(aa);aa=ca;if(aa){continue}break}}ca=a+136|0;aa=q[ca>>2];q[ca>>2]=0;if(aa){An(aa)}aa=q[a+120>>2];if(aa){An(aa)}aa=q[a+108>>2];if(aa){An(aa)}aa=q[a+96>>2];if(aa){An(aa)}aa=q[a+72>>2];if(aa){q[a+76>>2]=aa;An(aa)}aa=q[a+60>>2];if(aa){An(aa)}aa=q[a+48>>2];if(aa){q[a+52>>2]=aa;An(aa)}aa=q[a+36>>2];if(aa){q[a+40>>2]=aa;An(aa)}aa=q[a+24>>2];if(aa){q[a+28>>2]=aa;An(aa)}aa=q[a+12>>2];if(aa){q[a+16>>2]=aa;An(aa)}aa=q[a+8>>2];q[a+8>>2]=0;if(aa){wa(a+8|0,aa)}return a|0}function Ti(a){a=a|0;An(Si(a))}function Ui(a){a=a|0;var fa=0,ga=0,ha=0,ia=0,ja=0;q[a>>2]=11372;Vi(a+232|0);ia=q[a+216>>2];if(ia){ga=ia;ja=a+220|0;fa=q[ja>>2];ha=ga;a:{if((ga|0)==(fa|0)){break a}while(1){ga=q[fa+ -12>>2];if(ga){q[fa+ -8>>2]=ga;An(ga)}ga=q[fa+ -28>>2];if(ga){q[fa+ -24>>2]=ga;An(ga)}ga=fa+ -144|0;ha=q[fa+ -40>>2];if(ha){q[fa+ -36>>2]=ha;An(ha)}pi(fa+ -140|0);fa=ga;if((ia|0)!=(fa|0)){continue}break}ha=q[a+216>>2]}ga=ha;q[ja>>2]=ia;An(ga)}fa=q[a+196>>2];if(fa){q[a+200>>2]=fa;An(fa)}fa=q[a+184>>2];if(fa){q[a+188>>2]=fa;An(fa)}fa=q[a+172>>2];if(fa){q[a+176>>2]=fa;An(fa)}fa=q[a+160>>2];if(fa){q[a+164>>2]=fa;An(fa)}fa=q[a+144>>2];if(fa){while(1){ga=q[fa>>2];An(fa);fa=ga;if(fa){continue}break}}fa=a+136|0;ga=q[fa>>2];q[fa>>2]=0;if(ga){An(ga)}fa=q[a+120>>2];if(fa){An(fa)}fa=q[a+108>>2];if(fa){An(fa)}fa=q[a+96>>2];if(fa){An(fa)}fa=q[a+72>>2];if(fa){q[a+76>>2]=fa;An(fa)}fa=q[a+60>>2];if(fa){An(fa)}fa=q[a+48>>2];if(fa){q[a+52>>2]=fa;An(fa)}fa=q[a+36>>2];if(fa){q[a+40>>2]=fa;An(fa)}fa=q[a+24>>2];if(fa){q[a+28>>2]=fa;An(fa)}fa=q[a+12>>2];if(fa){q[a+16>>2]=fa;An(fa)}fa=q[a+8>>2];q[a+8>>2]=0;if(fa){wa(a+8|0,fa)}return a|0}function Vi(a){var ka=0,la=0,ma=0,na=0,oa=0;ka=q[a+196>>2];if(ka){q[a+200>>2]=ka;An(ka)}ka=q[a+184>>2];if(ka){oa=a+188|0;la=q[oa>>2];ma=ka;a:{if((ka|0)==(la|0)){break a}while(1){ma=la+ -12|0;na=q[ma>>2];if(na){q[la+ -8>>2]=na;An(na)}la=ma;if((la|0)!=(ka|0)){continue}break}ma=q[a+184>>2]}q[oa>>2]=ka;An(ma)}ka=q[a+156>>2];if(ka){q[a+160>>2]=ka;An(ka)}ka=a+136|0;a=q[ka>>2];q[ka>>2]=0;if(a){la=a+ -4|0;ka=q[la>>2];if(ka){ka=a+(ka<<4)|0;while(1){ka=ka+ -16|0;if((a|0)!=(ka|0)){continue}break}}An(la)}}function Wi(a){a=a|0;An(Ui(a))}function Xi(a){a=a|0;var pa=0;q[a>>2]=11760;pa=q[a+48>>2];if(pa){q[a+52>>2]=pa;An(pa)}q[a>>2]=12012;pa=q[a+36>>2];if(pa){An(pa)}pa=q[a+24>>2];if(pa){An(pa)}An(a)}function Yi(a){a=a|0;var qa=0;q[a>>2]=12012;qa=q[a+36>>2];if(qa){An(qa)}qa=q[a+24>>2];if(qa){An(qa)}return a|0}function Zi(a){a=a|0;var ra=0;q[a>>2]=12012;ra=q[a+36>>2];if(ra){An(ra)}ra=q[a+24>>2];if(ra){An(ra)}An(a)}function _i(a,sa,ta){a=a|0;sa=sa|0;ta=ta|0;var ua=0,va=0;ua=T-16|0;T=ua;q[a+4>>2]=sa;va=q[sa+4>>2];sa=q[sa>>2];o[ua+15|0]=0;bb(a+24|0,(va-sa>>2>>>0)/3|0,ua+15|0);sa=q[a+4>>2];va=q[sa+28>>2];sa=q[sa+24>>2];o[ua+14|0]=0;bb(a+36|0,va-sa>>2,ua+14|0);sa=q[ta+12>>2];q[a+16>>2]=q[ta+8>>2];q[a+20>>2]=sa;sa=q[ta+4>>2];q[a+8>>2]=q[ta>>2];q[a+12>>2]=sa;T=ua+16|0}function $i(a,sa){var ta=0,wa=0,xa=0;a:{if((a|0)!=(sa|0)){xa=a;ta=q[sa+4>>2];wa=0;b:{if(!ta){break b}c:{if(ta>>>0<=q[a+8>>2]<<5>>>0){wa=q[a>>2];break c}wa=q[a>>2];if(wa){An(wa);q[a+8>>2]=0;q[a>>2]=0;q[a+4>>2]=0;ta=q[sa+4>>2]}if((ta|0)<=-1){break a}ta=(ta+ -1>>>5)+1|0;wa=Mm(ta<<2);q[a+8>>2]=ta;q[a+4>>2]=0;q[a>>2]=wa;ta=q[sa+4>>2]}En(wa,q[sa>>2],(ta+ -1>>>3&536870908)+4|0);wa=q[sa+4>>2]}q[xa+4>>2]=wa}return}bn();F()}function aj(a){a=a|0;var sa=0;q[a>>2]=12336;sa=q[a+88>>2];if(sa){q[a+92>>2]=sa;An(sa)}sa=q[a+72>>2];if(sa){q[a+76>>2]=sa;An(sa)}sa=q[a+60>>2];if(sa){q[a- -64>>2]=sa;An(sa)}sa=q[a+48>>2];if(sa){q[a+52>>2]=sa;An(sa)}q[a>>2]=12572;sa=q[a+36>>2];if(sa){An(sa)}sa=q[a+24>>2];if(sa){An(sa)}return a|0}function bj(a){a=a|0;var ya=0;q[a>>2]=12124;q[a+8>>2]=12336;ya=q[a+96>>2];if(ya){q[a+100>>2]=ya;An(ya)}ya=q[a+80>>2];if(ya){q[a+84>>2]=ya;An(ya)}ya=q[a+68>>2];if(ya){q[a+72>>2]=ya;An(ya)}ya=q[a+56>>2];if(ya){q[a+60>>2]=ya;An(ya)}q[a+8>>2]=12572;ya=q[a+44>>2];if(ya){An(ya)}ya=q[a+32>>2];if(ya){An(ya)}return a|0}function cj(a){a=a|0;var za=0;q[a>>2]=12124;q[a+8>>2]=12336;za=q[a+96>>2];if(za){q[a+100>>2]=za;An(za)}za=q[a+80>>2];if(za){q[a+84>>2]=za;An(za)}za=q[a+68>>2];if(za){q[a+72>>2]=za;An(za)}za=q[a+56>>2];if(za){q[a+60>>2]=za;An(za)}q[a+8>>2]=12572;za=q[a+44>>2];if(za){An(za)}za=q[a+32>>2];if(za){An(za)}An(a)}function dj(a,Aa){a=a|0;Aa=Aa|0;var Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0;Ja=q[a+12>>2];Ba=q[a+108>>2];Ca=q[Ba+80>>2];o[Aa+84|0]=0;Fa=q[Aa+68>>2];Da=q[Aa+72>>2]-Fa>>2;a:{if(Ca>>>0>Da>>>0){md(Aa+68|0,Ca-Da|0,12324);Ba=q[a+108>>2];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a|0)>=1){Cn(Na,Aa,Oa)}q[Ma>>2]=Na;q[Ma+8>>2]=Ra;q[Ta>>2]=Qa;if(!Aa){break b}An(Aa)}Aa=q[Sa>>2];Ma=q[Aa+24>>2];Aa=q[Aa+28>>2];q[Pa+12>>2]=0;Aa=Aa-Ma>>2;Na=a+96|0;Oa=q[Na>>2];Ma=q[a+100>>2]-Oa>>2;c:{if(Aa>>>0>Ma>>>0){Ad(Na,Aa-Ma|0,Pa+12|0);break c}if(Aa>>>0>=Ma>>>0){break c}q[a+100>>2]=Oa+(Aa<<2)}Oa=a+8|0;d:{e:{Aa=q[a+116>>2];if(Aa){Na=q[Aa>>2];Ma=1;if((Na|0)==q[Aa+4>>2]){break d}Aa=0;while(1){if(!fj(Oa,q[(Aa<<2)+Na>>2])){break e}Ma=q[a+116>>2];Na=q[Ma>>2];Aa=Aa+1|0;if(Aa>>>0>2]-Na>>2>>>0){continue}break}Ma=1;break d}Aa=0;a=q[a+12>>2];a=(q[a+4>>2]-q[a>>2]>>2>>>0)/3|0;Ma=1;if((a|0)<=0){break d}while(1){if(!fj(Oa,w(Aa,3))){break e}Aa=Aa+1|0;if(Aa>>>0>>0){continue}break}Ma=1;break d}Ma=0}T=Pa+16|0;return Ma|0}ab(12024);F()}function fj(a,Ua){var Va=0,Wa=0,Xa=0,Ya=0,Za=0,_a=0,$a=0,ab=0,bb=0,cb=0,db=0,eb=0,fb=0;Ya=T-32|0;T=Ya;q[Ya+8>>2]=Ua;a:{if(q[a+92>>2]==q[a+88>>2]){break a}Xa=a+52|0;Va=q[Xa>>2];b:{if((Va|0)!=q[a+56>>2]){q[Va>>2]=Ua;q[Xa>>2]=Va+4;break b}zi(a+48|0,Ya+8|0)}q[a+84>>2]=0;Ua=-1;Xa=-1;Va=q[Ya+8>>2];c:{if((Va|0)==-1){break c}Wa=q[a+4>>2];Za=Va+1|0;Za=(Za>>>0)%3|0?Za:Va+ -2|0;if((Za|0)!=-1){Ua=q[q[Wa>>2]+(Za<<2)>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/3|0;bb=(Va>>>0)/3|0;ab=(Va|0)==-1;Xa=1;p:{if(ab){break p}Xa=ab?-1:bb;Xa=q[q[Za>>2]+(Xa>>>3&536870908)>>2]>>>(Xa&31)&1}q:{r:{s:{if((Ua|0)==-1){if(!Xa){break s}break m}Wa=(Ua|0)==-1?-1:Wa;t:{if(q[q[Za>>2]+(Wa>>>3&536870908)>>2]>>>(Wa&31)&1){break t}Wa=0;ab=Xa;_a=q[q[_a>>2]+(Ua<<2)>>2];if(!(q[q[$a>>2]+(_a>>>3&536870908)>>2]>>>(_a&31)&1)){_a=q[cb>>2]+(_a<<2)|0;Wa=q[_a>>2];q[_a>>2]=Wa+1;Wa=(Wa|0)<1?2:1}if((Wa|0)<=q[a+84>>2]?ab:0){break r}q[Ya+24>>2]=Ua;bb=w(Wa,12)+a|0;ab=bb+52|0;_a=q[ab>>2];u:{if((_a|0)!=q[bb+56>>2]){q[_a>>2]=Ua;q[ab>>2]=_a+4;break u}zi(bb+48|0,Ya+24|0)}if(q[a+84>>2]<=(Wa|0)){break t}q[a+84>>2]=Wa}if(Xa){break m}}Ua=-1;Xa=0;Ua=(Va|0)!=-1?q[q[q[db>>2]>>2]+(Va<<2)>>2]:Ua;if(!(q[q[$a>>2]+(Ua>>>3&536870908)>>2]>>>(Ua&31)&1)){Xa=q[cb>>2]+(Ua<<2)|0;Ua=q[Xa>>2];q[Xa>>2]=Ua+1;Xa=(Ua|0)<1?2:1}if((Xa|0)>q[a+84>>2]){break q}Ua=Va}q[Ya+8>>2]=Ua;Xa=q[Za>>2];continue}break}q[Ya+24>>2]=Va;Wa=w(Xa,12)+a|0;_a=Wa+52|0;Ua=q[_a>>2];v:{if((Ua|0)!=q[Wa+56>>2]){q[Ua>>2]=Va;q[_a>>2]=Ua+4;break v}zi(Wa+48|0,Ya+24|0)}Va=q[a+84>>2];if((Va|0)<=(Xa|0)){break l}q[a+84>>2]=Xa;Va=Xa;break l}Va=q[a+84>>2]}if((Va|0)<3){continue}break}}q[Ya+8>>2]=-1}T=Ya+32|0;return 1}function gj(a){a=a|0;var Ua=0;q[a>>2]=12336;Ua=q[a+88>>2];if(Ua){q[a+92>>2]=Ua;An(Ua)}Ua=q[a+72>>2];if(Ua){q[a+76>>2]=Ua;An(Ua)}Ua=q[a+60>>2];if(Ua){q[a- -64>>2]=Ua;An(Ua)}Ua=q[a+48>>2];if(Ua){q[a+52>>2]=Ua;An(Ua)}q[a>>2]=12572;Ua=q[a+36>>2];if(Ua){An(Ua)}Ua=q[a+24>>2];if(Ua){An(Ua)}An(a)}function hj(a){a=a|0;var gb=0;q[a>>2]=12572;gb=q[a+36>>2];if(gb){An(gb)}gb=q[a+24>>2];if(gb){An(gb)}return a|0}function ij(a){a=a|0;var hb=0;q[a>>2]=12572;hb=q[a+36>>2];if(hb){An(hb)}hb=q[a+24>>2];if(hb){An(hb)}An(a)}function jj(a){a=a|0;var ib=0;q[a>>2]=12756;ib=q[a+48>>2];if(ib){q[a+52>>2]=ib;An(ib)}q[a>>2]=12572;ib=q[a+36>>2];if(ib){An(ib)}ib=q[a+24>>2];if(ib){An(ib)}return a|0}function kj(a){a=a|0;var jb=0,kb=0;q[a>>2]=12592;kb=a+8|0;q[kb>>2]=12756;jb=q[a+56>>2];if(jb){q[a+60>>2]=jb;An(jb)}q[kb>>2]=12572;jb=q[a+44>>2];if(jb){An(jb)}jb=q[a+32>>2];if(jb){An(jb)}return a|0}function lj(a){a=a|0;var lb=0,mb=0;q[a>>2]=12592;mb=a+8|0;q[mb>>2]=12756;lb=q[a+56>>2];if(lb){q[a+60>>2]=lb;An(lb)}q[mb>>2]=12572;lb=q[a+44>>2];if(lb){An(lb)}lb=q[a+32>>2];if(lb){An(lb)}An(a)}function mj(a,nb){a=a|0;nb=nb|0;var ob=0,pb=0,qb=0,rb=0,sb=0,tb=0,ub=0,vb=0,wb=0,xb=0,yb=0;wb=q[a+12>>2];ob=q[a+68>>2];pb=q[ob+80>>2];o[nb+84|0]=0;sb=q[nb+68>>2];qb=q[nb+72>>2]-sb>>2;a:{if(pb>>>0>qb>>>0){md(nb+68|0,pb-qb|0,12324);ob=q[a+68>>2];pb=q[ob+80>>2];break a}if(pb>>>0>=qb>>>0){break a}q[nb+72>>2]=sb+(pb<<2)}vb=q[ob+96>>2];ob=q[ob+100>>2]-vb|0;xb=(ob|0)/12|0;if(!ob){return 1}yb=nb+68|0;nb=0;b:{while(1){c:{if((nb|0)==1431655765){break c}ob=q[wb>>2]+(w(nb,3)<<2)|0;sb=q[ob>>2];if((sb|0)==-1){break c}qb=w(nb,12)+vb|0;tb=q[qb>>2];if(tb>>>0>=pb>>>0){break c}rb=sb<<2;sb=q[q[a+72>>2]+12>>2];rb=q[rb+sb>>2];if(rb>>>0>=pb>>>0){break c}ub=tb<<2;tb=q[yb>>2];q[ub+tb>>2]=rb;rb=q[ob+4>>2];if((rb|0)==-1){break c}ub=q[qb+4>>2];if(ub>>>0>=pb>>>0){break c}rb=q[sb+(rb<<2)>>2];if(rb>>>0>=pb>>>0){break c}q[tb+(ub<<2)>>2]=rb;ob=q[ob+8>>2];if((ob|0)==-1){break c}qb=q[qb+8>>2];if(qb>>>0>=pb>>>0){break c}ob=q[sb+(ob<<2)>>2];if(ob>>>0>=pb>>>0){break c}q[tb+(qb<<2)>>2]=ob;ob=1;nb=nb+1|0;if(nb>>>0>>0){continue}break b}break}ob=0}return ob|0}function nj(a){a=a|0;var nb=0,zb=0,Ab=0,Bb=0,Cb=0,Db=0,Eb=0;Bb=q[a+4>>2];nb=q[Bb>>2];a:{zb=q[a+12>>2];Ab=q[zb+28>>2]-q[zb+24>>2]|0;zb=Ab>>2;b:{if(q[Bb+8>>2]-nb>>2>>>0>=zb>>>0){break b}if(zb>>>0>=1073741824){break a}Eb=Bb+4|0;Cb=q[Eb>>2];Db=zb<<2;zb=Mm(Ab);Db=Db+zb|0;Ab=Cb-nb|0;Cb=Ab+zb|0;if((Ab|0)>=1){Cn(zb,nb,Ab)}q[Bb>>2]=zb;q[Bb+8>>2]=Db;q[Eb>>2]=Cb;if(!nb){break b}An(nb)}zb=a+8|0;c:{d:{nb=q[a+76>>2];if(nb){Bb=q[nb>>2];Ab=1;if((Bb|0)==q[nb+4>>2]){break c}nb=0;while(1){if(!oj(zb,q[(nb<<2)+Bb>>2])){break d}Ab=q[a+76>>2];Bb=q[Ab>>2];nb=nb+1|0;if(nb>>>0>2]-Bb>>2>>>0){continue}break}return 1}nb=0;a=q[a+12>>2];a=(q[a+4>>2]-q[a>>2]>>2>>>0)/3|0;if((a|0)<=0){return 1}while(1){if(!oj(zb,w(nb,3))){break d}nb=nb+1|0;if(nb>>>0>>0){continue}break}return 1}Ab=0}return Ab|0}ab(12024);F()}function oj(a,Fb){var Gb=0,Hb=0,Ib=0,Jb=0,Kb=0,Lb=0,Mb=0,Nb=0,Ob=0,Pb=0,Qb=0,Rb=0,Sb=0,Tb=0,Ub=0;Kb=T-32|0;T=Kb;q[Kb+8>>2]=Fb;a:{if((Fb|0)==-1){Jb=1;break a}Jb=1;Gb=(Fb>>>0)/3|0;if(q[q[a+24>>2]+(Gb>>>3&268435452)>>2]>>>(Gb&31)&1){break a}Gb=a+52|0;Ib=q[a+48>>2];q[Gb>>2]=Ib;Pb=a+48|0;b:{if((Ib|0)!=q[a+56>>2]){q[Ib>>2]=Fb;q[Gb>>2]=Ib+4;break b}zi(Pb,Kb+8|0)}Jb=-1;Ib=q[Kb+8>>2];if((Ib|0)==-1){Jb=0;break a}Gb=q[a+4>>2];Fb=Ib+1|0;Fb=(Fb>>>0)%3|0?Fb:Ib+ -2|0;if((Fb|0)!=-1){Jb=q[q[Gb>>2]+(Fb<<2)>>2]}Fb=Ib+((Ib>>>0)%3|0?-1:2)|0;if((Fb|0)==-1){Jb=0;break a}if((Jb|0)==-1){Jb=0;break a}Lb=q[q[Gb>>2]+(Fb<<2)>>2];if((Lb|0)==-1){Jb=0;break a}Fb=q[a+36>>2];Hb=Fb+(Jb>>>3&536870908)|0;Ib=q[Hb>>2];Gb=1<<(Jb&31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>2]=Hb;if((Fb|0)==q[Ub>>2]){break m}q[Fb>>2]=q[Kb+24>>2];q[Nb>>2]=Fb+4;break h}if(Gb){break k}}q[Kb+8>>2]=Jb}Gb=q[Ob>>2]+(Fb>>>3&536870908)|0;q[Gb>>2]=q[Gb>>2]|1<<(Fb&31);Fb=q[Kb+8>>2];if((Fb|0)!=-1){continue}break}Jb=0;break a}zi(Pb,Kb+24|0);break h}q[Kb+24>>2]=-1}q[Nb>>2]=q[Nb>>2]+ -4}Jb=1;Fb=q[Nb>>2];if((Fb|0)!=q[a+48>>2]){continue}break}}T=Kb+32|0;return Jb}function pj(a){a=a|0;var Fb=0;q[a>>2]=12756;Fb=q[a+48>>2];if(Fb){q[a+52>>2]=Fb;An(Fb)}q[a>>2]=12572;Fb=q[a+36>>2];if(Fb){An(Fb)}Fb=q[a+24>>2];if(Fb){An(Fb)}An(a)}function qj(a){a=a|0;var Vb=0,Wb=0;q[a>>2]=12884;Wb=a+8|0;q[Wb>>2]=11760;Vb=q[a+56>>2];if(Vb){q[a+60>>2]=Vb;An(Vb)}q[Wb>>2]=12012;Vb=q[a+44>>2];if(Vb){An(Vb)}Vb=q[a+32>>2];if(Vb){An(Vb)}return a|0}function rj(a){a=a|0;var Xb=0,Yb=0;q[a>>2]=12884;Yb=a+8|0;q[Yb>>2]=11760;Xb=q[a+56>>2];if(Xb){q[a+60>>2]=Xb;An(Xb)}q[Yb>>2]=12012;Xb=q[a+44>>2];if(Xb){An(Xb)}Xb=q[a+32>>2];if(Xb){An(Xb)}An(a)}function sj(a,Zb){a=a|0;Zb=Zb|0;var _b=0,$b=0,ac=0,bc=0,cc=0,dc=0,ec=0,fc=0,gc=0,hc=0,ic=0;dc=q[a+12>>2];_b=q[a+68>>2];$b=q[_b+80>>2];o[Zb+84|0]=0;cc=q[Zb+68>>2];ac=q[Zb+72>>2]-cc>>2;a:{if($b>>>0>ac>>>0){md(Zb+68|0,$b-ac|0,12324);_b=q[a+68>>2];$b=q[_b+80>>2];break a}if($b>>>0>=ac>>>0){break a}q[Zb+72>>2]=cc+($b<<2)}fc=q[_b+96>>2];_b=q[_b+100>>2]-fc|0;gc=(_b|0)/12|0;if(!_b){return 1}hc=q[dc+28>>2];ic=Zb+68|0;Zb=0;b:{while(1){c:{_b=(w(Zb,3)<<2)+hc|0;dc=q[_b>>2];if((dc|0)==-1){break c}ac=w(Zb,12)+fc|0;cc=q[ac>>2];if(cc>>>0>=$b>>>0){break c}bc=dc<<2;dc=q[q[a+72>>2]+12>>2];bc=q[bc+dc>>2];if(bc>>>0>=$b>>>0){break c}ec=cc<<2;cc=q[ic>>2];q[ec+cc>>2]=bc;bc=q[_b+4>>2];if((bc|0)==-1){break c}ec=q[ac+4>>2];if(ec>>>0>=$b>>>0){break c}bc=q[dc+(bc<<2)>>2];if(bc>>>0>=$b>>>0){break c}q[cc+(ec<<2)>>2]=bc;_b=q[_b+8>>2];if((_b|0)==-1){break c}ac=q[ac+8>>2];if(ac>>>0>=$b>>>0){break c}_b=q[dc+(_b<<2)>>2];if(_b>>>0>=$b>>>0){break c}q[cc+(ac<<2)>>2]=_b;_b=1;Zb=Zb+1|0;if(Zb>>>0>>0){continue}break b}break}_b=0}return _b|0}function tj(a){a=a|0;var Zb=0,jc=0,kc=0,lc=0,mc=0,nc=0,oc=0;lc=q[a+4>>2];Zb=q[lc>>2];a:{jc=q[a+12>>2];kc=q[jc+56>>2]-q[jc+52>>2]|0;jc=kc>>2;b:{if(q[lc+8>>2]-Zb>>2>>>0>=jc>>>0){break b}if(jc>>>0>=1073741824){break a}oc=lc+4|0;mc=q[oc>>2];nc=jc<<2;jc=Mm(kc);nc=nc+jc|0;kc=mc-Zb|0;mc=kc+jc|0;if((kc|0)>=1){Cn(jc,Zb,kc)}q[lc>>2]=jc;q[lc+8>>2]=nc;q[oc>>2]=mc;if(!Zb){break b}An(Zb)}jc=a+8|0;c:{d:{Zb=q[a+76>>2];if(Zb){lc=q[Zb>>2];kc=1;if((lc|0)==q[Zb+4>>2]){break c}Zb=0;while(1){if(!uj(jc,q[(Zb<<2)+lc>>2])){break d}kc=q[a+76>>2];lc=q[kc>>2];Zb=Zb+1|0;if(Zb>>>0>2]-lc>>2>>>0){continue}break}return 1}Zb=0;a=q[q[a+12>>2]+64>>2];a=(q[a+4>>2]-q[a>>2]>>2>>>0)/3|0;if((a|0)<=0){return 1}while(1){if(!uj(jc,w(Zb,3))){break d}Zb=Zb+1|0;if(Zb>>>0>>0){continue}break}return 1}kc=0}return kc|0}ab(12024);F()}function uj(a,pc){var qc=0,rc=0,sc=0,tc=0,uc=0,vc=0,wc=0,xc=0,yc=0,zc=0,Ac=0,Bc=0,Cc=0,Dc=0,Ec=0;uc=T-32|0;T=uc;q[uc+8>>2]=pc;a:{if((pc|0)==-1){qc=1;break a}qc=1;tc=(pc>>>0)/3|0;if(q[q[a+24>>2]+(tc>>>3&268435452)>>2]>>>(tc&31)&1){break a}tc=a+52|0;qc=q[a+48>>2];q[tc>>2]=qc;zc=a+48|0;b:{if((qc|0)!=q[a+56>>2]){q[qc>>2]=pc;q[tc>>2]=qc+4;break b}zi(zc,uc+8|0)}rc=-1;qc=q[a+4>>2];pc=q[uc+8>>2];c:{if((pc|0)==-1){tc=q[qc+28>>2];qc=q[tc+ -4>>2];break c}tc=q[qc+28>>2];qc=pc+1|0;qc=q[tc+(((qc>>>0)%3|0?qc:pc+ -2|0)<<2)>>2];if((pc>>>0)%3){rc=pc+ -1|0;break c}rc=pc+2|0}if((qc|0)==-1){qc=0;break a}tc=q[(rc<<2)+tc>>2];if((tc|0)==-1){qc=0;break a}pc=q[a+36>>2];sc=pc+(qc>>>3&536870908)|0;rc=q[sc>>2];vc=1<<(qc&31);if(!(rc&vc)){q[sc>>2]=rc|vc;rc=-1;pc=q[uc+8>>2];if((pc|0)!=-1){sc=pc+1|0;rc=(sc>>>0)%3|0?sc:pc+ -2|0}q[uc+16>>2]=rc;pc=q[a+20>>2];sc=(rc>>>0)/3|0;rc=q[(q[q[a+16>>2]+96>>2]+w(sc,12)|0)+(rc-w(sc,3)<<2)>>2];q[uc+24>>2]=rc;sc=q[pc+4>>2];vc=sc+4|0;pc=q[vc>>2];d:{if((pc|0)!=q[sc+8>>2]){q[pc>>2]=rc;q[vc>>2]=pc+4;break d}zi(sc,uc+24|0)}sc=a+12|0;rc=q[sc>>2];vc=rc+4|0;pc=q[vc>>2];e:{if((pc|0)!=q[rc+8>>2]){q[pc>>2]=q[uc+16>>2];q[vc>>2]=pc+4;break e}zi(rc,uc+16|0);rc=q[sc>>2]}q[q[rc+12>>2]+(qc<<2)>>2]=q[rc+24>>2];q[rc+24>>2]=q[rc+24>>2]+1;pc=q[a+36>>2]}pc=(tc>>>3&536870908)+pc|0;qc=q[pc>>2];sc=1<<(tc&31);if(!(qc&sc)){q[pc>>2]=qc|sc;pc=uc;rc=pc;sc=q[pc+8>>2];qc=-1;f:{if((sc|0)==-1){break f}qc=sc+ -1|0;if((sc>>>0)%3){break f}qc=sc+2|0}q[rc+16>>2]=qc;pc=q[a+20>>2];sc=(qc>>>0)/3|0;sc=q[(q[q[a+16>>2]+96>>2]+w(sc,12)|0)+(qc-w(sc,3)<<2)>>2];q[uc+24>>2]=sc;qc=q[pc+4>>2];rc=qc+4|0;pc=q[rc>>2];g:{if((pc|0)!=q[qc+8>>2]){q[pc>>2]=sc;q[rc>>2]=pc+4;break g}zi(qc,uc+24|0)}sc=a+12|0;qc=q[sc>>2];rc=qc+4|0;pc=q[rc>>2];h:{if((pc|0)!=q[qc+8>>2]){q[pc>>2]=q[uc+16>>2];q[rc>>2]=pc+4;break h}zi(qc,uc+16|0);qc=q[sc>>2]}q[q[qc+12>>2]+(tc<<2)>>2]=q[qc+24>>2];q[qc+24>>2]=q[qc+24>>2]+1}vc=a+52|0;pc=q[vc>>2];if((pc|0)==q[a+48>>2]){qc=1;break a}xc=a+24|0;yc=a+4|0;Bc=a+36|0;Cc=a+16|0;Dc=a+20|0;Ec=a+56|0;while(1){tc=pc+ -4|0;pc=q[tc>>2];q[uc+8>>2]=pc;qc=(pc>>>0)/3|0;i:{j:{k:{if((pc|0)==-1){break k}pc=q[xc>>2]+(qc>>>3&268435452)|0;sc=q[pc>>2];qc=1<<(qc&31);if(sc&qc){break k}q[pc>>2]=qc|sc;rc=q[yc>>2];pc=q[uc+8>>2];qc=q[q[rc+28>>2]+(pc<<2)>>2];if((qc|0)!=-1){break j}qc=0;break a}q[vc>>2]=tc;break i}l:{m:{n:{while(1){o:{p:{tc=q[Bc>>2]+(qc>>>3&536870908)|0;sc=q[tc>>2];wc=1<<(qc&31);if(sc&wc){break p}Ac=qc<<2;qc=q[Ac+q[rc+40>>2]>>2];pc=1;q:{if((qc|0)==-1){break q}pc=qc+1|0;pc=(pc>>>0)%3|0?pc:qc+ -2|0;r:{if((pc|0)==-1|q[q[rc>>2]+(pc>>>3&536870908)>>2]>>>(pc&31)&1){break r}qc=q[q[q[rc+64>>2]+12>>2]+(pc<<2)>>2];if((qc|0)==-1){break r}rc=qc+1|0;pc=0;if((((rc>>>0)%3|0?rc:qc+ -2|0)|0)!=-1){break q}}pc=1}qc=pc;q[tc>>2]=sc|wc;pc=q[uc+8>>2];q[uc+16>>2]=pc;tc=q[Dc>>2];sc=(pc>>>0)/3|0;sc=q[(q[q[Cc>>2]+96>>2]+w(sc,12)|0)+(pc-w(sc,3)<<2)>>2];q[uc+24>>2]=sc;tc=q[tc+4>>2];rc=tc+4|0;pc=q[rc>>2];s:{if((pc|0)!=q[tc+8>>2]){q[pc>>2]=sc;q[rc>>2]=pc+4;break s}zi(tc,uc+24|0)}sc=a+12|0;pc=q[sc>>2];rc=pc+4|0;tc=q[rc>>2];t:{if((tc|0)!=q[pc+8>>2]){q[tc>>2]=q[uc+16>>2];q[rc>>2]=tc+4;break t}zi(pc,uc+16|0);pc=q[sc>>2]}q[q[pc+12>>2]+Ac>>2]=q[pc+24>>2];q[pc+24>>2]=q[pc+24>>2]+1;rc=q[yc>>2];pc=q[uc+8>>2];if(qc){break p}qc=-1;u:{if((pc|0)==-1){break u}tc=pc+1|0;pc=(tc>>>0)%3|0?tc:pc+ -2|0;if((pc|0)==-1|q[q[rc>>2]+(pc>>>3&536870908)>>2]>>>(pc&31)&1){break u}qc=q[q[q[rc+64>>2]+12>>2]+(pc<<2)>>2]}q[uc+8>>2]=qc;pc=(qc>>>0)/3|0;break o}if((pc|0)==-1){break m}tc=-1;sc=uc;wc=pc+1|0;wc=(wc>>>0)%3|0?wc:pc+ -2|0;qc=-1;v:{if((wc|0)==-1){break v}qc=-1;if(q[q[rc>>2]+(wc>>>3&536870908)>>2]>>>(wc&31)&1){break v}qc=q[q[q[rc+64>>2]+12>>2]+(wc<<2)>>2]}q[sc+24>>2]=qc;pc=((pc>>>0)%3|0?-1:2)+pc|0;if(!((pc|0)==-1|q[q[rc>>2]+(pc>>>3&536870908)>>2]>>>(pc&31)&1)){tc=q[q[q[rc+64>>2]+12>>2]+(pc<<2)>>2]}sc=(tc>>>0)/3|0;pc=(qc>>>0)/3|0;rc=(qc|0)==-1;w:{if(rc){pc=-1;rc=1;break w}rc=rc?-1:pc;rc=q[q[xc>>2]+(rc>>>3&536870908)>>2]>>>(rc&31)&1}x:{if((tc|0)!=-1){wc=(tc|0)==-1?-1:sc;wc=q[q[xc>>2]+(wc>>>3&536870908)>>2]&1<<(wc&31);if(rc){qc=tc;pc=sc;if(!wc){break x}break l}if(wc){break x}pc=q[vc>>2];q[pc+ -4>>2]=tc;if((pc|0)==q[Ec>>2]){break n}q[pc>>2]=q[uc+24>>2];q[vc>>2]=pc+4;break i}if(rc){break l}}q[uc+8>>2]=qc}qc=q[xc>>2]+(pc>>>3&536870908)|0;q[qc>>2]=q[qc>>2]|1<<(pc&31);rc=q[yc>>2];pc=q[uc+8>>2];qc=q[q[rc+28>>2]+(pc<<2)>>2];if((qc|0)!=-1){continue}break}qc=0;break a}zi(zc,uc+24|0);break i}q[uc+24>>2]=-1}q[vc>>2]=q[vc>>2]+ -4}qc=1;pc=q[vc>>2];if((pc|0)!=q[a+48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An(pc)}pc=q[Ic+ -40>>2];if(pc){q[Ic+ -36>>2]=pc;An(pc)}pi(Ic+ -140|0);Ic=q[a+8>>2];if((Jc|0)!=(Ic|0)){continue}break}}a=q[a>>2];if(a){An(a)}}function xj(a,Kc){var Lc=0,Mc=0,Nc=x(0);Lc=2;a:{if((Kc|0)==1){break a}Lc=Kc;if(!(Kc+ -1&Kc)){break a}Lc=jm(Kc)}Mc=q[a+4>>2];if(Lc>>>0>Mc>>>0){yj(a,Lc);return}b:{if(Lc>>>0>=Mc>>>0){break b}Nc=x(D(x(x(t[a+12>>2])/u[a+16>>2])));c:{if(Nc=x(0)){Kc=~~Nc>>>0;break c}Kc=0}d:{e:{if(Mc>>>0<3){break e}if(co(Mc)>>>0>1){break e}Kc=Kc>>>0<2?Kc:1<<32-z(Kc+ -1|0);break d}Kc=jm(Kc)}Kc=Lc>>>0>>0?Kc:Lc;if(Kc>>>0>=Mc>>>0){break b}yj(a,Kc)}}function yj(a,Kc){var Oc=0,Pc=0,Qc=0,Rc=0,Sc=0,Tc=0,Uc=0,Vc=0,Wc=0;a:{b:{if(Kc){if(Kc>>>0>=1073741824){break a}Oc=Mm(Kc<<2);Pc=q[a>>2];q[a>>2]=Oc;if(Pc){An(Pc)}q[a+4>>2]=Kc;Oc=0;while(1){q[q[a>>2]+(Oc<<2)>>2]=0;Oc=Oc+1|0;if((Oc|0)!=(Kc|0)){continue}break}Pc=a+8|0;Rc=q[Pc>>2];if(!Rc){break b}Sc=q[Rc+4>>2];Oc=co(Kc);c:{if(Oc>>>0<=1){Sc=Kc+ -1⪼break c}if(Sc>>>0>>0){break c}Sc=(Sc>>>0)%(Kc>>>0)|0}q[q[a>>2]+(Sc<<2)>>2]=Pc;Pc=q[Rc>>2];if(!Pc){break b}Vc=Kc+ -1|0;Wc=Oc>>>0>1;while(1){Qc=q[Pc+4>>2];d:{if(!Wc){Qc=Qc&Vc;break d}if(Qc>>>0>>0){break d}Qc=(Qc>>>0)%(Kc>>>0)|0}e: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}Kc=q[Zc+12>>2];q[Xc>>2]=q[Zc+8>>2];q[Xc+4>>2]=Kc;q[Xc+8>>2]=q[gd>>2];q[Yc>>2]=q[Yc>>2]+12}ld=ld+1|0;if((hd|0)==(ld|0)){break c}Yc=q[kd>>2];Kc=Yc;bd=q[Kc+16>>2];Xc=q[Kc+20>>2];q[gd>>2]=0;q[Zc+8>>2]=0;q[Zc+12>>2]=0;$c=q[Kc+12>>2];ad=$c;ed=q[Kc+8>>2];fd=ed;Kc=Xc;_c=bd+4|0;if(_c>>>0<4){Kc=Kc+1|0}dd=_c;_c=Kc;if(($c|0)>(Kc|0)?1:($c|0)>=(Kc|0)?fd>>>0
>>0?0:1:0){continue}break}}dd=0;break a}q[q[a+4>>2]+80>>2]=id;dd=1}T=Zc+32|0;return dd|0}function Aj(a,md,nd){var od=0,pd=0,qd=0,rd=0;a:{if(a>>>0>5){break a}qd=q[nd+16>>2];od=q[nd+12>>2];pd=q[nd+20>>2];if((od|0)<(pd|0)?1:(od|0)<=(pd|0)?t[nd+8>>2]>qd>>>0?0:1:0){break a}od=r[qd+q[nd>>2]|0];qd=qd+1|0;if(qd>>>0<1){pd=pd+1|0}q[nd+16>>2]=qd;q[nd+20>>2]=pd;pd=md;if(od&128){if(!Aj(a+1|0,md,nd)){break a}a=q[md>>2]<<7;q[md>>2]=a;od=a|od&127}q[pd>>2]=od;rd=1}return rd}function Bj(a,md){var nd=0,sd=0,td=0,ud=0,vd=0,wd=0,xd=0,yd=0,zd=0,Ad=0;nd=T-32|0;T=nd;q[nd+24>>2]=0;q[nd+16>>2]=0;q[nd+20>>2]=0;a:{ud=w(md,3);if(ud){if(ud>>>0>=1073741824){break a}sd=w(md,12);vd=Mm(sd);q[nd+16>>2]=vd;q[nd+24>>2]=(ud<<2)+vd;zd=nd,Ad=Dn(vd,0,sd)+sd|0,q[zd+20>>2]=Ad}b:{if(!qh(ud,1,q[a+32>>2],vd)){break b}td=1;if(!md){break b}yd=a+44|0;vd=0;while(1){ud=nd+8|0;q[ud>>2]=0;q[nd>>2]=0;q[nd+4>>2]=0;a=q[nd+16>>2]+(vd<<2)|0;sd=q[a>>2];td=sd>>>1;sd=(sd&1?0-td|0:td)+wd|0;q[nd>>2]=sd;td=q[a+4>>2];wd=td>>>1;sd=sd+(td&1?0-wd|0:wd)|0;q[nd+4>>2]=sd;a=q[a+8>>2];td=a>>>1;wd=sd+(a&1?0-td|0:td)|0;q[ud>>2]=wd;sd=q[yd>>2];td=sd+100|0;a=q[td>>2];c:{if((a|0)!=q[sd+104>>2]){sd=q[nd+4>>2];q[a>>2]=q[nd>>2];q[a+4>>2]=sd;q[a+8>>2]=q[ud>>2];q[td>>2]=q[td>>2]+12;break c}Cj(sd+96|0,nd)}vd=vd+3|0;td=1;xd=xd+1|0;if((xd|0)!=(md|0)){continue}break}}a=q[nd+16>>2];if(a){q[nd+20>>2]=a;An(a)}T=nd+32|0;return td}bn();F()}function Cj(a,md){var Bd=0,Cd=0,Dd=0,Ed=0,Fd=0,Gd=0;a:{Ed=q[a>>2];Fd=q[a+4>>2]-Ed|0;Bd=(Fd|0)/12|0;Cd=Bd+1|0;if(Cd>>>0<357913942){Gd=w(Bd,12);Dd=(q[a+8>>2]-Ed|0)/12|0;Bd=Dd<<1;Dd=Dd>>>0<178956970?Bd>>>0>>0?Cd:Bd:357913941;Bd=0;b:{if(!Dd){break b}if(Dd>>>0>=357913942){break a}Bd=Mm(w(Dd,12))}Cd=Gd+Bd|0;Gd=q[md+4>>2];q[Cd>>2]=q[md>>2];q[Cd+4>>2]=Gd;q[Cd+8>>2]=q[md+8>>2];md=Cd+w((Fd|0)/-12|0,12)|0;Bd=Bd+w(Dd,12)|0;Cd=Cd+12|0;if((Fd|0)>=1){Cn(md,Ed,Fd)}q[a>>2]=md;q[a+8>>2]=Bd;q[a+4>>2]=Cd;if(Ed){An(Ed)}return}bn();F()}ab(13160);F()}function Dj(a,md){a=a|0;md=md|0;var Hd=0,Id=0,Jd=0,Kd=0,Ld=0,Md=0,Nd=0;Kd=T-16|0;T=Kd;Ld=Mm(64);Hd=Mm(12);q[Hd+8>>2]=q[q[a+4>>2]+80>>2];q[Hd>>2]=13236;q[Hd+4>>2]=0;q[Kd+8>>2]=Hd;Ge(Ld,Kd+8|0);a:{if((md|0)>=0){Hd=q[a+12>>2];Md=a+8|0;Nd=q[Md>>2];Id=Hd-Nd>>2;b:{if((Id|0)>(md|0)){break b}Jd=md+1|0;if(Id>>>0<=md>>>0){ji(Md,Jd-Id|0);break b}if(Jd>>>0>=Id>>>0){break b}Jd=Nd+(Jd<<2)|0;if((Jd|0)!=(Hd|0)){while(1){Hd=Hd+ -4|0;Id=q[Hd>>2];q[Hd>>2]=0;if(Id){n[q[q[Id>>2]+4>>2]](Id)}if((Hd|0)!=(Jd|0)){continue}break}}q[a+12>>2]=Jd}md=q[Md>>2]+(md<<2)|0;a=q[md>>2];q[md>>2]=Ld;Id=1;if(!a){break a}n[q[q[a>>2]+4>>2]](a);break a}n[q[q[Ld>>2]+4>>2]](Ld)}a=q[Kd+8>>2];q[Kd+8>>2]=0;if(a){n[q[q[a>>2]+4>>2]](a)}T=Kd+16|0;return Id|0}function Ej(a){a=a|0;var md=0,Od=0,Pd=0,Qd=0,Rd=0;q[a>>2]=13300;md=q[a+20>>2];if(md){q[a+24>>2]=md;An(md)}Pd=q[a+8>>2];if(Pd){md=Pd;Rd=a+12|0;Od=q[Rd>>2];Qd=md;a:{if((md|0)==(Od|0)){break a}while(1){Od=Od+ -4|0;md=q[Od>>2];q[Od>>2]=0;if(md){n[q[q[md>>2]+4>>2]](md)}if((Od|0)!=(Pd|0)){continue}break}Qd=q[a+8>>2]}md=Qd;q[Rd>>2]=Pd;An(md)}An(a)}function Fj(a,Sd){a=a|0;Sd=Sd|0;o[Sd+84|0]=1;q[Sd+72>>2]=q[Sd+68>>2];return 1}function Gj(a){a=a|0;var Sd=0,Td=0,Ud=0,Vd=0;a:{Sd=q[a+8>>2];b:{if((Sd|0)<0){break b}Td=q[a+4>>2];Vd=q[Td>>2];Ud=q[Td+4>>2]-Vd>>2;c:{if(Sd>>>0>Ud>>>0){Hj(Td,Sd-Ud|0);Sd=q[a+8>>2];break c}if(Sd>>>0>=Ud>>>0){break c}q[Td+4>>2]=Vd+(Sd<<2)}Vd=1;if((Sd|0)<1){break b}a=q[a+4>>2];Td=q[a>>2];Ud=q[a+4>>2]-Td>>2;a=0;while(1){if((a|0)==(Ud|0)){break a}q[Td+(a<<2)>>2]=a;a=a+1|0;if((a|0)<(Sd|0)){continue}break}}return Vd|0}cn();F()}function Hj(a,Wd){var Xd=0,Yd=0,Zd=0,_d=0,$d=0,ae=0,be=0,ce=0,de=0;Yd=q[a+8>>2];Zd=a+4|0;Xd=q[Zd>>2];if(Yd-Xd>>2>>>0>=Wd>>>0){a=Wd<<2;ce=Zd,de=Dn(Xd,0,a)+a|0,q[ce>>2]=de;return}a:{Zd=q[a>>2];$d=Xd-Zd|0;Xd=$d>>2;_d=Xd+Wd|0;if(_d>>>0<1073741824){be=Xd<<2;Yd=Yd-Zd|0;Xd=Yd>>1;Yd=Yd>>2>>>0<536870911?Xd>>>0<_d>>>0?_d:Xd:1073741823;Xd=0;b:{if(!Yd){break b}if(Yd>>>0>=1073741824){break a}ae=Mm(Yd<<2);Xd=ae}Dn(be+Xd|0,0,Wd<<2);Wd=Xd+(_d<<2)|0;_d=Xd+(Yd<<2)|0;if(($d|0)>=1){Cn(ae,Zd,$d)}q[a>>2]=Xd;q[a+8>>2]=_d;q[a+4>>2]=Wd;if(Zd){An(Zd)}return}bn();F()}ab(13160);F()}function Ij(a){q[a+40>>2]=0;q[a>>2]=13300;q[a+4>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0;q[a+16>>2]=0;q[a+20>>2]=0;q[a+24>>2]=0;q[a+28>>2]=0;q[a+32>>2]=0;p[a+36>>1]=0}function Jj(a,Wd,ee){var fe=0,ge=0,he=0,ie=0,je=0,ke=0;ge=T-16|0;T=ge;ie=q[Wd+12>>2];fe=q[Wd+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ee+4|0]=r[fe+4|0];ie=Wd;fe=q[Wd+20>>2];he=q[Wd+16>>2]+5|0;if(he>>>0<5){fe=fe+1|0}je=he;he=fe;q[ie+16>>2]=je;q[ie+20>>2]=fe;if(cm(ee,13374,5)){Wd=Mm(32);q[ge>>2]=Wd;q[ge+4>>2]=17;q[ge+8>>2]=-2147483616;o[Wd+17|0]=0;o[Wd+16|0]=r[13396];ee=r[13392]|r[13393]<<8|(r[13394]<<16|r[13395]<<24);fe=r[13388]|r[13389]<<8|(r[13390]<<16|r[13391]<<24);o[Wd+8|0]=fe;o[Wd+9|0]=fe>>>8;o[Wd+10|0]=fe>>>16;o[Wd+11|0]=fe>>>24;o[Wd+12|0]=ee;o[Wd+13|0]=ee>>>8;o[Wd+14|0]=ee>>>16;o[Wd+15|0]=ee>>>24;ee=r[13384]|r[13385]<<8|(r[13386]<<16|r[13387]<<24);fe=r[13380]|r[13381]<<8|(r[13382]<<16|r[13383]<<24);o[Wd|0]=fe;o[Wd+1|0]=fe>>>8;o[Wd+2|0]=fe>>>16;o[Wd+3|0]=fe>>>24;o[Wd+4|0]=ee;o[Wd+5|0]=ee>>>8;o[Wd+6|0]=ee>>>16;o[Wd+7|0]=ee>>>24;q[a>>2]=-1;Rm(a+4|0,ge);if(o[ge+11|0]>-1){break a}An(q[ge>>2]);break a}fe=q[Wd+12>>2];if((fe|0)<(he|0)?1:(fe|0)<=(he|0)?t[Wd+8>>2]>je>>>0?0:1:0){Wd=Mm(32);q[ge>>2]=Wd;q[ge+4>>2]=29;q[ge+8>>2]=-2147483616;o[Wd+29|0]=0;ee=r[13369]|r[13370]<<8|(r[13371]<<16|r[13372]<<24);fe=r[13365]|r[13366]<<8|(r[13367]<<16|r[13368]<<24);o[Wd+21|0]=fe;o[Wd+22|0]=fe>>>8;o[Wd+23|0]=fe>>>16;o[Wd+24|0]=fe>>>24;o[Wd+25|0]=ee;o[Wd+26|0]=ee>>>8;o[Wd+27|0]=ee>>>16;o[Wd+28|0]=ee>>>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8;o[Wd+10|0]=fe>>>16;o[Wd+11|0]=fe>>>24;o[Wd+12|0]=ee;o[Wd+13|0]=ee>>>8;o[Wd+14|0]=ee>>>16;o[Wd+15|0]=ee>>>24;ee=q[3337];fe=q[3336];o[Wd|0]=fe;o[Wd+1|0]=fe>>>8;o[Wd+2|0]=fe>>>16;o[Wd+3|0]=fe>>>24;o[Wd+4|0]=ee;o[Wd+5|0]=ee>>>8;o[Wd+6|0]=ee>>>16;o[Wd+7|0]=ee>>>24;q[a>>2]=-2;Rm(a+4|0,ge);if(o[ge+11|0]>-1){break a}An(q[ge>>2]);break a}he=ee;ee=je+q[Wd>>2]|0;p[he+10>>1]=r[ee|0]|r[ee+1|0]<<8;ee=Wd;he=Wd;fe=q[Wd+20>>2];Wd=q[Wd+16>>2]+2|0;if(Wd>>>0<2){fe=fe+1|0}q[he+16>>2]=Wd;q[ee+20>>2]=fe;q[a+8>>2]=0;q[a+12>>2]=0;q[a>>2]=0;q[a+4>>2]=0}T=ge+16|0}function Kj(a,Wd){var ee=0,le=0,me=0,ne=0;le=T-48|0;T=le;ee=Mm(36);me=ee+4|0;q[me>>2]=0;q[me+4>>2]=0;ne=ee+16|0;q[ne>>2]=0;q[ne+4>>2]=0;q[ee>>2]=me;q[ee+32>>2]=0;q[ee+24>>2]=0;q[ee+28>>2]=0;q[ee+12>>2]=ne;q[le+40>>2]=ee;ee=le+32|0;q[ee>>2]=0;a:{if(!Ok(ee,q[Wd+32>>2],q[le+40>>2])){q[le+24>>2]=0;q[le+16>>2]=0;q[le+20>>2]=0;Wd=Mm(32);q[le+16>>2]=Wd;q[le+20>>2]=26;q[le+24>>2]=-2147483616;o[Wd+26|0]=0;ee=r[13422]|r[13423]<<8;o[Wd+24|0]=ee;o[Wd+25|0]=ee>>>8;ee=r[13418]|r[13419]<<8|(r[13420]<<16|r[13421]<<24);me=r[13414]|r[13415]<<8|(r[13416]<<16|r[13417]<<24);o[Wd+16|0]=me;o[Wd+17|0]=me>>>8;o[Wd+18|0]=me>>>16;o[Wd+19|0]=me>>>24;o[Wd+20|0]=ee;o[Wd+21|0]=ee>>>8;o[Wd+22|0]=ee>>>16;o[Wd+23|0]=ee>>>24;ee=r[13410]|r[13411]<<8|(r[13412]<<16|r[13413]<<24);me=r[13406]|r[13407]<<8|(r[13408]<<16|r[13409]<<24);o[Wd+8|0]=me;o[Wd+9|0]=me>>>8;o[Wd+10|0]=me>>>16;o[Wd+11|0]=me>>>24;o[Wd+12|0]=ee;o[Wd+13|0]=ee>>>8;o[Wd+14|0]=ee>>>16;o[Wd+15|0]=ee>>>24;ee=r[13402]|r[13403]<<8|(r[13404]<<16|r[13405]<<24);me=r[13398]|r[13399]<<8|(r[13400]<<16|r[13401]<<24);o[Wd|0]=me;o[Wd+1|0]=me>>>8;o[Wd+2|0]=me>>>16;o[Wd+3|0]=me>>>24;o[Wd+4|0]=ee;o[Wd+5|0]=ee>>>8;o[Wd+6|0]=ee>>>16;o[Wd+7|0]=ee>>>24;q[a>>2]=-1;Rm(a+4|0,le+16|0);if(o[le+27|0]>-1){break a}An(q[le+16>>2]);break a}Wd=q[Wd+4>>2];q[le+8>>2]=0;me=q[le+40>>2];q[le+40>>2]=0;ee=q[Wd+4>>2];q[Wd+4>>2]=me;b:{if(!ee){q[le+8>>2]=0;break b}Lj(ee);Wd=q[le+8>>2];q[le+8>>2]=0;if(!Wd){break b}Lj(Wd)}q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0}a=q[le+40>>2];q[le+40>>2]=0;if(a){Lj(a)}T=le+48|0}function Lj(a){var Wd=0,oe=0,pe=0,qe=0,re=0;if(a){pe=q[a+24>>2];if(pe){Wd=pe;re=a+28|0;oe=q[re>>2];qe=Wd;a:{if((oe|0)==(Wd|0)){break a}while(1){oe=oe+ -4|0;Wd=q[oe>>2];q[oe>>2]=0;if(Wd){Hc(Wd+12|0,q[Wd+16>>2]);Ic(Wd,q[Wd+4>>2]);An(Wd)}if((oe|0)!=(pe|0)){continue}break}qe=q[a+24>>2]}Wd=qe;q[re>>2]=pe;An(Wd)}Hc(a+12|0,q[a+16>>2]);Ic(a,q[a+4>>2]);An(a)}}function Mj(a,se,te,ue,ve){var we=0,xe=0;we=T-32|0;T=we;q[se+32>>2]=ue;q[se+40>>2]=te;q[se+4>>2]=ve;Jj(a,ue,we+16|0);a:{if(q[a>>2]){break a}te=a+4|0;if(o[a+15|0]<=-1){An(q[te>>2])}ve=r[we+23|0];if((n[q[q[se>>2]+8>>2]](se)|0)!=(ve|0)){se=Mm(64);q[we>>2]=se;q[we+4>>2]=50;q[we+8>>2]=-2147483584;o[se+50|0]=0;ue=r[13473]|r[13474]<<8;o[se+48|0]=ue;o[se+49|0]=ue>>>8;ue=r[13469]|r[13470]<<8|(r[13471]<<16|r[13472]<<24);ve=r[13465]|r[13466]<<8|(r[13467]<<16|r[13468]<<24);o[se+40|0]=ve;o[se+41|0]=ve>>>8;o[se+42|0]=ve>>>16;o[se+43|0]=ve>>>24;o[se+44|0]=ue;o[se+45|0]=ue>>>8;o[se+46|0]=ue>>>16;o[se+47|0]=ue>>>24;ue=r[13461]|r[13462]<<8|(r[13463]<<16|r[13464]<<24);ve=r[13457]|r[13458]<<8|(r[13459]<<16|r[13460]<<24);o[se+32|0]=ve;o[se+33|0]=ve>>>8;o[se+34|0]=ve>>>16;o[se+35|0]=ve>>>24;o[se+36|0]=ue;o[se+37|0]=ue>>>8;o[se+38|0]=ue>>>16;o[se+39|0]=ue>>>24;ue=r[13453]|r[13454]<<8|(r[13455]<<16|r[13456]<<24);ve=r[13449]|r[13450]<<8|(r[13451]<<16|r[13452]<<24);o[se+24|0]=ve;o[se+25|0]=ve>>>8;o[se+26|0]=ve>>>16;o[se+27|0]=ve>>>24;o[se+28|0]=ue;o[se+29|0]=ue>>>8;o[se+30|0]=ue>>>16;o[se+31|0]=ue>>>24;ue=r[13445]|r[13446]<<8|(r[13447]<<16|r[13448]<<24);ve=r[13441]|r[13442]<<8|(r[13443]<<16|r[13444]<<24);o[se+16|0]=ve;o[se+17|0]=ve>>>8;o[se+18|0]=ve>>>16;o[se+19|0]=ve>>>24;o[se+20|0]=ue;o[se+21|0]=ue>>>8;o[se+22|0]=ue>>>16;o[se+23|0]=ue>>>24;ue=r[13437]|r[13438]<<8|(r[13439]<<16|r[13440]<<24);ve=r[13433]|r[13434]<<8|(r[13435]<<16|r[13436]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13429]|r[13430]<<8|(r[13431]<<16|r[13432]<<24);ve=r[13425]|r[13426]<<8|(r[13427]<<16|r[13428]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-1;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}ue=r[we+21|0];o[se+36|0]=ue;xe=r[we+22|0];o[se+37|0]=xe;if((ue+ -1&255)>>>0>=2){se=Mm(32);q[we>>2]=se;q[we+4>>2]=22;q[we+8>>2]=-2147483616;o[se+22|0]=0;ue=r[13494]|r[13495]<<8|(r[13496]<<16|r[13497]<<24);ve=r[13490]|r[13491]<<8|(r[13492]<<16|r[13493]<<24);o[se+14|0]=ve;o[se+15|0]=ve>>>8;o[se+16|0]=ve>>>16;o[se+17|0]=ve>>>24;o[se+18|0]=ue;o[se+19|0]=ue>>>8;o[se+20|0]=ue>>>16;o[se+21|0]=ue>>>24;ue=r[13488]|r[13489]<<8|(r[13490]<<16|r[13491]<<24);ve=r[13484]|r[13485]<<8|(r[13486]<<16|r[13487]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13480]|r[13481]<<8|(r[13482]<<16|r[13483]<<24);ve=r[13476]|r[13477]<<8|(r[13478]<<16|r[13479]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-5;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}if(!((ue|0)!=2|(ve?2:3)>>>0>=xe>>>0)){se=Mm(32);q[we>>2]=se;q[we+4>>2]=22;q[we+8>>2]=-2147483616;o[se+22|0]=0;ue=r[13517]|r[13518]<<8|(r[13519]<<16|r[13520]<<24);ve=r[13513]|r[13514]<<8|(r[13515]<<16|r[13516]<<24);o[se+14|0]=ve;o[se+15|0]=ve>>>8;o[se+16|0]=ve>>>16;o[se+17|0]=ve>>>24;o[se+18|0]=ue;o[se+19|0]=ue>>>8;o[se+20|0]=ue>>>16;o[se+21|0]=ue>>>24;ue=r[13511]|r[13512]<<8|(r[13513]<<16|r[13514]<<24);ve=r[13507]|r[13508]<<8|(r[13509]<<16|r[13510]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13503]|r[13504]<<8|(r[13505]<<16|r[13506]<<24);ve=r[13499]|r[13500]<<8|(r[13501]<<16|r[13502]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-5;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}ue=ue<<8|xe;p[q[se+32>>2]+38>>1]=ue;b:{if((ue&65535)>>>0<259|p[we+26>>1]>-1){break b}Kj(a,se);if(q[a>>2]){break a}if(o[te+11|0]>-1){break b}An(q[te>>2])}if(!n[q[q[se>>2]+12>>2]](se)){se=Mm(48);q[we>>2]=se;q[we+4>>2]=33;q[we+8>>2]=-2147483600;o[se+33|0]=0;o[se+32|0]=r[13554];ue=r[13550]|r[13551]<<8|(r[13552]<<16|r[13553]<<24);ve=r[13546]|r[13547]<<8|(r[13548]<<16|r[13549]<<24);o[se+24|0]=ve;o[se+25|0]=ve>>>8;o[se+26|0]=ve>>>16;o[se+27|0]=ve>>>24;o[se+28|0]=ue;o[se+29|0]=ue>>>8;o[se+30|0]=ue>>>16;o[se+31|0]=ue>>>24;ue=r[13542]|r[13543]<<8|(r[13544]<<16|r[13545]<<24);ve=r[13538]|r[13539]<<8|(r[13540]<<16|r[13541]<<24);o[se+16|0]=ve;o[se+17|0]=ve>>>8;o[se+18|0]=ve>>>16;o[se+19|0]=ve>>>24;o[se+20|0]=ue;o[se+21|0]=ue>>>8;o[se+22|0]=ue>>>16;o[se+23|0]=ue>>>24;ue=r[13534]|r[13535]<<8|(r[13536]<<16|r[13537]<<24);ve=r[13530]|r[13531]<<8|(r[13532]<<16|r[13533]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13526]|r[13527]<<8|(r[13528]<<16|r[13529]<<24);ve=r[13522]|r[13523]<<8|(r[13524]<<16|r[13525]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-1;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}if(!n[q[q[se>>2]+20>>2]](se)){se=Mm(32);q[we>>2]=se;q[we+4>>2]=31;q[we+8>>2]=-2147483616;o[se+31|0]=0;ue=r[13583]|r[13584]<<8|(r[13585]<<16|r[13586]<<24);ve=r[13579]|r[13580]<<8|(r[13581]<<16|r[13582]<<24);o[se+23|0]=ve;o[se+24|0]=ve>>>8;o[se+25|0]=ve>>>16;o[se+26|0]=ve>>>24;o[se+27|0]=ue;o[se+28|0]=ue>>>8;o[se+29|0]=ue>>>16;o[se+30|0]=ue>>>24;ue=r[13576]|r[13577]<<8|(r[13578]<<16|r[13579]<<24);ve=r[13572]|r[13573]<<8|(r[13574]<<16|r[13575]<<24);o[se+16|0]=ve;o[se+17|0]=ve>>>8;o[se+18|0]=ve>>>16;o[se+19|0]=ve>>>24;o[se+20|0]=ue;o[se+21|0]=ue>>>8;o[se+22|0]=ue>>>16;o[se+23|0]=ue>>>24;ue=r[13568]|r[13569]<<8|(r[13570]<<16|r[13571]<<24);ve=r[13564]|r[13565]<<8|(r[13566]<<16|r[13567]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13560]|r[13561]<<8|(r[13562]<<16|r[13563]<<24);ve=r[13556]|r[13557]<<8|(r[13558]<<16|r[13559]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-1;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}if(!n[q[q[se>>2]+24>>2]](se)){se=Mm(48);q[we>>2]=se;q[we+4>>2]=34;q[we+8>>2]=-2147483600;o[se+34|0]=0;ue=r[13620]|r[13621]<<8;o[se+32|0]=ue;o[se+33|0]=ue>>>8;ue=r[13616]|r[13617]<<8|(r[13618]<<16|r[13619]<<24);ve=r[13612]|r[13613]<<8|(r[13614]<<16|r[13615]<<24);o[se+24|0]=ve;o[se+25|0]=ve>>>8;o[se+26|0]=ve>>>16;o[se+27|0]=ve>>>24;o[se+28|0]=ue;o[se+29|0]=ue>>>8;o[se+30|0]=ue>>>16;o[se+31|0]=ue>>>24;ue=r[13608]|r[13609]<<8|(r[13610]<<16|r[13611]<<24);ve=r[13604]|r[13605]<<8|(r[13606]<<16|r[13607]<<24);o[se+16|0]=ve;o[se+17|0]=ve>>>8;o[se+18|0]=ve>>>16;o[se+19|0]=ve>>>24;o[se+20|0]=ue;o[se+21|0]=ue>>>8;o[se+22|0]=ue>>>16;o[se+23|0]=ue>>>24;ue=r[13600]|r[13601]<<8|(r[13602]<<16|r[13603]<<24);ve=r[13596]|r[13597]<<8|(r[13598]<<16|r[13599]<<24);o[se+8|0]=ve;o[se+9|0]=ve>>>8;o[se+10|0]=ve>>>16;o[se+11|0]=ve>>>24;o[se+12|0]=ue;o[se+13|0]=ue>>>8;o[se+14|0]=ue>>>16;o[se+15|0]=ue>>>24;ue=r[13592]|r[13593]<<8|(r[13594]<<16|r[13595]<<24);ve=r[13588]|r[13589]<<8|(r[13590]<<16|r[13591]<<24);o[se|0]=ve;o[se+1|0]=ve>>>8;o[se+2|0]=ve>>>16;o[se+3|0]=ve>>>24;o[se+4|0]=ue;o[se+5|0]=ue>>>8;o[se+6|0]=ue>>>16;o[se+7|0]=ue>>>24;q[a>>2]=-1;Rm(te,we);if(o[we+11|0]>-1){break a}An(q[we>>2]);break a}q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0}T=we+32|0}function Nj(a){a=a|0;var se=0,te=0,ue=0,ve=0,ye=0,ze=0,Ae=0,Be=0,Ce=0,De=0,Ee=0,Fe=0;a:{se=q[a+32>>2];ve=q[se+16>>2];ze=q[se+12>>2];ue=q[se+20>>2];b:{if((ze|0)<(ue|0)?1:(ze|0)<=(ue|0)?t[se+8>>2]>ve>>>0?0:1:0){break b}ye=r[ve+q[se>>2]|0];Ae=ve+1|0;if(Ae>>>0<1){ue=ue+1|0}q[se+16>>2]=Ae;q[se+20>>2]=ue;c:{if(!ye){break c}while(1){if(n[q[q[a>>2]+16>>2]](a,te)){te=te+1|0;if((ye|0)!=(te|0)){continue}break c}break}return 0}te=q[a+8>>2];ue=q[a+12>>2];if((te|0)!=(ue|0)){while(1){se=q[te>>2];if(!n[q[q[se>>2]+8>>2]](se,a,q[a+4>>2])){break b}te=te+4|0;if((ue|0)!=(te|0)){continue}break}}d:{if(!ye){break d}te=0;ue=a+8|0;while(1){se=q[q[ue>>2]+(te<<2)>>2];if(!n[q[q[se>>2]+12>>2]](se,q[a+32>>2])){break a}te=te+1|0;if((ye|0)!=(te|0)){continue}break}if(!ye){break d}ve=a+20|0;Be=a+8|0;ze=a+24|0;while(1){te=0;Ae=Ce<<2;se=q[Ae+q[Be>>2]>>2];ue=n[q[q[se>>2]+24>>2]](se)|0;if((ue|0)>0){while(1){se=q[q[Be>>2]+Ae>>2];se=n[q[q[se>>2]+20>>2]](se,te)|0;De=q[a+20>>2];Ee=q[ze>>2]-De>>2;e:{if(se>>>0>>0){break e}Fe=se+1|0;if(Fe>>>0>Ee>>>0){Fa(ve,Fe-Ee|0);De=q[ve>>2];break e}if(Fe>>>0>=Ee>>>0){break e}q[ze>>2]=(Fe<<2)+De}q[(se<<2)+De>>2]=Ce;te=te+1|0;if((ue|0)!=(te|0)){continue}break}}Ce=Ce+1|0;if((Ce|0)!=(ye|0)){continue}break}}Be=0;if(!n[q[q[a>>2]+28>>2]](a)){break b}Be=n[q[q[a>>2]+32>>2]](a)|0}return Be|0}return 0}function Oj(a){a=a|0;var Ge=0,He=0,Ie=0,Je=0;He=1;Ge=q[a+8>>2];Ie=q[a+12>>2];a:{if((Ge|0)==(Ie|0)){break a}while(1){Je=q[Ge>>2];if(n[q[q[Je>>2]+16>>2]](Je,q[a+32>>2])){Ge=Ge+4|0;if((Ie|0)!=(Ge|0)){continue}break a}break}He=0}return He|0}function Pj(a,Ke){var Le=0,Me=0;a:{if((Ke|0)<0){break a}Le=q[a+4>>2];if(q[Le+12>>2]-q[Le+8>>2]>>2<=(Ke|0)){break a}a=q[q[a+8>>2]+(q[q[a+20>>2]+(Ke<<2)>>2]<<2)>>2];Me=n[q[q[a>>2]+32>>2]](a,Ke)|0}return Me}function Qj(a){a=a|0;var Ke=0,Ne=0,Oe=0,Pe=0,Qe=0,Re=0,Se=0,Te=0;Oe=q[a+32>>2];Ne=Oe;Pe=q[Ne+8>>2];Qe=q[Ne+12>>2];Ke=q[Ne+20>>2];Se=Pe;Pe=q[Ne+16>>2];Ne=Pe+4|0;if(Ne>>>0<4){Ke=Ke+1|0}Re=Ne;Ne=Ke;a:{if((Qe|0)<(Ke|0)?1:(Qe|0)<=(Ke|0)?Se>>>0>=Re>>>0?0:1:0){break a}Ke=Pe+q[Oe>>2]|0;Ke=r[Ke|0]|r[Ke+1|0]<<8|(r[Ke+2|0]<<16|r[Ke+3|0]<<24);q[Oe+16>>2]=Re;q[Oe+20>>2]=Ne;if((Ke|0)<0){break a}q[q[a+4>>2]+80>>2]=Ke;Te=1}return Te|0}function Rj(a,Ue){a=a|0;Ue=Ue|0;var Ve=0,We=0,Xe=0,Ye=0,Ze=0,_e=0;Ye=Mm(72);Id(Ye);a:{if((Ue|0)>=0){Ve=q[a+12>>2];Ze=a+8|0;_e=q[Ze>>2];We=Ve-_e>>2;b:{if((We|0)>(Ue|0)){break b}Xe=Ue+1|0;if(We>>>0<=Ue>>>0){ji(Ze,Xe-We|0);break b}if(Xe>>>0>=We>>>0){break b}Xe=_e+(Xe<<2)|0;if((Xe|0)!=(Ve|0)){while(1){Ve=Ve+ -4|0;We=q[Ve>>2];q[Ve>>2]=0;if(We){n[q[q[We>>2]+4>>2]](We)}if((Ve|0)!=(Xe|0)){continue}break}}q[a+12>>2]=Xe}Ue=q[Ze>>2]+(Ue<<2)|0;a=q[Ue>>2];q[Ue>>2]=Ye;Ve=1;if(!a){break a}n[q[q[a>>2]+4>>2]](a);return 1}n[q[q[Ye>>2]+4>>2]](Ye)}return Ve|0}function Sj(a){a=a|0;var Ue=0,$e=0,af=0,bf=0,cf=0,df=0,ef=0;af=q[a+32>>2];$e=af;bf=q[$e+8>>2];cf=q[$e+12>>2];Ue=q[$e+20>>2];ef=bf;bf=q[$e+16>>2];$e=bf+4|0;if($e>>>0<4){Ue=Ue+1|0}df=$e;$e=Ue;if((cf|0)>(Ue|0)?1:(cf|0)>=(Ue|0)?ef>>>0>>0?0:1:0){Ue=bf+q[af>>2]|0;Ue=r[Ue|0]|r[Ue+1|0]<<8|(r[Ue+2|0]<<16|r[Ue+3|0]<<24);q[af+16>>2]=df;q[af+20>>2]=$e;q[q[a+4>>2]+80>>2]=Ue;a=1}else{a=0}return a|0}function Tj(a,ff,gf){var hf=0,jf=0,kf=0;if((ff|0)>0){while(1){jf=hf<<2;kf=q[jf+a>>2];q[gf+jf>>2]=0-(kf&1)^kf>>>1;hf=hf+1|0;if((hf|0)!=(ff|0)){continue}break}}}function Uj(a){q[a+16>>2]=0;q[a+20>>2]=0;q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;q[a+24>>2]=0;q[a+28>>2]=0}function Vj(a,q,ff,gf){return Wj(a,q,ff,gf)}function Wj(a,ff,gf,lf){var mf=0,nf=0,of=0;a:{if(!ff){ff=gf;lf=ff>>>0<0?lf+1|0:lf;if((lf|0)<0?1:(lf|0)<=0?ff>>>0>=0?0:1:0){return 0}lf=q[a>>2];gf=q[a+4>>2]-lf|0;if(gf>>>0>>0){Ha(a,ff-gf|0);break a}if(gf>>>0<=ff>>>0){break a}q[a+4>>2]=ff+lf;break a}if((lf|0)<0?1:(lf|0)<=0?gf>>>0>=0?0:1:0){return 0}nf=gf;if(gf>>>0<0){lf=lf+1|0}of=q[a>>2];mf=q[a+4>>2]-of|0;b:{if((lf|0)<0?1:(lf|0)<=0?nf>>>0>mf>>>0?0:1:0){break b}lf=nf;if(mf>>>0>>0){Ha(a,lf-mf|0);break b}if(mf>>>0<=lf>>>0){break b}q[a+4>>2]=lf+of}if(!gf){break a}En(q[a>>2],ff,gf)}ff=a+24|0;gf=ff;lf=ff;a=q[ff+4>>2];ff=q[ff>>2]+1|0;if(ff>>>0<1){a=a+1|0}q[lf>>2]=ff;q[gf+4>>2]=a;return 1}function Xj(a,ff){var gf=0,lf=0;lf=q[a>>2];gf=q[a+4>>2]-lf|0;a:{if(gf>>>0>>0){Ha(a,ff-gf|0);break a}if(gf>>>0<=ff>>>0){break a}q[a+4>>2]=ff+lf}ff=a+24|0;gf=ff;lf=ff;a=q[ff+4>>2];ff=q[ff>>2]+1|0;if(ff>>>0<1){a=a+1|0}q[lf>>2]=ff;q[gf+4>>2]=a}function Yj(a){p[a+38>>1]=0;q[a>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0;q[a+16>>2]=0;q[a+20>>2]=0;q[a+24>>2]=0;q[a+28>>2]=0;o[a+29|0]=0;o[a+30|0]=0;o[a+31|0]=0;o[a+32|0]=0;o[a+33|0]=0;o[a+34|0]=0;o[a+35|0]=0;o[a+36|0]=0;return a}function Zj(a,ff,pf,qf){p[a+38>>1]=qf;q[a>>2]=ff;q[a+16>>2]=0;q[a+20>>2]=0;q[a+8>>2]=pf;q[a+12>>2]=0}function _j(a,ff,pf){var qf=0,rf=0,sf=0,tf=0;a:{b:{if(!ff){break b}if(s[a+38>>1]<=513){rf=q[a+12>>2];ff=q[a+20>>2];sf=q[a+16>>2];tf=sf+8|0;if(tf>>>0<8){ff=ff+1|0}if((rf|0)<(ff|0)?1:(rf|0)<=(ff|0)?t[a+8>>2]>=tf>>>0?0:1:0){break a}ff=sf+q[a>>2]|0;qf=r[ff+4|0]|r[ff+5|0]<<8|(r[ff+6|0]<<16|r[ff+7|0]<<24);q[pf>>2]=r[ff|0]|r[ff+1|0]<<8|(r[ff+2|0]<<16|r[ff+3|0]<<24);q[pf+4>>2]=qf;pf=q[a+20>>2];qf=q[a+16>>2]+8|0;if(qf>>>0<8){pf=pf+1|0}q[a+16>>2]=qf;q[a+20>>2]=pf;break b}if(!$j(1,pf,a)){break a}}o[a+36|0]=1;q[a+32>>2]=0;ff=q[a+16>>2];pf=ff+q[a>>2]|0;q[a+24>>2]=pf;qf=a;a=q[a+8>>2];q[qf+28>>2]=pf+(a-ff|0);qf=1}return qf}function $j(a,ff,pf){var uf=0,vf=0,wf=0,xf=0,yf=0,zf=0;a:{if(a>>>0>10){break a}wf=q[pf+16>>2];uf=q[pf+12>>2];vf=q[pf+20>>2];xf=vf;if((uf|0)<(xf|0)?1:(uf|0)<=(xf|0)?t[pf+8>>2]>wf>>>0?0:1:0){break a}yf=o[wf+q[pf>>2]|0];uf=wf+1|0;if(uf>>>0<1){vf=vf+1|0}q[pf+16>>2]=uf;q[pf+20>>2]=vf;xf=ff;wf=ff;uf=yf;b:{if((uf|0)<=-1){if(!$j(a+1|0,ff,pf)){break a}a=ff;pf=q[ff+4>>2];ff=q[ff>>2];vf=pf<<7|ff>>>25;ff=ff<<7;q[a>>2]=ff;q[a+4>>2]=vf;a=uf&127|ff;break b}vf=0;a=uf&255}q[wf>>2]=a;q[xf+4>>2]=vf;zf=1}return zf}function ak(a){var ff=0,pf=0,Af=0,Bf=0,Cf=0,Df=0;o[a+36|0]=0;Af=q[a+20>>2];Bf=a;Cf=a;Df=q[a+16>>2];a=q[a+32>>2]+7|0;if(a>>>0<7){ff=1}pf=ff>>>3;a=ff<<29|a>>>3;ff=Df+a|0;pf=pf+Af|0;q[Cf+16>>2]=ff;q[Bf+20>>2]=ff>>>0>>0?pf+1|0:pf}function bk(a){a=a+ -1|0;if(a>>>0<=10){return q[(a<<2)+13848>>2]}return-1}function ck(a){var Ef=0;Ef=a+4|0;q[Ef>>2]=0;q[Ef+4>>2]=0;q[a>>2]=Ef;return a}function dk(a,Ff,Gf,Hf){var If=0,Jf=0,Kf=0,Lf=0;If=T-16|0;T=If;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>>2];if(a){continue}break}if((Hf|0)==(Pf|0)){break b}a=r[Hf+27|0];Of=a<<24>>24<0;d:{Mf=Of?q[Hf+20>>2]:a;Ff=Mf>>>0>>0?Mf:Nf;if(Ff){a=Hf+16|0;a=cm(Rf,Of?q[a>>2]:a,Ff);if(a){break d}}if(Nf>>>0>>0){break b}break a}if((a|0)>-1){break a}}Hf=Pf}return Hf}function gk(a,Ff){var Tf=0;Ff=fk(a,Ff);a:{if((Ff|0)==(a+4|0)){break a}a=Ff+28|0;if(o[Ff+39|0]<=-1){a=q[a>>2]}a=bm(a);if((a|0)==-1){break a}Tf=(a|0)!=0}return Tf}function hk(a){q[a>>2]=1065353216;return a}function ik(a,q,Ff){if((Ff|0)<1){return 0}u[a>>2]=q/x(Ff|0);return 1}function jk(a){var Ff=0;q[a>>2]=0;q[a+4>>2]=0;q[a+56>>2]=0;q[a+48>>2]=0;q[a+52>>2]=0;q[a+40>>2]=0;q[a+44>>2]=0;q[a+32>>2]=0;q[a+36>>2]=0;q[a+24>>2]=0;q[a+28>>2]=0;q[a+16>>2]=0;q[a+20>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0;Ff=a- -64|0;q[Ff>>2]=0;q[Ff+4>>2]=0;q[a+72>>2]=0;q[a+76>>2]=0;q[a+80>>2]=0;q[a+84>>2]=0;q[a+60>>2]=a}function kk(a,Uf){var Vf=0,Wf=0,Xf=0;Xf=T-16|0;T=Xf;Wf=Mm(88);Vf=Wf;q[Vf>>2]=0;q[Vf+4>>2]=0;q[Vf+56>>2]=0;q[Vf+48>>2]=0;q[Vf+52>>2]=0;q[Vf+40>>2]=0;q[Vf+44>>2]=0;q[Vf+32>>2]=0;q[Vf+36>>2]=0;q[Vf+24>>2]=0;q[Vf+28>>2]=0;q[Vf+16>>2]=0;q[Vf+20>>2]=0;q[Vf+8>>2]=0;q[Vf+12>>2]=0;Vf=Vf- -64|0;q[Vf>>2]=0;q[Vf+4>>2]=0;q[Wf+72>>2]=0;q[Wf+76>>2]=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dg=hg>>2;gg=dg+Uf|0;if(gg>>>0<1073741824){jg=dg<<2;eg=eg-fg|0;dg=eg>>1;eg=eg>>2>>>0<536870911?dg>>>0>>0?gg:dg:1073741823;dg=0;b:{if(!eg){break b}if(eg>>>0>=1073741824){break a}ig=Mm(eg<<2);dg=ig}Dn(jg+dg|0,0,Uf<<2);Uf=dg+(gg<<2)|0;gg=dg+(eg<<2)|0;if((hg|0)>=1){Cn(ig,fg,hg)}q[a>>2]=dg;q[a+8>>2]=gg;q[a+4>>2]=Uf;if(fg){An(fg)}return}bn();F()}ab(13904);F()}function nk(a,Uf){var mg=0,ng=0,og=0,pg=0,qg=0,rg=0,sg=0,tg=0,ug=0,vg=0,wg=0,xg=0,yg=0,zg=0,Ag=0,Bg=0,Cg=0,Dg=0,Eg=0,Fg=0,Gg=0;og=T-48|0;T=og;if(Uf){Dg=a+12|0;ng=a+4|0;tg=q[ng>>2];ug=q[a>>2];rg=tg-ug|0;pg=rg>>2;mg=q[a+12>>2];qg=q[a+16>>2]-mg>>2;a:{if(pg>>>0>qg>>>0){qk(Dg,pg-qg|0);tg=q[ng>>2];ug=q[a>>2];rg=tg-ug|0;pg=rg>>2;break a}if(pg>>>0>=qg>>>0){break a}q[a+16>>2]=mg+(pg<<2)}ng=0;q[og+40>>2]=0;q[og+32>>2]=0;q[og+36>>2]=0;b:{c:{d:{if(!pg){mg=0;qg=0;break d}if(pg>>>0>=1073741824){break c}mg=Mm(rg);q[og+36>>2]=mg;q[og+32>>2]=mg;q[og+40>>2]=(pg<<2)+mg;qg=mg}e:{if(!rg){break e}sg=a+4|0;ng=qg;wg=ng;rg=0;while(1){vg=q[(rg<<2)+ug>>2];wg=wg-ng>>2;if(vg>>>0>=wg>>>0){q[og+16>>2]=0;mg=vg+1|0;f:{if(mg>>>0>wg>>>0){Ad(og+32|0,mg-wg|0,og+16|0);tg=q[sg>>2];ug=q[a>>2];break f}if(mg>>>0>=wg>>>0){break f}q[og+36>>2]=(mg<<2)+ng}mg=q[og+32>>2];qg=mg}ng=(vg<<2)+mg|0;q[ng>>2]=q[ng>>2]+1;rg=rg+1|0;ng=tg-ug|0;pg=ng>>2;if(rg>>>0>=pg>>>0){break e}wg=q[og+36>>2];ng=mg;continue}}q[og+24>>2]=0;q[og+16>>2]=0;q[og+20>>2]=0;rg=0;g:{if(ng){if(pg>>>0>=536870912){break g}rg=Mm(ng<<1);q[og+16>>2]=rg;q[og+20>>2]=rg;ng=pg<<3;q[og+24>>2]=ng+rg;ng=Dn(rg,255,ng);while(1){ng=ng+8|0;pg=pg+ -1|0;if(pg){continue}break}q[og+20>>2]=ng}q[og+8>>2]=0;q[og>>2]=0;q[og+4>>2]=0;ng=q[og+36>>2]-qg|0;Ag=ng>>2;h:{if(ng){if(Ag>>>0>=1073741824){break h}xg=Mm(ng);q[og>>2]=xg;q[og+8>>2]=(Ag<<2)+xg;pg=0;sg=Dn(xg,0,ng);q[og+4>>2]=sg+ng;ng=0;while(1){qg=ng<<2;q[qg+sg>>2]=pg;pg=q[mg+qg>>2]+pg|0;ng=ng+1|0;if(ng>>>0>>0){continue}break}}if((tg|0)==(ug|0)){break b}Gg=tg-ug>>2;sg=0;Eg=q[og+32>>2];while(1){Bg=sg<<2;wg=q[Bg+ug>>2];tg=-1;ng=sg+1|0;mg=(ng>>>0)%3|0?ng:sg+ -2|0;if((mg|0)!=-1){tg=q[(mg<<2)+ug>>2]}yg=-1;qg=(sg>>>0)%3|0;mg=(qg?-1:2)+sg|0;if((mg|0)!=-1){yg=q[(mg<<2)+ug>>2]}i:{j:{if(qg){break j}k:{if((tg|0)==(yg|0)){break k}mg=q[ug+Bg>>2];if((mg|0)==(tg|0)){break k}if((mg|0)!=(yg|0)){break j}}q[a+40>>2]=q[a+40>>2]+1;ng=sg+3|0;break i}mg=yg<<2;Cg=q[mg+Eg>>2];l:{m:{if((Cg|0)<1){break m}mg=q[mg+xg>>2];pg=0;while(1){vg=(mg<<3)+rg|0;qg=q[vg>>2];if((qg|0)==-1){break m}n:{if((qg|0)!=(tg|0)){break n}zg=q[vg+4>>2];if((zg|0)!=-1){qg=q[(zg<<2)+ug>>2]}else{qg=-1}if((qg|0)==(wg|0)){break n}while(1){qg=mg;pg=pg+1|0;o:{if((pg|0)>=(Cg|0)){break o}Fg=(qg<<3)+rg|0;mg=qg+1|0;wg=(mg<<3)+rg|0;vg=q[wg>>2];q[Fg>>2]=vg;q[Fg+4>>2]=q[wg+4>>2];if((vg|0)!=-1){continue}}break}q[(qg<<3)+rg>>2]=-1;if((zg|0)==-1){break m}mg=q[Dg>>2];q[mg+Bg>>2]=zg;q[mg+(zg<<2)>>2]=sg;break l}mg=mg+1|0;pg=pg+1|0;if((Cg|0)!=(pg|0)){continue}break}}mg=tg<<2;qg=q[mg+Eg>>2];if((qg|0)<1){break l}mg=q[mg+xg>>2];pg=0;while(1){vg=(mg<<3)+rg|0;if(q[vg>>2]==-1){q[vg>>2]=yg;q[vg+4>>2]=sg;break l}mg=mg+1|0;pg=pg+1|0;if((qg|0)!=(pg|0)){continue}break}}}sg=ng;if(sg>>>0>>0){continue}break}break b}bn();F()}bn();F()}ab(13904);F()}q[Uf>>2]=Ag;if(xg){q[og+4>>2]=xg;An(xg)}a=q[og+16>>2];if(a){q[og+20>>2]=a;An(a)}a=q[og+32>>2];if(a){q[og+36>>2]=a;An(a)}a=1}else{a=0}T=og+48|0;return a}function ok(a){var Uf=0,Hg=0,Ig=0,Jg=0,Kg=0,Lg=0,Mg=0,Ng=0,Og=0,Pg=0,Qg=0,Rg=0,Sg=0,Tg=0,Ug=0;Ig=T-48|0;T=Ig;Qg=a+4|0;Uf=q[Qg>>2];Og=q[a>>2];o[Ig+16|0]=0;Rg=rk(Ig+32|0,Uf-Og>>2,Ig+16|0);q[Ig+24>>2]=0;q[Ig+16>>2]=0;q[Ig+20>>2]=0;Uf=q[Qg>>2];Mg=q[a>>2];Ng=a+12|0;while(1){Sg=0;Lg=0;a:{if((Uf|0)==(Mg|0)){break a}while(1){Jg=q[Rg>>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){break j}Xg=Wg+1|0;Xg=(Xg>>>0)%3|0?Xg:Wg+ -2|0}Wg=Xg;if((_g|0)!=(Wg|0)){continue}break}if((Yg|0)!=-1){break e}}Wg=Yg+((Yg>>>0)%3|0?-1:2)|0;if((Wg|0)==-1){break e}Wg=q[q[hh>>2]+(Wg<<2)>>2];if((Wg|0)==-1){break e}Wg=Wg+((Wg>>>0)%3|0?-1:2)|0;if((Wg|0)==-1){break e}bh=q[ch>>2];while(1){Yg=(Wg>>>3&536870908)+bh|0;q[Yg>>2]=q[Yg>>2]|1<<(Wg&31);if(Zg){q[q[a>>2]+(Wg<<2)>>2]=q[$g+8>>2]}Wg=((Wg>>>0)%3|0?-1:2)+Wg|0;if((Wg|0)==-1){break e}Wg=q[q[hh>>2]+(Wg<<2)>>2];if((Wg|0)==-1){break e}Wg=Wg+((Wg>>>0)%3|0?-1:2)|0;if((Wg|0)!=-1){continue}break}}eh=eh+1|0;if((eh|0)!=3){continue}break}}ih=ih+1|0;Wg=q[a>>2];if(ih>>>0<(q[gh>>2]-Wg>>2>>>0)/3>>>0){continue}break b}break}bn();F()}q[a+44>>2]=0;Vg=q[ah>>2];Wg=q[ah+4>>2];Yg=Wg>>>5;Zg=Wg&31;if(Yg|Zg){Yg=(Yg<<2)+Vg|0;Xg=Vg;Wg=0;while(1){if(!(q[Xg>>2]>>>Wg&1)){lh=lh+1|0;q[a+44>>2]=lh}_g=(Wg|0)==31;Wg=_g?0:Wg+1|0;Xg=_g?Xg+4|0:Xg;if((Yg|0)!=(Xg|0)|(Wg|0)!=(Zg|0)){continue}break}}a=q[ch>>2];if(a){An(a);Vg=q[ah>>2]}if(Vg){An(Vg)}T=$g+48|0}function qk(a,Vg){var rh=0,sh=0,th=0,uh=0,vh=0,wh=0;th=q[a+8>>2];rh=q[a+4>>2];if(th-rh>>2>>>0>=Vg>>>0){while(1){q[rh>>2]=q[3475];rh=rh+4|0;Vg=Vg+ -1|0;if(Vg){continue}break}q[a+4>>2]=rh;return}a:{uh=q[a>>2];vh=rh-uh|0;wh=vh>>2;rh=wh+Vg|0;if(rh>>>0<1073741824){th=th-uh|0;sh=th>>1;rh=th>>2>>>0<536870911?sh>>>0>>0?rh:sh:1073741823;sh=0;b:{if(!rh){break b}if(rh>>>0>=1073741824){break a}sh=Mm(rh<<2)}th=sh+(rh<<2)|0;rh=sh+(wh<<2)|0;while(1){q[rh>>2]=q[3475];rh=rh+4|0;Vg=Vg+ -1|0;if(Vg){continue}break}if((vh|0)>=1){Cn(sh,uh,vh)}q[a>>2]=sh;q[a+8>>2]=th;q[a+4>>2]=rh;if(uh){An(uh)}return}bn();F()}ab(13904);F()}function rk(a,Vg,xh){var yh=0,zh=0,Ah=0;q[a>>2]=0;q[a+4>>2]=0;q[a+8>>2]=0;a:{b:{if(!Vg){break b}if((Vg|0)<=-1){break a}zh=Vg+ -1>>>5;Ah=zh+1|0;yh=Mm(Ah<<2);q[a+8>>2]=Ah;q[a>>2]=yh;Ah=r[xh|0];q[a+4>>2]=Vg;q[(Vg>>>0<33?yh:yh+(zh<<2)|0)>>2]=0;xh=Vg>>>5;zh=xh<<2;if(Ah){yh=Dn(yh,255,zh);Vg=Vg&31;if(!Vg){break b}xh=yh+(xh<<2)|0;q[xh>>2]=q[xh>>2]|-1>>>32-Vg;return a}yh=Dn(yh,0,zh);Vg=Vg&31;if(!Vg){break b}xh=yh+(xh<<2)|0;q[xh>>2]=q[xh>>2]&(-1>>>32-Vg^-1)}return a}bn();F()}function sk(a,Vg){var xh=0,Bh=0,Ch=0,Dh=0,Eh=0,Fh=0;a:{Ch=q[a>>2];Fh=q[a+4>>2]-Ch|0;xh=Fh>>3;Bh=xh+1|0;if(Bh>>>0<536870912){Dh=xh<<3;Eh=q[a+8>>2]-Ch|0;xh=Eh>>2;Bh=Eh>>3>>>0<268435455?xh>>>0>>0?Bh:xh:536870911;xh=0;b:{if(!Bh){break b}if(Bh>>>0>=536870912){break a}xh=Mm(Bh<<3)}Dh=Dh+xh|0;Eh=q[Vg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=(Vg<<2)+Mh;return}if(Mh){q[a+4>>2]=Mh;An(Mh);q[a+8>>2]=0;q[a>>2]=0;q[a+4>>2]=0;Lh=0}a:{if(Vg>>>0>=1073741824){break a}Mh=Lh>>1;Mh=Lh>>2>>>0<536870911?Mh>>>0>>0?Vg:Mh:1073741823;if(Mh>>>0>=1073741824){break a}Mh=Mh<<2;Lh=Mm(Mh);q[a>>2]=Lh;q[a+4>>2]=Lh;q[a+8>>2]=Lh+Mh;while(1){q[Lh>>2]=q[Gh>>2];Lh=Lh+4|0;Vg=Vg+ -1|0;if(Vg){continue}break}q[a+4>>2]=Lh;return}bn();F()}function vk(a){al(a);q[a+84>>2]=0;q[a+88>>2]=0;q[a>>2]=13980;q[a+92>>2]=0;q[a+96>>2]=0;q[a+100>>2]=0;q[a+104>>2]=0;return a}function wk(a){a=a|0;var Vg=0,Gh=0,Qh=0,Rh=0,Sh=0;q[a>>2]=14380;Vg=q[a+68>>2];if(Vg){q[a+72>>2]=Vg;An(Vg)}Vg=q[a+56>>2];if(Vg){q[a+60>>2]=Vg;An(Vg)}Vg=q[a+44>>2];if(Vg){q[a+48>>2]=Vg;An(Vg)}Vg=q[a+32>>2];if(Vg){q[a+36>>2]=Vg;An(Vg)}Vg=q[a+20>>2];if(Vg){q[a+24>>2]=Vg;An(Vg)}Qh=q[a+8>>2];if(Qh){Vg=Qh;Sh=a+12|0;Gh=q[Sh>>2];Rh=Vg;a:{if((Vg|0)==(Gh|0)){break a}while(1){Gh=Gh+ -4|0;Vg=q[Gh>>2];q[Gh>>2]=0;if(Vg){Hb(Vg)}if((Gh|0)!=(Qh|0)){continue}break}Rh=q[a+8>>2]}Vg=Rh;q[Sh>>2]=Qh;An(Vg)}Vg=q[a+4>>2];q[a+4>>2]=0;if(Vg){Lj(Vg)}return a|0}function xk(a){a=a|0;var Th=0;q[a>>2]=13980;Th=q[a+96>>2];if(Th){q[a+100>>2]=Th;An(Th)}Th=q[a+84>>2];if(Th){q[a+88>>2]=Th;An(Th)}wk(a);return a|0}function yk(a){a=a|0;var Uh=0;q[a>>2]=13980;Uh=q[a+96>>2];if(Uh){q[a+100>>2]=Uh;An(Uh)}Uh=q[a+84>>2];if(Uh){q[a+88>>2]=Uh;An(Uh)}wk(a);An(a)}function zk(a,Vh,Wh){a=a|0;Vh=Vh|0;Wh=Wh|0;var Xh=0,Yh=0;Xh=T-16|0;T=Xh;Yh=q[Wh>>2];q[Wh>>2]=0;q[Xh+8>>2]=Yh;gl(a,Vh,Xh+8|0);Wh=q[Xh+8>>2];q[Xh+8>>2]=0;if(Wh){Hb(Wh)}Yh=q[a+84>>2];Wh=q[a+88>>2]-Yh>>2;a:{if((Wh|0)>(Vh|0)){break a}Vh=Vh+1|0;if(Vh>>>0>Wh>>>0){Ak(a+84|0,Vh-Wh|0);break a}if(Vh>>>0>=Wh>>>0){break a}q[a+88>>2]=Yh+(Vh<<2)}T=Xh+16|0}function Ak(a,Vh){var Wh=0,Zh=0,_h=0,$h=0,ai=0,bi=0;_h=q[a+8>>2];Wh=q[a+4>>2];if(_h-Wh>>2>>>0>=Vh>>>0){while(1){q[Wh>>2]=1;Wh=Wh+4|0;Vh=Vh+ -1|0;if(Vh){continue}break}q[a+4>>2]=Wh;return}a:{$h=q[a>>2];ai=Wh-$h|0;bi=ai>>2;Wh=bi+Vh|0;if(Wh>>>0<1073741824){_h=_h-$h|0;Zh=_h>>1;Wh=_h>>2>>>0<536870911?Zh>>>0>>0?Wh:Zh:1073741823;Zh=0;b:{if(!Wh){break b}if(Wh>>>0>=1073741824){break a}Zh=Mm(Wh<<2)}_h=Zh+(Wh<<2)|0;Wh=Zh+(bi<<2)|0;while(1){q[Wh>>2]=1;Wh=Wh+4|0;Vh=Vh+ -1|0;if(Vh){continue}break}if((ai|0)>=1){Cn(Zh,$h,ai)}q[a>>2]=Zh;q[a+8>>2]=_h;q[a+4>>2]=Wh;if($h){An($h)}return}bn();F()}ab(14024);F()}function Bk(a,Vh){a=a|0;Vh=Vh|0;var ci=0,di=0,ei=0;jl(a,Vh);a:{if((Vh|0)<0){break a}ci=q[a+88>>2];di=q[a+84>>2];if(ci-di>>2<=(Vh|0)){break a}Vh=di+(Vh<<2)|0;di=Vh+4|0;ci=ci-di|0;ei=ci>>2;if(ci){En(Vh,di,ci)}q[a+88>>2]=Vh+(ei<<2)}}function Ck(a,Vh){var fi=0,gi=0,hi=0,ii=0,ji=0,ki=0;a:{hi=q[a>>2];ji=q[a+4>>2]-hi|0;fi=ji>>2;gi=fi+1|0;if(gi>>>0<1073741824){ki=fi<<2;fi=q[a+8>>2]-hi|0;ii=fi>>1;gi=fi>>2>>>0<536870911?ii>>>0>>0?gi:ii:1073741823;fi=0;b:{if(!gi){break b}if(gi>>>0>=1073741824){break a}fi=Mm(gi<<2)}ii=ki+fi|0;q[ii>>2]=q[Vh>>2];Vh=fi+(gi<<2)|0;gi=ii+4|0;if((ji|0)>=1){Cn(fi,hi,ji)}q[a>>2]=fi;q[a+8>>2]=Vh;q[a+4>>2]=gi;if(hi){An(hi)}return}bn();F()}ab(14092);F()}function Dk(a){q[a>>2]=0;q[a+4>>2]=0;o[a+24|0]=1;q[a+16>>2]=0;q[a+20>>2]=0;q[a+8>>2]=0;q[a+12>>2]=0;q[a+28>>2]=0;q[a+32>>2]=0;q[a+36>>2]=0;q[a+40>>2]=0;q[a+44>>2]=0;q[a+48>>2]=0;q[a+52>>2]=0;q[a+56>>2]=0;q[a+60>>2]=0;q[a+64>>2]=0;q[a+72>>2]=0;q[a+76>>2]=0;q[a+80>>2]=0;q[a+84>>2]=0;q[a+88>>2]=0;q[a+92>>2]=0;q[a+68>>2]=a}function Ek(a,Vh){var li=0,mi=0,ni=0,oi=0,pi=0,qi=0,ri=0,si=0;qi=T-16|0;T=qi;a:{b:{if(Vh){q[a+88>>2]=0;q[a+92>>2]=0;li=a+84|0;mi=q[li>>2];q[li>>2]=0;if(mi){An(mi)}q[a+76>>2]=0;q[a+80>>2]=0;li=a+72|0;mi=q[li>>2];q[li>>2]=0;if(mi){An(mi)}mi=Vh+4|0;li=q[mi>>2];ni=q[Vh>>2];o[qi+15|0]=0;bb(a,li-ni>>2,qi+15|0);ni=Vh+28|0;li=q[ni>>2];oi=q[Vh+24>>2];o[qi+14|0]=0;bb(a+12|0,li-oi>>2,qi+14|0);uk(a+28|0,q[mi>>2]-q[Vh>>2]>>2,14160);mi=q[a+52>>2];oi=q[ni>>2]-q[Vh+24>>2]|0;li=oi>>2;c:{if(q[a+60>>2]-mi>>2>>>0>=li>>>0){break c}if(li>>>0>=1073741824){break b}ri=a+56|0;pi=q[ri>>2];si=li<<2;li=Mm(oi);si=si+li|0;oi=pi-mi|0;pi=oi+li|0;if((oi|0)>=1){Cn(li,mi,oi)}q[a+52>>2]=li;q[a+60>>2]=si;q[ri>>2]=pi;if(!mi){break c}An(mi)}mi=q[a+40>>2];ni=q[ni>>2]-q[Vh+24>>2]|0;li=ni>>2;d:{if(q[a+48>>2]-mi>>2>>>0>=li>>>0){break d}if(li>>>0>=1073741824){break a}oi=a+44|0;ri=q[oi>>2];pi=li<<2;li=Mm(ni);pi=pi+li|0;ni=ri-mi|0;ri=ni+li|0;if((ni|0)>=1){Cn(li,mi,ni)}q[a+40>>2]=li;q[a+48>>2]=pi;q[oi>>2]=ri;if(!mi){break d}An(mi)}o[a+24|0]=1;q[a+64>>2]=Vh}T=qi+16|0;return}ab(14164);F()}ab(14164);F()}function Fk(a){var Vh=0,ti=0,ui=0,vi=0,wi=0,xi=0,yi=0,Ai=0,Bi=0,Ci=0,Di=0,Ei=0,Fi=0;ui=T-32|0;T=ui;xi=a+56|0;q[xi>>2]=q[a+52>>2];yi=a+44|0;q[yi>>2]=q[a+40>>2];Vh=q[a+64>>2];if(q[Vh+28>>2]!=q[Vh+24>>2]){Bi=a+40|0;Ci=a+52|0;Di=a+60|0;Ei=a+48|0;while(1){ti=q[q[Vh+24>>2]+(Ai<<2)>>2];a:{if((ti|0)==-1){break a}q[ui+24>>2]=wi;Vh=q[xi>>2];b:{if((Vh|0)!=q[Di>>2]){q[Vh>>2]=wi;q[xi>>2]=Vh+4;break b}Hk(Ci,ui+24|0)}q[ui+16>>2]=ti;q[ui+8>>2]=0;c:{if(!(q[q[a+12>>2]+(Ai>>>3&536870908)>>2]>>>(Ai&31)&1)){break c}d:{Vh=ti+1|0;Vh=(Vh>>>0)%3|0?Vh:ti+ -2|0;if(!((Vh|0)==-1|q[q[a>>2]+(Vh>>>3&536870908)>>2]>>>(Vh&31)&1)){Vh=q[q[q[a+64>>2]+12>>2]+(Vh<<2)>>2];if((Vh|0)!=-1){break d}}q[ui+8>>2]=-1;break c}vi=Vh+1|0;Vh=(vi>>>0)%3|0?vi:Vh+ -2|0;q[ui+8>>2]=Vh;if((Vh|0)==-1){break c}while(1){q[ui+16>>2]=Vh;e:{vi=Vh+1|0;ti=Vh;Vh=(vi>>>0)%3|0?vi:Vh+ -2|0;if(!((Vh|0)==-1|q[q[a>>2]+(Vh>>>3&536870908)>>2]>>>(Vh&31)&1)){Vh=q[q[q[a+64>>2]+12>>2]+(Vh<<2)>>2];if((Vh|0)!=-1){break e}}q[ui+8>>2]=-1;break c}vi=Vh+1|0;Vh=(vi>>>0)%3|0?vi:Vh+ -2|0;q[ui+8>>2]=Vh;if((Vh|0)!=-1){continue}break}}Fi=a+28|0;q[q[Fi>>2]+(ti<<2)>>2]=q[ui+24>>2];Vh=q[yi>>2];f:{if((Vh|0)!=q[Ei>>2]){q[Vh>>2]=q[ui+16>>2];q[yi>>2]=Vh+4;break f}zi(Bi,ui+16|0)}wi=wi+1|0;Vh=q[a+64>>2];g:{vi=q[ui+16>>2];if((vi|0)==-1){break g}ti=vi+((vi>>>0)%3|0?-1:2)|0;if((ti|0)==-1){break g}ti=q[q[Vh+12>>2]+(ti<<2)>>2];if((ti|0)==-1){break g}ti=ti+((ti>>>0)%3|0?-1:2)|0;q[ui+8>>2]=ti;if((ti|0)==-1|(ti|0)==(vi|0)){break a}while(1){Vh=ti+1|0;Vh=(Vh>>>0)%3|0?Vh:ti+ -2|0;h:{if(!(q[q[a>>2]+(Vh>>>3&536870908)>>2]>>>(Vh&31)&1)){break h}q[ui+24>>2]=wi;Vh=q[xi>>2];i:{if((Vh|0)!=q[Di>>2]){q[Vh>>2]=wi;q[xi>>2]=Vh+4;break i}Hk(Ci,ui+24|0)}wi=wi+1|0;Vh=q[yi>>2];if((Vh|0)!=q[Ei>>2]){q[Vh>>2]=q[ui+8>>2];q[yi>>2]=Vh+4;break h}zi(Bi,ui+8|0)}q[q[Fi>>2]+(q[ui+8>>2]<<2)>>2]=q[ui+24>>2];Vh=q[a+64>>2];ti=q[ui+8>>2];if((ti|0)==-1){break g}ti=ti+((ti>>>0)%3|0?-1:2)|0;if((ti|0)==-1){break g}ti=q[q[Vh+12>>2]+(ti<<2)>>2];if((ti|0)==-1){break g}ti=ti+((ti>>>0)%3|0?-1:2)|0;q[ui+8>>2]=ti;if((ti|0)==-1){break a}if(q[ui+16>>2]!=(ti|0)){continue}break}break a}q[ui+8>>2]=-1}Ai=Ai+1|0;if(Ai>>>0>2]-q[Vh+24>>2]>>2>>>0){continue}break}}T=ui+32|0}function Gk(a,zi){var Gi=0,Hi=0,Ii=0,Ji=0,Ki=0,Li=0;Ii=q[a>>2];Gi=Ii+(zi>>>3&536870908)|0;q[Gi>>2]=q[Gi>>2]|1<<(zi&31);Ki=q[a+64>>2];Ji=(zi|0)==-1;Gi=-1;a:{if(Ji){break a}Hi=zi+1|0;Hi=(Hi>>>0)%3|0?Hi:zi+ -2|0;Gi=-1;if((Hi|0)==-1){break a}Gi=q[q[Ki>>2]+(Hi<<2)>>2]}Hi=q[a+12>>2];Li=(Gi>>>3&536870908)+Hi|0;q[Li>>2]=q[Li>>2]|1<<(Gi&31);b:{c:{if(!Ji){Gi=-1;Ji=((zi>>>0)%3|0?-1:2)+zi|0;if((Ji|0)!=-1){Gi=q[q[Ki>>2]+(Ji<<2)>>2]}Ji=Hi+(Gi>>>3&536870908)|0;q[Ji>>2]=q[Ji>>2]|1<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2]=0;zi=Vi-Zi|0;Yi=(zi|0)/12|0;b:{if(zi){if(Yi>>>0>=357913942){break b}Wi=Mm(zi);q[Ti>>2]=Wi;q[Ti+4>>2]=Wi;q[Ti+8>>2]=w(Yi,12)+Wi;zi=Dn(Wi,0,zi);Si=Yi;while(1){zi=zi+12|0;Si=Si+ -1|0;if(Si){continue}break}q[Ti+4>>2]=zi}if((Vi|0)!=(Zi|0)){zi=0;$i=r[Ui+84|0];aj=Ui+68|0;while(1){_i=w(zi,12);Si=_i+Zi|0;Ui=q[Si>>2];c:{if($i){Vi=Si+8|0;Si=Si+4|0;break c}Xi=q[aj>>2];Vi=Xi+(q[Si+8>>2]<<2)|0;Ui=q[Xi+(Ui<<2)>>2];Si=Xi+(q[Si+4>>2]<<2)|0}Xi=q[Si>>2];Si=Wi+_i|0;q[Si+8>>2]=q[Vi>>2];q[Si+4>>2]=Xi;q[Si>>2]=Ui;zi=zi+1|0;if(zi>>>0>>0){continue}break}}kk(a,Ti);a=q[Ti>>2];if(!a){break a}q[Ti+4>>2]=a;An(a);break a}bn();F()}T=Ti+16|0}function Jk(a,zi,bj){var cj=0,dj=0,ej=0,fj=0,gj=0,hj=0,ij=0,jj=0,kj=0,lj=0,mj=0,nj=0,oj=0,pj=0,qj=0,rj=0;hj=T-16|0;T=hj;gj=w(zi,12)+a|0;ij=gj+12|0;nj=gj+8|0;q[ij>>2]=q[nj>>2];q[hj+8>>2]=(bj|0)==-1?-1:(bj>>>0)/3|0;oj=gj+16|0;pj=a+4|0;ej=bj;while(1){gj=dj;jj=(dj|0)==1;a:{b:{if(!jj){dj=q[hj+8>>2];break b}if((ej|0)==-1){ej=-1;Kk(a,-1);break a}if((ej|0)==-1|(Kk(a,((ej>>>0)%3|0?-1:2)+ej|0)|0)==-1){break a}bj=ej+1|0;cj=(bj>>>0)%3|0?bj:ej+ -2|0;if((cj|0)==-1){break a}bj=cj+1|0;bj=(bj>>>0)%3|0?bj:cj+ -2|0;if((bj|0)==-1){break a}cj=q[q[q[pj>>2]+12>>2]+(bj<<2)>>2];if((cj|0)==-1){break a}bj=cj+1|0;bj=(bj>>>0)%3|0?bj:cj+ -2|0;if((bj|0)==-1){break a}dj=(bj>>>0)/3|0;q[hj+8>>2]=dj}kj=1<<(dj&31);lj=q[a+56>>2]+(dj>>>3&536870908)|0;mj=q[lj>>2];c:{if(kj&mj){break c}fj=0;while(1){q[lj>>2]=kj|mj;cj=q[ij>>2];d:{if((cj|0)!=q[oj>>2]){q[cj>>2]=dj;q[ij>>2]=cj+4;break d}Ck(nj,hj+8|0)}cj=fj+1|0;e:{if(!fj){break e}if(cj&1){if((bj|0)==-1){bj=-1;break e}fj=bj+1|0;bj=(fj>>>0)%3|0?fj:bj+ -2|0;break e}ej=jj?bj:ej;if((bj|0)==-1){bj=-1;break e}if((bj>>>0)%3){bj=bj+ -1|0;break e}bj=bj+2|0}bj=Kk(a,bj);if((bj|0)!=-1){dj=(bj>>>0)/3|0;q[hj+8>>2]=dj;fj=cj;kj=1<<(dj&31);lj=q[a+56>>2]+(dj>>>3&268435452)|0;mj=q[lj>>2];if(!(kj&mj)){continue}}break}if(!(cj&1)|(gj|0)!=1){break c}jj=q[ij>>2]+ -4|0;dj=q[jj>>2];fj=q[a+56>>2]+(dj>>>3&536870908)|0;cj=q[fj>>2];qj=fj,rj=eo(dj)&cj,q[qj>>2]=rj;q[ij>>2]=jj}dj=1;if(!gj){continue}}break}q[((zi<<2)+a|0)+44>>2]=ej;zi=q[ij>>2];ej=q[nj>>2];if((zi|0)!=(ej|0)){fj=zi-ej>>2;cj=q[a+56>>2];bj=0;while(1){gj=q[ej+(bj<<2)>>2];zi=cj+(gj>>>3&536870908)|0;a=q[zi>>2];qj=zi,rj=eo(gj)&a,q[qj>>2]=rj;bj=bj+1|0;if(bj>>>0>>0){continue}break}}T=hj+16|0}function Kk(a,zi){var bj=0,sj=0,tj=0,uj=0,vj=0;sj=-1;uj=-1;tj=-1;a:{b:{if((zi|0)==-1){break b}vj=1;uj=q[q[q[a+4>>2]+12>>2]+(zi<<2)>>2];bj=zi+1|0;bj=(bj>>>0)%3|0?bj:zi+ -2|0;if((bj|0)>=0){tj=(bj>>>0)/3|0;tj=q[(q[q[a>>2]+96>>2]+w(tj,12)|0)+(bj-w(tj,3)<<2)>>2]}c:{if((uj|0)==-1){break c}vj=0;bj=((uj>>>0)%3|0?-1:2)+uj|0;if((bj|0)<0){break c}sj=(bj>>>0)/3|0;sj=q[(q[q[a>>2]+96>>2]+w(sj,12)|0)+(bj-w(sj,3)<<2)>>2]}bj=-1;if((sj|0)!=(tj|0)){break a}tj=-1;d:{zi=((zi>>>0)%3|0?-1:2)+zi|0;if((zi|0)>=0){sj=(zi>>>0)/3|0;sj=q[(q[q[a>>2]+96>>2]+w(sj,12)|0)+(zi-w(sj,3)<<2)>>2];if(vj){break b}break d}sj=-1;if(!vj){break d}break b}zi=uj+1|0;zi=(zi>>>0)%3|0?zi:uj+ -2|0;if((zi|0)<0){break b}tj=q[q[a>>2]+96>>2];a=(zi>>>0)/3|0;tj=q[(tj+w(a,12)|0)+(zi-w(a,3)<<2)>>2]}bj=(sj|0)==(tj|0)?uj:-1}return bj}function Lk(a,zi){var wj=0,xj=0,yj=0,zj=0,Aj=0,Bj=0,Cj=0,Dj=0,Ej=0,Fj=0,Gj=0;xj=T-48|0;T=xj;q[xj+40>>2]=0;q[xj+32>>2]=0;q[xj+36>>2]=0;wj=Mm(8);q[wj+4>>2]=zi;q[wj>>2]=0;zi=wj+8|0;q[xj+40>>2]=zi;q[xj+36>>2]=zi;q[xj+32>>2]=wj;a:{b:{c:{d:{while(1){zi=zi+ -8|0;Bj=q[zi+4>>2];Gj=q[zi>>2];q[xj+36>>2]=zi;if(Gj){q[xj+24>>2]=0;q[xj+16>>2]=0;q[xj+20>>2]=0;Dj=1;zi=q[a>>2];Aj=q[zi+16>>2];zj=q[zi+12>>2];wj=q[zi+20>>2];e:{if((zj|0)<(wj|0)?1:(zj|0)<=(wj|0)?t[zi+8>>2]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>0>=536870912){break d}zj=zi<<3;yj=wj-Cj|0;wj=yj>>2;yj=yj>>3>>>0<268435455?wj>>>0>>0?Ej:wj:536870911;zi=0;g:{if(!yj){break g}if(yj>>>0>=536870912){break c}zi=Mm(yj<<3)}wj=zj+zi|0;q[wj+4>>2]=0;q[wj>>2]=Bj;yj=zi+(yj<<3)|0;wj=wj+8|0;if((Fj|0)>=1){Cn(zi,Cj,Fj)}q[xj+40>>2]=yj;q[xj+36>>2]=wj;q[xj+32>>2]=zi;if(!Cj){break f}An(Cj)}Dj=Dj+1|0;if(Dj>>>0>>0){continue}break}}zi=q[xj+36>>2];wj=q[xj+32>>2];if((zi|0)!=(wj|0)){continue}break}a=1;break a}bn();F()}ab(14232);F()}wj=q[xj+32>>2];a=0}if(wj){q[xj+36>>2]=wj;An(wj)}T=xj+48|0;return a}function Mk(a,zi,Hj){var Ij=0,Jj=0,Kj=0,Lj=0;a:{if(a>>>0>5){break a}Kj=q[Hj+16>>2];Ij=q[Hj+12>>2];Jj=q[Hj+20>>2];if((Ij|0)<(Jj|0)?1:(Ij|0)<=(Jj|0)?t[Hj+8>>2]>Kj>>>0?0:1:0){break a}Ij=r[Kj+q[Hj>>2]|0];Kj=Kj+1|0;if(Kj>>>0<1){Jj=Jj+1|0}q[Hj+16>>2]=Kj;q[Hj+20>>2]=Jj;Jj=zi;if(Ij&128){if(!Mk(a+1|0,zi,Hj)){break a}a=q[zi>>2]<<7;q[zi>>2]=a;Ij=a|Ij&127}q[Jj>>2]=Ij;Lj=1}return Lj}function Nk(a,zi){var Hj=0,Mj=0,Nj=0,Oj=0,Pj=0,Qj=0,Rj=0,Sj=0,Tj=0,Uj=0;Mj=T-32|0;T=Mj;q[Mj+24>>2]=0;q[Mj+16>>2]=0;q[Mj+20>>2]=0;a:{Nj=q[a>>2];Hj=Nj;Pj=q[Hj+16>>2];Qj=t[Hj+8>>2]>Pj>>>0?0:1;Oj=q[Hj+12>>2];Hj=q[Hj+20>>2];b:{if((Oj|0)<(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>24;fk=(gk|0)<0?q[$j+4>>2]:dk;if((fk|0)!=(((bk|0)<0?q[kk>>2]:ak)|0)){break d}ek=(bk|0)<0?q[Vj>>2]:Vj;bk=q[$j>>2];ak=(gk|0)<0;e:{if(!ak){if(!fk){break e}ak=$j;if(r[ek|0]!=(bk&255)){break d}while(1){dk=dk+ -1|0;if(!dk){break e}bk=r[ek+1|0];ek=ek+1|0;ak=ak+1|0;if((bk|0)==r[ak|0]){continue}break}break d}if(!fk){break e}if(cm(ak?bk:$j,ek,fk)){break c}}ik=q[ck>>2];a=1}if((gk|0)>-1){break b}}An(q[$j>>2])}if(a>>>0>3){break a}f:{switch(a-1|0){case 0:case 1:break a;default:break f}}ck=ck+4|0;if((hk|0)!=(ck|0)){continue}break}}ik=0}T=$j+16|0;return ik}function Qk(a,zi){var Vj=0,lk=0,mk=0;lk=q[zi>>2];if(!lk){return}Vj=a+28|0;mk=q[Vj>>2];if(mk>>>0>2]){q[zi>>2]=0;q[mk>>2]=lk;q[Vj>>2]=q[Vj>>2]+4;return}Rk(a+24|0,zi)}function Rk(a,zi){var nk=0,ok=0,pk=0,qk=0,rk=0;a:{b:{c:{pk=q[a>>2];qk=q[a+4>>2]-pk>>2;nk=qk+1|0;if(nk>>>0<1073741824){pk=q[a+8>>2]-pk|0;rk=pk>>1;nk=pk>>2>>>0<536870911?rk>>>0>>0?nk:rk:1073741823;if(nk){if(nk>>>0>=1073741824){break c}ok=Mm(nk<<2)}pk=q[zi>>2];q[zi>>2]=0;zi=(qk<<2)+ok|0;q[zi>>2]=pk;pk=(nk<<2)+ok|0;qk=zi+4|0;nk=q[a+4>>2];ok=q[a>>2];if((nk|0)==(ok|0)){break b}while(1){nk=nk+ -4|0;rk=q[nk>>2];q[nk>>2]=0;zi=zi+ -4|0;q[zi>>2]=rk;if((nk|0)!=(ok|0)){continue}break}ok=q[a+4>>2];nk=q[a>>2];break a}bn();F()}ab(14300);F()}nk=ok}q[a>>2]=zi;q[a+8>>2]=pk;q[a+4>>2]=qk;if((nk|0)!=(ok|0)){while(1){ok=ok+ -4|0;a=q[ok>>2];q[ok>>2]=0;if(a){Hc(a+12|0,q[a+16>>2]);Ic(a,q[a+4>>2]);An(a)}if((nk|0)!=(ok|0)){continue}break}}if(nk){An(nk)}}function Sk(a,zi,sk,tk){var uk=0,vk=0,wk=0,xk=0;uk=T-16|0;T=uk;xk=a;vk=ph(zi,uk+12|0,sk);sk=q[vk>>2];if(sk){zi=0}else{sk=Mm(32);Rm(sk+16|0,q[tk>>2]);q[sk+28>>2]=0;q[sk+8>>2]=q[uk+12>>2];q[sk>>2]=0;q[sk+4>>2]=0;q[vk>>2]=sk;tk=sk;wk=q[q[zi>>2]>>2];if(wk){q[zi>>2]=wk;tk=q[vk>>2]}nh(q[zi+4>>2],tk);zi=zi+8|0;q[zi>>2]=q[zi>>2]+1;zi=1}o[xk+4|0]=zi;q[a>>2]=sk;T=uk+16|0}function Tk(a,zi){var sk=0,tk=0,yk=0;sk=q[zi+4>>2];a:{if(!sk){tk=q[zi+8>>2];if(q[tk>>2]==(zi|0)){break a}yk=zi+8|0;while(1){sk=q[yk>>2];yk=sk+8|0;tk=q[sk+8>>2];if((sk|0)!=q[tk>>2]){continue}break}break a}while(1){tk=sk;sk=q[sk>>2];if(sk){continue}break}}if(q[a>>2]==(zi|0)){q[a>>2]=tk}tk=a+8|0;q[tk>>2]=q[tk>>2]+ -1;$k(q[a+4>>2],zi);a=q[zi+28>>2];if(a){q[zi+32>>2]=a;An(a)}if(o[zi+27|0]<=-1){An(q[zi+16>>2])}An(zi)}function Uk(a,zi,zk){var Ak=0,Bk=0,Ck=0,Dk=0,Ek=0;Ak=Mm(40);o[a+8|0]=0;q[a+4>>2]=zi+4;q[a>>2]=Ak;zi=zk+8|0;q[Ak+24>>2]=q[zi>>2];Bk=q[zk+4>>2];q[Ak+16>>2]=q[zk>>2];q[Ak+20>>2]=Bk;q[zk>>2]=0;q[zk+4>>2]=0;q[zi>>2]=0;q[Ak+36>>2]=0;q[Ak+28>>2]=0;q[Ak+32>>2]=0;Ck=zk+16|0;Bk=q[Ck>>2];zi=q[zk+12>>2];Dk=Bk-zi|0;if(Dk){zi=Ak+28|0;Ha(zi,Dk);Bk=q[Ck>>2];Ek=q[zi>>2];zi=q[zk+12>>2]}Cn(Ek,zi,Bk-zi|0);o[a+8|0]=1}function Vk(a,zi,zk){var Fk=0;Fk=a+4|0;a=fk(a,zi);a:{if((Fk|0)==(a|0)){break a}zi=q[a+32>>2];a=q[a+28>>2];if((zi-a|0)!=4){break a}q[zk>>2]=r[a|0]|r[a+1|0]<<8|(r[a+2|0]<<16|r[a+3|0]<<24)}}function Wk(a,zi,zk){var Gk=0,Hk=0,Ik=0,Jk=0;a:{zi=fk(a,zi);b:{if((zi|0)==(a+4|0)){break b}a=q[zi+28>>2];Gk=q[zi+32>>2];if((a|0)==(Gk|0)){break b}a=Gk-a|0;if(a&3){break b}Gk=a>>>2;Jk=zk+4|0;Hk=q[Jk>>2];a=q[zk>>2];Ik=Hk-a>>2;c:{if(Gk>>>0>Ik>>>0){Fa(zk,Gk-Ik|0);Hk=q[Jk>>2];a=q[zk>>2];break c}if(Gk>>>0>=Ik>>>0){break c}Hk=(Gk<<2)+a|0;q[zk+4>>2]=Hk}if((a|0)==(Hk|0)){break a}zk=a;a=q[zi+28>>2];Cn(zk,a,q[zi+32>>2]-a|0)}return}cn();F()}function Xk(a,zi,zk){var Kk=0;Kk=a+4|0;a=fk(a,zi);a:{if((Kk|0)==(a|0)){break a}zi=q[a+32>>2];a=q[a+28>>2];if((zi-a|0)!=8){break a}zi=r[a+4|0]|r[a+5|0]<<8|(r[a+6|0]<<16|r[a+7|0]<<24);q[zk>>2]=r[a|0]|r[a+1|0]<<8|(r[a+2|0]<<16|r[a+3|0]<<24);q[zk+4>>2]=zi}}function Yk(a,zi,zk){var Lk=0,Mk=0,Nk=0;Lk=a+4|0;a=fk(a,zi);a:{if((Lk|0)==(a|0)){break a}zi=a+32|0;Lk=q[zi>>2];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zk+4>>2];if(r[zi+12|0]?0:zi){break f}o[zk+12|0]=0;zk=q[zk+8>>2];h:{if((zk|0)==(a|0)){zk=a;break h}if(r[zk+12|0]){break g}}o[zk+12|0]=1;return}zi=q[zk+4>>2];if(zi){break f}break e}i:{if(zi){zi=zk;break i}o[zk+12|0]=1;o[Vk+12|0]=0;zi=q[zk+4>>2];q[Vk>>2]=zi;if(zi){q[zi+8>>2]=Vk}q[zk+8>>2]=q[Vk+8>>2];Sk=q[Vk+8>>2];j:{if((Vk|0)==q[Sk>>2]){q[Sk>>2]=zk;zi=q[Vk>>2];break j}q[Sk+4>>2]=zk}q[zk+4>>2]=Vk;q[Vk+8>>2]=zk;a=(a|0)==(Vk|0)?zk:a}Sk=q[zi>>2];k:{if(!(!Sk|r[Sk+12|0])){zk=zi;break k}zk=q[zi+4>>2];if(!(r[zk+12|0]?0:zk)){o[zi+12|0]=0;zk=q[zi+8>>2];if(r[zk+12|0]?(zk|0)!=(a|0):0){break g}o[zk+12|0]=1;return}if(Sk){if(!r[Sk+12|0]){zk=zi;break k}zk=q[zi+4>>2]}o[zk+12|0]=1;o[zi+12|0]=0;a=q[zk>>2];q[zi+4>>2]=a;if(a){q[a+8>>2]=zi}q[zk+8>>2]=q[zi+8>>2];a=q[zi+8>>2];q[(q[a>>2]==(zi|0)?a:a+4|0)>>2]=zk;q[zk>>2]=zi;q[zi+8>>2]=zk;Sk=zi}a=zk;zk=q[zk+8>>2];o[a+12|0]=r[zk+12|0];o[zk+12|0]=1;o[Sk+12|0]=1;zi=q[zk>>2];a=q[zi+4>>2];q[zk>>2]=a;if(a){q[a+8>>2]=zk}q[zi+8>>2]=q[zk+8>>2];a=q[zk+8>>2];q[((zk|0)==q[a>>2]?a:a+4|0)>>2]=zi;q[zi+4>>2]=zk;q[zk+8>>2]=zi;return}zi=q[zk+8>>2];zk=q[(q[zi>>2]==(zk|0)?zi+4|0:zi)>>2];continue}}o[Vk+12|0]=1}return}if(r[zi+12|0]){break e}Sk=zk;break d}o[Sk+12|0]=1;o[zk+12|0]=0;a=q[Sk+4>>2];q[zk>>2]=a;if(a){q[a+8>>2]=zk}q[Sk+8>>2]=q[zk+8>>2];a=q[zk+8>>2];q[(q[a>>2]==(zk|0)?a:a+4|0)>>2]=Sk;q[Sk+4>>2]=zk;q[zk+8>>2]=Sk;zi=zk}zk=q[Sk+8>>2];o[Sk+12|0]=r[zk+12|0];o[zk+12|0]=1;o[zi+12|0]=1;zi=q[zk+4>>2];a=q[zi>>2];q[zk+4>>2]=a;if(a){q[a+8>>2]=zk}q[zi+8>>2]=q[zk+8>>2];a=q[zk+8>>2];q[((zk|0)==q[a>>2]?a:a+4|0)>>2]=zi;q[zi>>2]=zk;q[zk+8>>2]=zi}function al(a){q[a>>2]=14380;Dn(a+4|0,0,80);return a}function bl(a,zi){var Zk=0;Zk=-1;a:{if((zi|0)==-1|(zi|0)>4){break a}zi=w(zi,12)+a|0;a=q[zi+20>>2];if((q[zi+24>>2]-a|0)<1){break a}Zk=q[a>>2]}return Zk}function cl(a){var zi=0,_k=0;zi=q[a+20>>2];a:{if((q[a+24>>2]-zi|0)<1){break a}zi=q[zi>>2];if((zi|0)==-1){break a}_k=q[q[a+8>>2]+(zi<<2)>>2]}return _k}function dl(a,$k){var al=0,bl=0,cl=0;al=q[a+8>>2];a=q[a+12>>2];a:{if((al|0)==(a|0)){break a}cl=a-al>>2;a=0;while(1){bl=q[(a<<2)+al>>2];if(q[bl+60>>2]==($k|0)){break a}a=a+1|0;if(a>>>0>>0){continue}break}bl=0}return bl}function el(a,$k){var dl=0,el=0;dl=q[a+8>>2];a=q[a+12>>2];if((dl|0)!=(a|0)){el=a-dl>>2;a=0;while(1){if(q[q[(a<<2)+dl>>2]+60>>2]==($k|0)){return a}a=a+1|0;if(a>>>0>>0){continue}break}}return-1}function fl(a,$k){var fl=0,gl=0,hl=0,il=0,jl=0;fl=T-16|0;T=fl;gl=a+12|0;hl=q[gl>>2];il=q[a+8>>2];jl=q[$k>>2];q[$k>>2]=0;q[fl+8>>2]=jl;n[q[q[a>>2]+8>>2]](a,hl-il>>2,fl+8|0);$k=q[fl+8>>2];q[fl+8>>2]=0;if($k){Hb($k)}T=fl+16|0;return(q[gl>>2]-q[a+8>>2]>>2)+ -1|0}function gl(a,$k,kl){a=a|0;$k=$k|0;kl=kl|0;var ll=0,ml=0,nl=0,ol=0,pl=0,ql=0;ol=T-16|0;T=ol;q[ol+12>>2]=$k;pl=a+8|0;ll=q[a+12>>2];ql=q[a+8>>2];ml=ll-ql>>2;a:{if((ml|0)>($k|0)){break a}nl=$k+1|0;if(nl>>>0>ml>>>0){hl(pl,nl-ml|0);break a}if(nl>>>0>=ml>>>0){break a}ml=ql+(nl<<2)|0;if((ml|0)!=(ll|0)){while(1){ll=ll+ -4|0;nl=q[ll>>2];q[ll>>2]=0;if(nl){Hb(nl)}if((ll|0)!=(ml|0)){continue}break}}q[a+12>>2]=ml}ll=q[q[kl>>2]+56>>2];b:{if((ll|0)>4){break b}ll=w(ll,12)+a|0;ml=ll+24|0;a=q[ml>>2];if((a|0)!=q[ll+28>>2]){q[a>>2]=$k;q[ml>>2]=a+4;break b}il(ll+20|0,ol+12|0)}$k=q[kl>>2];a=q[ol+12>>2];q[$k+60>>2]=a;ll=q[pl>>2];q[kl>>2]=0;kl=ll+(a<<2)|0;a=q[kl>>2];q[kl>>2]=$k;if(a){Hb(a)}T=ol+16|0}function hl(a,$k){var kl=0,rl=0,sl=0,tl=0,ul=0,vl=0,wl=0,xl=0,yl=0;rl=q[a+8>>2];sl=a+4|0;kl=q[sl>>2];if(rl-kl>>2>>>0>=$k>>>0){a=$k<<2;xl=sl,yl=Dn(kl,0,a)+a|0,q[xl>>2]=yl;return}a:{sl=q[a>>2];tl=kl-sl>>2;ul=tl+$k|0;if(ul>>>0<1073741824){tl=tl<<2;rl=rl-sl|0;wl=rl>>1;rl=rl>>2>>>0<536870911?wl>>>0