From bb25c00c983080407ba24357317d6b152fac5f4f Mon Sep 17 00:00:00 2001 From: Ben Coleman Date: Fri, 1 Mar 2024 10:25:16 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=85=B1=EF=B8=8F=20More=20builder=20update?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dist-single/gsots3d.js | 2 +- dist-single/gsots3d.js.map | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dist-single/gsots3d.js b/dist-single/gsots3d.js index 790c9ef..085a76a 100644 --- a/dist-single/gsots3d.js +++ b/dist-single/gsots3d.js @@ -6639,7 +6639,7 @@ var setAxes = function() { }(); // package.json -var version = "0.0.5-alpha.9"; +var version = "0.0.5-alpha.10"; // node_modules/cannon-es/dist/cannon-es.js var Mat3 = class _Mat3 { diff --git a/dist-single/gsots3d.js.map b/dist-single/gsots3d.js.map index 48cecf8..f70b893 100644 --- a/dist-single/gsots3d.js.map +++ b/dist-single/gsots3d.js.map @@ -1 +1 @@ -{"version":3,"sources":["../node_modules/loglevel/lib/loglevel.js","../src/core/gl.ts","../src/core/context.ts","../node_modules/twgl.js/dist/5.x/twgl-full.module.js","../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat3.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/quat.js","../node_modules/gl-matrix/esm/vec3.js","../node_modules/gl-matrix/esm/vec4.js","../package.json","../node_modules/cannon-es/dist/cannon-es.js","../src/engine/tuples.ts","../src/core/cache.ts","../src/engine/camera.ts","../shaders/shadowmap/glsl.frag","../shaders/shadowmap/glsl.vert","../src/engine/lights.ts","../src/engine/envmap.ts","../shaders/envmap/glsl.frag","../shaders/envmap/glsl.vert","../src/core/stats.ts","../src/engine/node.ts","../src/renderable/instance.ts","../src/renderable/billboard.ts","../src/engine/material.ts","../src/renderable/primitive.ts","../src/renderable/particles.ts","../shaders/particles/update.frag","../shaders/particles/update.vert","../shaders/particles/render.frag","../shaders/particles/render.vert","../src/renderable/model.ts","../src/parsers/mtl-parser.ts","../src/parsers/obj-parser.ts","../src/core/files.ts","../src/core/hud.ts","../src/engine/post-effects.ts","../shaders/phong/glsl.frag","../shaders/phong/glsl.vert","../shaders/billboard/glsl.frag","../shaders/billboard/glsl.vert","../src/engine/physics.ts","../src/renderable/builder.ts"],"sourcesContent":["/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n var _loggersByName = {};\n var defaultLogger = null;\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods() {\n /*jshint validthis:true */\n var level = this.getLevel();\n\n // Replace the actual methods.\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, this.name);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n\n // Return any important warnings.\n if (typeof console === undefinedType && level < this.levels.SILENT) {\n return \"No console available for logging\";\n }\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, _level, _loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, factory) {\n // Private instance variables.\n var self = this;\n /**\n * The level inherited from a parent logger (or a global default). We\n * cache this here rather than delegating to the parent so that it stays\n * in sync with the actual logging methods that we have installed (the\n * parent could change levels but we might not have rebuilt the loggers\n * in this child yet).\n * @type {number}\n */\n var inheritedLevel;\n /**\n * The default level for this logger, if any. If set, this overrides\n * `inheritedLevel`.\n * @type {number|null}\n */\n var defaultLevel;\n /**\n * A user-specific level for this logger. If set, this overrides\n * `defaultLevel`.\n * @type {number|null}\n */\n var userLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var cookieName = encodeURIComponent(storageKey);\n var location = cookie.indexOf(cookieName + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(\n cookie.slice(location + cookieName.length + 1)\n )[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n function normalizeLevel(input) {\n var level = input;\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n return level;\n } else {\n throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n }\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n if (userLevel != null) {\n return userLevel;\n } else if (defaultLevel != null) {\n return defaultLevel;\n } else {\n return inheritedLevel;\n }\n };\n\n self.setLevel = function (level, persist) {\n userLevel = normalizeLevel(level);\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(userLevel);\n }\n\n // NOTE: in v2, this should call rebuild(), which updates children.\n return replaceLoggingMethods.call(self);\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = normalizeLevel(level);\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n userLevel = null;\n clearPersistedLevel();\n replaceLoggingMethods.call(self);\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n self.rebuild = function () {\n if (defaultLogger !== self) {\n inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n }\n replaceLoggingMethods.call(self);\n\n if (defaultLogger === self) {\n for (var childName in _loggersByName) {\n _loggersByName[childName].rebuild();\n }\n }\n };\n\n // Initialize all the internal levels.\n inheritedLevel = normalizeLevel(\n defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n );\n var initialLevel = getPersistedLevel();\n if (initialLevel != null) {\n userLevel = normalizeLevel(initialLevel);\n }\n replaceLoggingMethods.call(self);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n defaultLogger = new Logger();\n\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name,\n defaultLogger.methodFactory\n );\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","// ===== gl.ts ==========================================================\n// Interactions with the GL context, as a global singleton\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport log from 'loglevel'\n\n/** A map of uniforms that can be used when WebGL rendering, typically applied with twlg.setUniforms() */\nexport type UniformSet = { [key: string]: number | number[] | mat4 | WebGLTexture | null }\n\n// Memoized global WebGL2 context\nlet glContext: WebGL2RenderingContext | undefined\n\n/**\n * Get the WebGL2 context, if it doesn't exist it will be created for the provided canvas element, and memoized\n * @returns {WebGL2RenderingContext} - Global WebGL2 context\n * @param {boolean} aa - Enable antialiasing\n * @param {string} selector - CSS selector for locating the canvas element\n */\nexport function getGl(selector = 'canvas', aa = true) {\n if (glContext) {\n return glContext\n }\n\n log.info(`🖌️ Creating new WebGL2 context for: '${selector}'`)\n\n const canvasElement = document.querySelector(selector) as HTMLElement\n if (!canvasElement) {\n log.error(`💥 FATAL! Unable to find element with selector: '${selector}'`)\n return undefined\n }\n\n if (canvasElement && canvasElement.tagName !== 'CANVAS') {\n log.error(`💥 FATAL! Element with selector: '${selector}' is not a canvas element`)\n return undefined\n }\n\n const canvas = canvasElement as HTMLCanvasElement\n if (!canvas) {\n log.error(`💥 FATAL! Unable to find canvas element with selector: '${selector}'`)\n return undefined\n }\n\n glContext = canvas.getContext('webgl2', { antialias: aa }) ?? undefined\n\n if (!glContext) {\n log.error(`💥 Unable to create WebGL2 context, maybe it's not supported on this device`)\n return undefined\n }\n\n log.info(`📐 Internal: ${canvas.width} x ${canvas.height}, display: ${canvas.clientWidth} x ${canvas.clientHeight}`)\n\n return glContext\n}\n","// ===== context.ts ===========================================================\n// Main rendering context, this is the core of the library\n// Ben Coleman, 2023\n// ============================================================================\n\nimport log from 'loglevel'\nimport * as CANNON from 'cannon-es'\nimport * as twgl from 'twgl.js'\nimport { mat4, vec3 } from 'gl-matrix'\n\nimport { version } from '../../package.json'\nimport { getGl, UniformSet } from './gl.ts'\nimport { RGB, XYZ, Tuples } from '../engine/tuples.ts'\nimport { ModelCache, ProgramCache, TextureCache } from './cache.ts'\nimport { LightDirectional, LightPoint } from '../engine/lights.ts'\nimport { Camera, CameraType } from '../engine/camera.ts'\nimport { Material } from '../engine/material.ts'\nimport { DynamicEnvironmentMap, EnvironmentMap } from '../engine/envmap.ts'\nimport { Instance } from '../renderable/instance.ts'\nimport { Billboard, BillboardType } from '../renderable/billboard.ts'\nimport { PrimitiveCube, PrimitivePlane, PrimitiveSphere, PrimitiveCylinder } from '../renderable/primitive.ts'\nimport { ParticleSystem } from '../renderable/particles.ts'\nimport { Model } from '../renderable/model.ts'\nimport { HUD } from './hud.ts'\nimport { Stats } from './stats.ts'\nimport { PostEffects } from '../engine/post-effects.ts'\nimport { RenderableBuilder } from '../renderable/builder.ts'\n\n// Import shaders, tsup will inline these as text strings\nimport fragShaderPhong from '../../shaders/phong/glsl.frag'\nimport vertShaderPhong from '../../shaders/phong/glsl.vert'\nimport fragShaderBill from '../../shaders/billboard/glsl.frag'\nimport vertShaderBill from '../../shaders/billboard/glsl.vert'\n\n/** @ignore Total max dynamic lights */\nconst MAX_LIGHTS = 16\n\n/**\n * The main rendering context. This is the effectively main entry point for the library.\n * Typically you will create a single instance of this class using init() and use it to render your scene.\n */\nexport class Context {\n private gl: WebGL2RenderingContext\n private started: boolean\n private instances: Map // Keyed on instance id\n private instancesTrans: Map\n private instancesParticles: Map\n private cameras: Map\n private activeCameraName: string\n private _envmap?: EnvironmentMap\n private dynamicEnvMap?: DynamicEnvironmentMap\n private renderPass: number\n\n /** Global directional light */\n public globalLight: LightDirectional\n\n /** All the dynamic point lights in the scene */\n public lights: LightPoint[]\n\n /** Main camera for this context */\n private _camera: Camera\n\n /** Show extra debug details on the canvas */\n public debug: boolean\n\n /** Optional post effects filter to apply to the output image */\n private postEffects?: PostEffects\n\n /**\n * The pre-render update function, called every frame.\n * Hook in your custom logic and processing here\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n public update: (delta: number, now?: number) => void = () => {}\n\n /** A HUD you can use to render HTML elements over the canvas */\n public readonly hud: HUD\n\n /** Gamma correction value, default 1.0 */\n public gamma: number\n\n /**\n * Integration with cannon-es for physics, set the CANNON.World you are using here.\n * When set, world stepping will be called for you in the core rendering loop\n */\n public physicsWorld?: CANNON.World\n\n /** Set the fixed time step for physics stepping, only used when physicsWorld is set */\n public physicsTimeStep: number\n\n /** Backface culling */\n public disableCulling = false\n\n // ==== Getters =============================================================\n\n /** Get the active camera */\n get camera() {\n return this._camera\n }\n\n /** Get the name of the active camera */\n get cameraName() {\n return this.activeCameraName\n }\n\n /** Get the current EnvironmentMap for the scene */\n get envmap() {\n return this._envmap\n }\n\n /** Constructor is private, use init() to create a new context */\n private constructor(gl: WebGL2RenderingContext) {\n this.gl = gl\n this.started = false\n this.debug = false\n this.gamma = 1.0\n this.instances = new Map()\n this.instancesTrans = new Map()\n this.instancesParticles = new Map()\n this.cameras = new Map()\n this.lights = []\n this.renderPass = 0\n this.physicsTimeStep = 1 / 60\n\n // Main global light\n this.globalLight = new LightDirectional()\n this.globalLight.setAsPosition(20, 50, 30)\n\n const defaultCamera = new Camera(CameraType.PERSPECTIVE)\n this.cameras.set('default', defaultCamera)\n this._camera = defaultCamera\n this.activeCameraName = 'default'\n\n this.hud = new HUD(gl.canvas)\n\n this.setLogLevel('info')\n\n log.info(`👑 GSOTS-3D context created, v${version}`)\n }\n\n /**\n * Create & initialize a new Context which will render into provided canvas. This is where you start when using the library.\n * @param canvasSelector CSS selector for canvas element, default is 'canvas'\n * @param antiAlias Enable anti-aliasing in the renderer, default is true\n */\n static async init(canvasSelector = 'canvas', antiAlias = true) {\n const gl = getGl(canvasSelector, antiAlias)\n\n if (!gl) {\n log.error('💥 Failed to create WebGL context, this is extremely bad news')\n throw new Error('Failed to get WebGL context')\n }\n\n // Create the context around the WebGL2 context\n const ctx = new Context(gl)\n\n const canvas = gl.canvas\n ctx.camera.aspectRatio = canvas.clientWidth / canvas.clientHeight\n\n // Load shaders and put into global cache\n const phongProgInfo = twgl.createProgramInfo(gl, [vertShaderPhong, fragShaderPhong])\n ProgramCache.init(phongProgInfo)\n ProgramCache.instance.add(ProgramCache.PROG_PHONG, phongProgInfo)\n ProgramCache.instance.add(ProgramCache.PROG_BILLBOARD, twgl.createProgramInfo(gl, [vertShaderBill, fragShaderBill]))\n log.info(`🎨 Loaded all shaders & programs, GL is ready`)\n\n gl.enable(gl.DEPTH_TEST)\n gl.enable(gl.BLEND)\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)\n\n // Bind to the render function\n ctx.render = ctx.render.bind(ctx)\n\n // Global texture cache, needs to be initialized after GL context is ready\n TextureCache.init(gl)\n\n return ctx\n }\n\n /**\n * Main render loop, called every frame by the context when started\n * @param now Current time in milliseconds\n */\n private async render(now: number) {\n if (!this.gl) return\n\n Stats.updateTime(now)\n\n // Move camera before any rendering\n this.camera.update()\n\n // -----------------------------------------------------------------------\n // RENDER CORE - Render into the dynamic environment map(s) if any\n // -----------------------------------------------------------------------\n if (this.dynamicEnvMap) {\n // This is a rare case of passing the context to the object, but it's needed for the dynamic env map\n this.dynamicEnvMap.update(this.gl, this)\n }\n\n // -------------------------------------------------------------\n // RENDER CORE - Render the shadow map from the global light\n // -------------------------------------------------------------\n if (this.globalLight.shadowsEnabled) {\n // Switch to front face culling for shadow map, yeah it's weird but it works!\n this.gl.cullFace(this.gl.FRONT)\n this.gl.enable(this.gl.POLYGON_OFFSET_FILL)\n\n const shadowOpt = this.globalLight.shadowMapOptions\n this.gl.polygonOffset(shadowOpt?.polygonOffset ?? 0, 1)\n\n // Bind the shadow map framebuffer and render the scene from the light's POV\n // Using the special shadow map program as an override for the whole rendering pass\n twgl.bindFramebufferInfo(this.gl, this.globalLight.shadowMapFrameBufffer)\n const shadowCam = this.globalLight.getShadowCamera(this.camera)\n\n if (shadowCam) {\n this.addCamera('__shadow', shadowCam)\n this.renderWithCamera(shadowCam, this.globalLight.shadowMapProgram)\n }\n\n // Switch back to back face culling\n this.gl.cullFace(this.gl.BACK)\n this.gl.disable(this.gl.POLYGON_OFFSET_FILL)\n }\n\n // -------------------------------------------------------------------------------------\n // RENDER CORE - FINAL: Render the scene from active camera into the main framebuffer\n // -------------------------------------------------------------------------------------\n if (this.postEffects) {\n // Render the main camera view into the post effects framebuffer\n twgl.bindFramebufferInfo(this.gl, this.postEffects.frameBuffer)\n this.renderWithCamera(this.camera)\n\n // Then render the post effects to the screen\n this.postEffects.renderToScreen(this.gl)\n } else {\n twgl.bindFramebufferInfo(this.gl, null)\n this.renderWithCamera(this.camera)\n }\n\n // **** FINAL POST RENDER STEPS ****\n\n this.hud.render(this.debug, this.camera)\n\n // Call the external update function\n this.update(Stats.deltaTime, now)\n\n // Advance the physics simulation if configured\n if (this.physicsWorld) {\n this.physicsWorld.step(this.physicsTimeStep, Stats.prevTime)\n }\n\n // Reset stats for next frame\n Stats.resetPerFrame()\n Stats.frameCount++\n this.renderPass = 0\n\n // Loop forever or stop if not started\n if (this.started) requestAnimationFrame(this.render)\n }\n\n /**\n * Render the scene from the given camera, used internally for rendering both the main view,\n * but also shadow maps and dynamic env maps\n * @param camera\n */\n renderWithCamera(camera: Camera, programOverride?: twgl.ProgramInfo) {\n if (!this.gl) return\n this.renderPass++\n\n // Clear the framebuffer and depth buffer\n this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT)\n\n // Do this in every frame since camera can move\n const camMatrix = camera.matrix\n\n // Work out what reflection map to use, if any\n // NOTE: This *not* part of the material because it's too hard to dynamically change\n let reflectMap: WebGLTexture | null = this._envmap?.texture ?? null\n\n // As there is only one dynamic reflection envmap, we can use it across all instances\n // But ONLY set this when the camera is NOT rendering into it!\n if (this.dynamicEnvMap) {\n if (!camera.usedForEnvMap) {\n reflectMap = this.dynamicEnvMap.texture\n }\n }\n\n // The uniforms that are the same for all instances\n const uniforms = {\n u_gamma: this.gamma,\n\n u_worldInverseTranspose: mat4.create(), // Updated per instance\n u_worldViewProjection: mat4.create(), // Updated per instance\n u_view: mat4.invert(mat4.create(), camMatrix),\n u_proj: camera.projectionMatrix,\n u_camPos: camera.position,\n\n u_reflectionMap: reflectMap,\n\n u_shadowMap: this.globalLight.shadowMapTexture,\n u_shadowMatrix: this.globalLight.getShadowMatrix(this.camera) ?? mat4.create(),\n } as UniformSet\n\n // ------------------------------------------------------------------------------\n // RENDER CORE - Draw envmap around the scene first, as a skybox background\n // ------------------------------------------------------------------------------\n if (this._envmap) {\n this._envmap.render(uniforms.u_view, uniforms.u_proj, camera)\n }\n\n // ------------------------------------------------\n // RENDER CORE - Process lighting\n // ------------------------------------------------\n\n // Apply global light to the two programs\n uniforms.u_lightDirGlobal = this.globalLight.uniforms\n\n // Only sort lights if we have more than MAX_LIGHTS, it's expensive!\n if (this.lights.length > MAX_LIGHTS) {\n // Sort lights by distance to camera so we can use the closest ones\n this.lights.sort((lightA, lightB) => {\n const ad = vec3.distance(lightA.position, this.camera.position)\n const bd = vec3.distance(lightB.position, this.camera.position)\n return ad - bd\n })\n }\n\n // Add the point lights into u_lightsPos array up to MAX_LIGHTS\n let lightCount = 0\n for (const light of this.lights) {\n if (lightCount >= MAX_LIGHTS) break\n if (!light.enabled) continue\n\n uniforms[`u_lightsPos[${lightCount++}]`] = light.uniforms\n }\n\n uniforms.u_lightsPosCount = lightCount\n\n // ------------------------------------------------\n // RENDER CORE - Draw all standard opaque instances\n // ------------------------------------------------\n if (this.disableCulling) this.gl.disable(this.gl.CULL_FACE)\n else this.gl.enable(this.gl.CULL_FACE)\n this.gl.enable(this.gl.BLEND)\n this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA)\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [_id, instance] of this.instances) {\n instance.render(this.gl, uniforms, programOverride)\n\n // Update physics body position from instance only on first render pass\n if (this.renderPass == 1) instance.updateFromPhysicsBody()\n }\n\n // ------------------------------------------------\n // RENDER CORE - Draw all transparent instances\n // ------------------------------------------------\n\n // Sort transparent instances by distance to camera\n // TODO: Maybe remove this in scenes with lots of transparent instances?\n const instancesTransArray = Array.from(this.instancesTrans.values())\n instancesTransArray.sort((a, b) => {\n const ad = Tuples.distance(a.position ?? [0, 0, 0], this.camera.position)\n const bd = Tuples.distance(b.position ?? [0, 0, 0], this.camera.position)\n return bd - ad\n })\n\n this.gl.disable(this.gl.CULL_FACE)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const instance of instancesTransArray) {\n instance.render(this.gl, uniforms, programOverride)\n\n // Update physics body position from instance only on first render pass\n if (this.renderPass == 1) instance.updateFromPhysicsBody()\n }\n\n // ------------------------------------------------\n // RENDER CORE - Draw all particle systems\n // ------------------------------------------------\n this.gl.depthMask(false)\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [_id, instance] of this.instancesParticles) {\n instance.render(this.gl, uniforms, programOverride)\n }\n\n this.gl.depthMask(true)\n }\n\n /**\n * Start the rendering loop, without calling this nothing will render\n */\n start() {\n log.info('🚀 Starting main GSOTS render loop!')\n\n this.hud.hideLoading()\n this.started = true\n // Restart the render loop\n requestAnimationFrame(this.render)\n }\n\n /**\n * Stop the rendering loop\n */\n stop() {\n log.info('🛑 Stopping main GSOTS render loop')\n\n this.started = false\n }\n\n /**\n * Set the log level for the library\n * @param level - Log level to set, default is 'info'\n */\n setLogLevel(level: log.LogLevelNames) {\n log.setLevel(level)\n }\n\n /**\n * Resize the canvas & viewport to match the size of the HTML element that contains it\n * @param viewportOnly - Only resize the GL viewport, not the canvas, default false\n */\n resize(viewportOnly = false) {\n const canvas = this.gl.canvas\n\n if (!viewportOnly) twgl.resizeCanvasToDisplaySize(canvas)\n\n this.gl.viewport(0, 0, canvas.width, canvas.height)\n this.camera.aspectRatio = canvas.width / canvas.height\n\n log.info(\n `📐 RESIZE Internal: ${canvas.width} x ${canvas.height}, display: ${canvas.clientWidth} x ${canvas.clientHeight}`,\n )\n }\n\n /**\n * Internal function to add an instance to the scene\n */\n private addInstance(instance: Instance, material: Material) {\n if (material.opacity !== undefined && material.opacity < 1) {\n this.instancesTrans.set(instance.id, instance)\n } else {\n this.instances.set(instance.id, instance)\n }\n }\n\n /**\n * Model loader, loads an OBJ model from a file via URL or path and adds it to the cache\n * This is preferred over calling Model.parse() directly\n * @param path Base path to the model file, e.g. './renderable/'\n * @param fileName Name of the model file, e.g 'teapot.obj'\n * @param filterTextures Apply texture filtering as materials are loaded\n * @param flipTextureY Flip the Y coordinate of the texture\n */\n async loadModel(path: string, fileName: string, filterTextures = true, flipY = false, flipUV = true) {\n const modelName = fileName.split('.')[0]\n\n // Check if model is already loaded\n if (ModelCache.instance.get(modelName, false)) {\n log.warn(`⚠️ Model '${modelName}' already loaded, skipping`)\n return\n }\n\n // Load the model and always flip the UV\n const model = await Model.parse(path, fileName, filterTextures, flipY, flipUV)\n\n ModelCache.instance.add(model)\n }\n\n /**\n * Add or replace a named camera to the scene\n * @param name Name of the camera\n * @param camera Camera instance\n */\n addCamera(name: string, camera: Camera) {\n this.cameras.set(name, camera)\n }\n\n /**\n * Get a camera by name\n * @param name Name of the camera\n */\n getCamera(name: string) {\n return this.cameras.get(name)\n }\n\n /**\n * Set the active camera, rendering will switch to this camera's view\n * @param name Name of the camera to set as active\n */\n setActiveCamera(name: string) {\n if (name == this.activeCameraName) return\n\n const camera = this.cameras.get(name)\n if (!camera) {\n throw new Error(`💥 Unable to set active camera to '${name}', camera not found`)\n }\n\n this.camera.active = false\n this._camera = camera\n this.camera.active = true\n this.activeCameraName = name\n\n log.info(`📷 Active camera switched to '${name}'`)\n }\n\n // ==========================================================================\n // Methods to create new instances of renderable objects & things\n // ==========================================================================\n\n /**\n * Create a new model instance, which should have been previously loaded into the cache\n * @param modelName - Name of the model previously loaded into the cache, don't include the file extension\n */\n createModelInstance(modelName: string) {\n const model = ModelCache.instance.get(modelName)\n if (!model) {\n throw new Error(`💥 Unable to create model instance for ${modelName}`)\n }\n\n const instance = new Instance(model)\n this.instances.set(instance.id, instance)\n Stats.triangles += model.triangleCount\n Stats.instances++\n\n return instance\n }\n\n /**\n * Create an instance of a primitive sphere\n * @param material - Material to apply to the sphere\n * @param radius - Radius of the sphere\n * @param subdivisionsH - Number of subdivisions along the horizontal\n * @param subdivisionsV - Number of subdivisions along the vertical\n */\n createSphereInstance(material: Material, radius = 5, subdivisionsH = 16, subdivisionsV = 8) {\n const sphere = new PrimitiveSphere(this.gl, radius, subdivisionsH, subdivisionsV)\n sphere.material = material\n\n const instance = new Instance(sphere)\n this.addInstance(instance, material)\n Stats.triangles += sphere.triangleCount\n Stats.instances++\n\n log.debug(`🟢 Created sphere instance, r:${radius}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive plane\n * @param material - Material to apply to the plane\n * @param width - Width of the plane\n * @param height - Height of the plane\n * @param subdivisionsW - Number of subdivisions along the width\n * @param subdivisionsH - Number of subdivisions along the height\n * @param tiling - Number of times to tile the texture over the plane\n */\n createPlaneInstance(material: Material, width = 5, height = 5, subdivisionsW = 1, subdivisionsH = 1, tiling = 1) {\n const plane = new PrimitivePlane(this.gl, width, height, subdivisionsW, subdivisionsH, tiling)\n plane.material = material\n\n const instance = new Instance(plane)\n this.addInstance(instance, material)\n Stats.triangles += plane.triangleCount\n Stats.instances++\n\n log.debug(`🟨 Created plane instance, w:${width} h:${height}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive cube\n */\n createCubeInstance(material: Material, size = 5, tilingFactor?: number) {\n const cube = new PrimitiveCube(this.gl, size, tilingFactor)\n cube.material = material\n\n const instance = new Instance(cube)\n this.addInstance(instance, material)\n Stats.triangles += cube.triangleCount\n Stats.instances++\n\n log.debug(`📦 Created cube instance, size:${size}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive cylinder\n */\n createCylinderInstance(material: Material, r = 2, h = 5, subdivisionsR = 16, subdivisionsH = 1, caps = true) {\n const cyl = new PrimitiveCylinder(this.gl, r, h, subdivisionsR, subdivisionsH, caps)\n cyl.material = material\n\n const instance = new Instance(cyl)\n this.addInstance(instance, material)\n Stats.triangles += cyl.triangleCount\n Stats.instances++\n\n log.debug(`🛢️ Created cylinder instance, r:${r}`)\n\n return instance\n }\n\n /**\n * Create an instance of a billboard/sprite in the scene\n * @param textureUrl - Path to the texture image file to use for the billboard\n * @param width - Width of the billboard (default: 5)\n * @param height - Height of the billboard (default: 5)\n * @param type - Type of billboard to create (default: CYLINDRICAL)\n */\n createBillboardInstance(material: Material, size = 5, type = BillboardType.CYLINDRICAL) {\n const billboard = new Billboard(this.gl, type, material, size)\n\n const instance = new Instance(billboard)\n\n this.addInstance(instance, material)\n\n Stats.triangles += 2\n Stats.instances++\n\n log.debug(`🚧 Created billboard instance of type: ${type} size: ${size}`)\n\n return instance\n }\n\n /**\n * Create a new point light in the scene\n * @param position - Position of the light\n * @param colour - Colour of the light, defaults to white\n * @param intensity - Intensity of the light\n * @returns The new light object\n */\n createPointLight(position: XYZ, colour: RGB = [1, 1, 1], intensity = 1) {\n const light = new LightPoint(position, colour)\n light.position = position\n light.colour = colour\n\n // A very simple scaling of the light attenuation\n // Users can still set the attenuation manually if they want\n light.constant /= intensity\n light.linear /= intensity\n light.quad /= intensity\n\n this.lights.push(light)\n\n log.debug(`🔆 Created point light, pos:${position} col:${colour} int:${intensity}`)\n\n return light\n }\n\n /**\n * Create a new particle system in the scene\n * @param maxParticles Maximum number of particles to allow in the system\n * @param baseSize Base size of the particles, default 2\n * @returns Both the instance and the particle system\n */\n createParticleSystem(maxParticles = 1000, baseSize = 2) {\n const particleSystem = new ParticleSystem(this.gl, maxParticles, baseSize)\n\n const instance = new Instance(particleSystem)\n instance.castShadow = false\n\n this.instancesParticles.set(instance.id, instance)\n Stats.instances++\n\n log.debug(`✨ Created particle system`)\n\n return { instance, particleSystem }\n }\n\n /**\n * Set the EnvironmentMap for the scene, will overwrite any existing envmap.\n * This will enable static reflections and create a 'skybox' around the scene\n * @param textureURLs - Array of 6 texture URLs to use for the map, in the order: +X, -X, +Y, -Y, +Z, -Z\n */\n setEnvmap(renderAsBackground = false, ...textureURLs: string[]) {\n this._envmap = new EnvironmentMap(this.gl, textureURLs)\n this._envmap.renderAsBackground = renderAsBackground\n }\n\n /**\n * Remove any current EnvironmentMap from the scene\n */\n removeEnvmap() {\n this._envmap = undefined\n }\n\n /**\n * Set and create a dynamic environment map which will enable dynamic/realtime reflections\n * @param position - Position to render reflections from\n * @param size - Size of the map to render, note higher sizes will come with a big performance hit\n */\n setDynamicEnvmap(position: XYZ, size = 256, renderDistance = 500) {\n this.dynamicEnvMap = new DynamicEnvironmentMap(this.gl, size, position, renderDistance)\n }\n\n /**\n * Remove instance from the scene, it will no longer be rendered\n * @param instance - Instance to remove\n */\n removeInstance(instance: Instance) {\n if (!instance) return\n\n if (instance.renderable instanceof ParticleSystem) {\n this.instancesParticles.delete(instance.id)\n return\n }\n\n this.instances.delete(instance.id)\n this.instancesTrans.delete(instance.id)\n }\n\n /**\n * Remove all instances from the scene\n */\n removeAllInstances() {\n this.instances.clear()\n this.instancesTrans.clear()\n this.instancesParticles.clear()\n }\n\n /**\n * Use a custom shader for post effects, user must provide their own shader\n * @param shaderCode - GLSL shader code for the post effect\n */\n setEffectCustom(shaderCode: string) {\n this.postEffects = new PostEffects(this.gl, shaderCode)\n log.info(`🌈 Post effects shader added`)\n }\n\n /**\n * Use bulit-in scanlines post effect shader\n * @param density - Density of the scanlines, default 1.5\n * @param opacity - Opacity of the scanlines, default 0.5\n * @param noise - Noise level, default 0.2\n * @param flicker - Flicker ammount, default 0.015\n */\n setEffectScanlines(density = 1.5, opacity = 0.5, noise = 0.2, flicker = 0.015) {\n this.postEffects = PostEffects.scanlines(this.gl, density, opacity, noise, flicker)\n\n log.info(`🌈 Post effects scanline shader added`)\n }\n\n /**\n * Use bulit-in glitch post effect shader\n * @param amount - Amount of glitch, default 0.01\n */\n setEffectGlitch(amount = 0.01) {\n this.postEffects = PostEffects.glitch(this.gl, amount)\n\n log.info(`🌈 Post effects glitch shader added`)\n }\n\n /**\n * Use bulit-in noise post effect shader\n * @param amount - Amount of noise, default 0.1\n * @param speed - Speed of noise pattern, default 5.0\n */\n setEffectNoise(amount = 0.2, speed = 5.0) {\n this.postEffects = PostEffects.noise(this.gl, amount, speed)\n\n log.info(`🌈 Post effects noise shader added`)\n }\n\n /**\n * Use bulit-in duotone post effect shader for monotone images\n * @param colour1 - First colour, default [0.15, 0.09, 0.309]\n * @param colour2 - Second colour, default [0.96, 0.39, 0.407]\n * @param contrast - Contrast, default 1.5\n */\n setEffectDuotone(colour1: RGB = [0.15, 0.09, 0.309], colour2: RGB = [0.96, 0.39, 0.407], contrast = 1.5) {\n this.postEffects = PostEffects.duotone(this.gl, colour1, colour2, contrast)\n\n log.info(`🌈 Post effects monochrome shader added`)\n }\n\n /**\n * Use bulit-in contrast post effect shader, which reduces the image to two solid colours\n * @param threshold\n * @param darkColour\n * @param lightColour\n */\n setEffectContrast(threshold = 0.2, darkColour: RGB = [0, 0, 0], lightColour: RGB = [1, 1, 1]) {\n this.postEffects = PostEffects.contrast(this.gl, threshold, darkColour, lightColour)\n\n log.info(`🌈 Post effects monochrome shader added`)\n }\n\n /**\n * Remove any post effects shader\n */\n removeEffect() {\n this.postEffects = undefined\n }\n\n /**\n * Build a instance of a custom renderable from a builder and add it to the scene\n * @param builder Builder with\n */\n createCustomInstance(builder: RenderableBuilder) {\n const renderable = builder.build(this.gl)\n const instance = new Instance(renderable)\n\n this.instances.set(instance.id, instance)\n Stats.triangles += renderable.triangleCount\n Stats.instances++\n\n log.debug(`🗿 Created a custom renderable instance`)\n\n return instance\n }\n}\n","/* @license twgl.js 5.5.3 Copyright (c) 2015, Gregg Tavares All Rights Reserved.\nAvailable via the MIT license.\nsee: http://github.com/greggman/twgl.js for details */\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n *\n * Vec3 math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new Vec3. In other words you can do this\n *\n * var v = v3.cross(v1, v2); // Creates a new Vec3 with the cross product of v1 x v2.\n *\n * or\n *\n * var v = v3.create();\n * v3.cross(v1, v2, v); // Puts the cross product of v1 x v2 in v\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any vector as the destination. So for example\n *\n * v3.cross(v1, v2, v1); // Puts the cross product of v1 x v2 in v1\n *\n * @module twgl/v3\n */\n\nlet VecType = Float32Array;\n\n/**\n * A JavaScript array with 3 values or a Float32Array with 3 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/v3.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Vec3\n * @memberOf module:twgl/v3\n */\n\n/**\n * Sets the type this library creates for a Vec3\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Vec3\n * @memberOf module:twgl/v3\n */\nfunction setDefaultType$1(ctor) {\n const oldType = VecType;\n VecType = ctor;\n return oldType;\n}\n\n/**\n * Creates a vec3; may be called with x, y, z to set initial values.\n * @param {number} [x] Initial x value.\n * @param {number} [y] Initial y value.\n * @param {number} [z] Initial z value.\n * @return {module:twgl/v3.Vec3} the created vector\n * @memberOf module:twgl/v3\n */\nfunction create$1(x, y, z) {\n const dst = new VecType(3);\n if (x) {\n dst[0] = x;\n }\n if (y) {\n dst[1] = y;\n }\n if (z) {\n dst[2] = z;\n }\n return dst;\n}\n\n/**\n * Adds two vectors; assumes a and b have the same dimension.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector tha tis the sum of a and b.\n * @memberOf module:twgl/v3\n */\nfunction add(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + b[0];\n dst[1] = a[1] + b[1];\n dst[2] = a[2] + b[2];\n\n return dst;\n}\n\n/**\n * Subtracts two vectors.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector that is the difference of a and b.\n * @memberOf module:twgl/v3\n */\nfunction subtract(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] - b[0];\n dst[1] = a[1] - b[1];\n dst[2] = a[2] - b[2];\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {number} t Interpolation coefficient.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerp(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t * (b[0] - a[0]);\n dst[1] = a[1] + t * (b[1] - a[1]);\n dst[2] = a[2] + t * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient vector t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} t Interpolation coefficients vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} the linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerpV(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t[0] * (b[0] - a[0]);\n dst[1] = a[1] + t[1] * (b[1] - a[1]);\n dst[2] = a[2] + t[2] * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Return max values of two vectors.\n * Given vectors a and b returns\n * [max(a[0], b[0]), max(a[1], b[1]), max(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The max components vector.\n * @memberOf module:twgl/v3\n */\nfunction max(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.max(a[0], b[0]);\n dst[1] = Math.max(a[1], b[1]);\n dst[2] = Math.max(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Return min values of two vectors.\n * Given vectors a and b returns\n * [min(a[0], b[0]), min(a[1], b[1]), min(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The min components vector.\n * @memberOf module:twgl/v3\n */\nfunction min(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.min(a[0], b[0]);\n dst[1] = Math.min(a[1], b[1]);\n dst[2] = Math.min(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Multiplies a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction mulScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] * k;\n dst[1] = v[1] * k;\n dst[2] = v[2] * k;\n\n return dst;\n}\n\n/**\n * Divides a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction divScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] / k;\n dst[1] = v[1] / k;\n dst[2] = v[2] / k;\n\n return dst;\n}\n\n/**\n * Computes the cross product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of a cross b.\n * @memberOf module:twgl/v3\n */\nfunction cross(a, b, dst) {\n dst = dst || new VecType(3);\n\n const t1 = a[2] * b[0] - a[0] * b[2];\n const t2 = a[0] * b[1] - a[1] * b[0];\n dst[0] = a[1] * b[2] - a[2] * b[1];\n dst[1] = t1;\n dst[2] = t2;\n\n return dst;\n}\n\n/**\n * Computes the dot product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @return {number} dot product\n * @memberOf module:twgl/v3\n */\nfunction dot(a, b) {\n return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);\n}\n\n/**\n * Computes the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} length of vector.\n * @memberOf module:twgl/v3\n */\nfunction length$1(v) {\n return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n}\n\n/**\n * Computes the square of the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} square of the length of vector.\n * @memberOf module:twgl/v3\n */\nfunction lengthSq(v) {\n return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];\n}\n\n/**\n * Computes the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distance(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/**\n * Computes the square of the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} square of the distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distanceSq(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return dx * dx + dy * dy + dz * dz;\n}\n\n/**\n * Divides a vector by its Euclidean length and returns the quotient.\n * @param {module:twgl/v3.Vec3} a The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The normalized vector.\n * @memberOf module:twgl/v3\n */\nfunction normalize(a, dst) {\n dst = dst || new VecType(3);\n\n const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];\n const len = Math.sqrt(lenSq);\n if (len > 0.00001) {\n dst[0] = a[0] / len;\n dst[1] = a[1] / len;\n dst[2] = a[2] / len;\n } else {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = 0;\n }\n\n return dst;\n}\n\n/**\n * Negates a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} -v.\n * @memberOf module:twgl/v3\n */\nfunction negate$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = -v[0];\n dst[1] = -v[1];\n dst[2] = -v[2];\n\n return dst;\n}\n\n/**\n * Copies a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A copy of v.\n * @memberOf module:twgl/v3\n */\nfunction copy$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0];\n dst[1] = v[1];\n dst[2] = v[2];\n\n return dst;\n}\n\n/**\n * Multiplies a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of products of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction multiply$1(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] * b[0];\n dst[1] = a[1] * b[1];\n dst[2] = a[2] * b[2];\n\n return dst;\n}\n\n/**\n * Divides a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of quotients of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction divide(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] / b[0];\n dst[1] = a[1] / b[1];\n dst[2] = a[2] / b[2];\n\n return dst;\n}\n\nvar v3 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n add: add,\n copy: copy$1,\n create: create$1,\n cross: cross,\n distance: distance,\n distanceSq: distanceSq,\n divide: divide,\n divScalar: divScalar,\n dot: dot,\n lerp: lerp,\n lerpV: lerpV,\n length: length$1,\n lengthSq: lengthSq,\n max: max,\n min: min,\n mulScalar: mulScalar,\n multiply: multiply$1,\n negate: negate$1,\n normalize: normalize,\n setDefaultType: setDefaultType$1,\n subtract: subtract\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * 4x4 Matrix math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new matrix. In other words you can do this\n *\n * const mat = m4.translation([1, 2, 3]); // Creates a new translation matrix\n *\n * or\n *\n * const mat = m4.create();\n * m4.translation([1, 2, 3], mat); // Puts translation matrix in mat.\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any matrix as the destination. So for example\n *\n * const mat = m4.identity();\n * const trans = m4.translation([1, 2, 3]);\n * m4.multiply(mat, trans, mat); // Multiplies mat * trans and puts result in mat.\n *\n * @module twgl/m4\n */\nlet MatType = Float32Array;\n\n/**\n * A JavaScript array with 16 values or a Float32Array with 16 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/m4.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Mat4\n * @memberOf module:twgl/m4\n */\n\n/**\n * Sets the type this library creates for a Mat4\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Mat4\n * @memberOf module:twgl/m4\n */\nfunction setDefaultType(ctor) {\n const oldType = MatType;\n MatType = ctor;\n return oldType;\n}\n\n/**\n * Negates a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} -m.\n * @memberOf module:twgl/m4\n */\nfunction negate(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = -m[ 0];\n dst[ 1] = -m[ 1];\n dst[ 2] = -m[ 2];\n dst[ 3] = -m[ 3];\n dst[ 4] = -m[ 4];\n dst[ 5] = -m[ 5];\n dst[ 6] = -m[ 6];\n dst[ 7] = -m[ 7];\n dst[ 8] = -m[ 8];\n dst[ 9] = -m[ 9];\n dst[10] = -m[10];\n dst[11] = -m[11];\n dst[12] = -m[12];\n dst[13] = -m[13];\n dst[14] = -m[14];\n dst[15] = -m[15];\n\n return dst;\n}\n\n/**\n * Creates a matrix.\n * @return {module:twgl/m4.Mat4} A new matrix.\n * @memberOf module:twgl/m4\n */\nfunction create() {\n return new MatType(16).fill(0);\n}\n\n/**\n * Copies a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] The matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A copy of m.\n * @memberOf module:twgl/m4\n */\nfunction copy(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n\n return dst;\n}\n\n/**\n * Creates an n-by-n identity matrix.\n *\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} An n-by-n identity matrix.\n * @memberOf module:twgl/m4\n */\nfunction identity(dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Takes the transpose of a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The transpose of m.\n * @memberOf module:twgl/m4\n */\n function transpose(m, dst) {\n dst = dst || new MatType(16);\n if (dst === m) {\n let t;\n\n t = m[1];\n m[1] = m[4];\n m[4] = t;\n\n t = m[2];\n m[2] = m[8];\n m[8] = t;\n\n t = m[3];\n m[3] = m[12];\n m[12] = t;\n\n t = m[6];\n m[6] = m[9];\n m[9] = t;\n\n t = m[7];\n m[7] = m[13];\n m[13] = t;\n\n t = m[11];\n m[11] = m[14];\n m[14] = t;\n return dst;\n }\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n dst[ 0] = m00;\n dst[ 1] = m10;\n dst[ 2] = m20;\n dst[ 3] = m30;\n dst[ 4] = m01;\n dst[ 5] = m11;\n dst[ 6] = m21;\n dst[ 7] = m31;\n dst[ 8] = m02;\n dst[ 9] = m12;\n dst[10] = m22;\n dst[11] = m32;\n dst[12] = m03;\n dst[13] = m13;\n dst[14] = m23;\n dst[15] = m33;\n\n return dst;\n}\n\n/**\n * Computes the inverse of a 4-by-4 matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The inverse of m.\n * @memberOf module:twgl/m4\n */\nfunction inverse(m, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n const tmp_0 = m22 * m33;\n const tmp_1 = m32 * m23;\n const tmp_2 = m12 * m33;\n const tmp_3 = m32 * m13;\n const tmp_4 = m12 * m23;\n const tmp_5 = m22 * m13;\n const tmp_6 = m02 * m33;\n const tmp_7 = m32 * m03;\n const tmp_8 = m02 * m23;\n const tmp_9 = m22 * m03;\n const tmp_10 = m02 * m13;\n const tmp_11 = m12 * m03;\n const tmp_12 = m20 * m31;\n const tmp_13 = m30 * m21;\n const tmp_14 = m10 * m31;\n const tmp_15 = m30 * m11;\n const tmp_16 = m10 * m21;\n const tmp_17 = m20 * m11;\n const tmp_18 = m00 * m31;\n const tmp_19 = m30 * m01;\n const tmp_20 = m00 * m21;\n const tmp_21 = m20 * m01;\n const tmp_22 = m00 * m11;\n const tmp_23 = m10 * m01;\n\n const t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -\n (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\n const t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -\n (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\n const t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -\n (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\n const t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -\n (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\n\n const d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\n\n dst[ 0] = d * t0;\n dst[ 1] = d * t1;\n dst[ 2] = d * t2;\n dst[ 3] = d * t3;\n dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -\n (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));\n dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -\n (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));\n dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -\n (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));\n dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -\n (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));\n dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -\n (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));\n dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -\n (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));\n dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -\n (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));\n dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -\n (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));\n dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -\n (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));\n dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -\n (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));\n dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -\n (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));\n dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -\n (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));\n\n return dst;\n}\n\n/**\n * Multiplies two 4-by-4 matrices with a on the left and b on the right\n * @param {module:twgl/m4.Mat4} a The matrix on the left.\n * @param {module:twgl/m4.Mat4} b The matrix on the right.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix product of a and b.\n * @memberOf module:twgl/m4\n */\nfunction multiply(a, b, dst) {\n dst = dst || new MatType(16);\n\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[ 4 + 0];\n const a11 = a[ 4 + 1];\n const a12 = a[ 4 + 2];\n const a13 = a[ 4 + 3];\n const a20 = a[ 8 + 0];\n const a21 = a[ 8 + 1];\n const a22 = a[ 8 + 2];\n const a23 = a[ 8 + 3];\n const a30 = a[12 + 0];\n const a31 = a[12 + 1];\n const a32 = a[12 + 2];\n const a33 = a[12 + 3];\n const b00 = b[0];\n const b01 = b[1];\n const b02 = b[2];\n const b03 = b[3];\n const b10 = b[ 4 + 0];\n const b11 = b[ 4 + 1];\n const b12 = b[ 4 + 2];\n const b13 = b[ 4 + 3];\n const b20 = b[ 8 + 0];\n const b21 = b[ 8 + 1];\n const b22 = b[ 8 + 2];\n const b23 = b[ 8 + 3];\n const b30 = b[12 + 0];\n const b31 = b[12 + 1];\n const b32 = b[12 + 2];\n const b33 = b[12 + 3];\n\n dst[ 0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;\n dst[ 1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;\n dst[ 2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;\n dst[ 3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;\n dst[ 4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;\n dst[ 5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;\n dst[ 6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;\n dst[ 7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;\n dst[ 8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;\n dst[ 9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;\n dst[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;\n dst[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;\n dst[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;\n dst[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;\n dst[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;\n dst[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;\n\n return dst;\n}\n\n/**\n * Sets the translation component of a 4-by-4 matrix to the given\n * vector.\n * @param {module:twgl/m4.Mat4} a The matrix.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with translation set.\n * @memberOf module:twgl/m4\n */\nfunction setTranslation(a, v, dst) {\n dst = dst || identity();\n if (a !== dst) {\n dst[ 0] = a[ 0];\n dst[ 1] = a[ 1];\n dst[ 2] = a[ 2];\n dst[ 3] = a[ 3];\n dst[ 4] = a[ 4];\n dst[ 5] = a[ 5];\n dst[ 6] = a[ 6];\n dst[ 7] = a[ 7];\n dst[ 8] = a[ 8];\n dst[ 9] = a[ 9];\n dst[10] = a[10];\n dst[11] = a[11];\n }\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Returns the translation component of a 4-by-4 matrix as a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The translation component of m.\n * @memberOf module:twgl/m4\n */\nfunction getTranslation(m, dst) {\n dst = dst || create$1();\n dst[0] = m[12];\n dst[1] = m[13];\n dst[2] = m[14];\n return dst;\n}\n\n/**\n * Returns an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @return {module:twgl/v3.Vec3} [dst] vector.\n * @return {module:twgl/v3.Vec3} The axis component of m.\n * @memberOf module:twgl/m4\n */\nfunction getAxis(m, axis, dst) {\n dst = dst || create$1();\n const off = axis * 4;\n dst[0] = m[off + 0];\n dst[1] = m[off + 1];\n dst[2] = m[off + 2];\n return dst;\n}\n\n/**\n * Sets an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v the axis vector\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @param {module:twgl/m4.Mat4} [dst] The matrix to set. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with axis set.\n * @memberOf module:twgl/m4\n */\nfunction setAxis(a, v, axis, dst) {\n if (dst !== a) {\n dst = copy(a, dst);\n }\n const off = axis * 4;\n dst[off + 0] = v[0];\n dst[off + 1] = v[1];\n dst[off + 2] = v[2];\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the angular height\n * of the frustum, the aspect ratio, and the near and far clipping planes. The\n * arguments define a frustum extending in the negative z direction. The given\n * angle is the vertical angle of the frustum, and the horizontal angle is\n * determined to produce the given aspect ratio. The arguments near and far are\n * the distances to the near and far clipping planes. Note that near and far\n * are not z coordinates, but rather they are distances along the negative\n * z-axis. The matrix generated sends the viewing frustum to the unit box.\n * We assume a unit box extending from -1 to 1 in the x and y dimensions and\n * from 0 to 1 in the z dimension.\n * @param {number} fieldOfViewYInRadians The camera angle from top to bottom (in radians).\n * @param {number} aspect The aspect ratio width / height.\n * @param {number} zNear The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} zFar The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction perspective(fieldOfViewYInRadians, aspect, zNear, zFar, dst) {\n dst = dst || new MatType(16);\n\n const f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfViewYInRadians);\n const rangeInv = 1.0 / (zNear - zFar);\n\n dst[0] = f / aspect;\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = f;\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = (zNear + zFar) * rangeInv;\n dst[11] = -1;\n\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = zNear * zFar * rangeInv * 2;\n dst[15] = 0;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 orthogonal transformation matrix given the left, right,\n * bottom, and top dimensions of the near clipping plane as well as the\n * near and far clipping plane distances.\n * @param {number} left Left side of the near clipping plane viewport.\n * @param {number} right Right side of the near clipping plane viewport.\n * @param {number} bottom Bottom of the near clipping plane viewport.\n * @param {number} top Top of the near clipping plane viewport.\n * @param {number} near The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} far The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction ortho(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n dst[0] = 2 / (right - left);\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = 2 / (top - bottom);\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = 2 / (near - far);\n dst[11] = 0;\n\n dst[12] = (right + left) / (left - right);\n dst[13] = (top + bottom) / (bottom - top);\n dst[14] = (far + near) / (near - far);\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the left, right,\n * top, bottom, near and far clipping planes. The arguments define a frustum\n * extending in the negative z direction. The arguments near and far are the\n * distances to the near and far clipping planes. Note that near and far are not\n * z coordinates, but rather they are distances along the negative z-axis. The\n * matrix generated sends the viewing frustum to the unit box. We assume a unit\n * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z\n * dimension.\n * @param {number} left The x coordinate of the left plane of the box.\n * @param {number} right The x coordinate of the right plane of the box.\n * @param {number} bottom The y coordinate of the bottom plane of the box.\n * @param {number} top The y coordinate of the right plane of the box.\n * @param {number} near The negative z coordinate of the near plane of the box.\n * @param {number} far The negative z coordinate of the far plane of the box.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective projection matrix.\n * @memberOf module:twgl/m4\n */\nfunction frustum(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n const dx = (right - left);\n const dy = (top - bottom);\n const dz = (near - far);\n\n dst[ 0] = 2 * near / dx;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 2 * near / dy;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = (left + right) / dx;\n dst[ 9] = (top + bottom) / dy;\n dst[10] = far / dz;\n dst[11] = -1;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = near * far / dz;\n dst[15] = 0;\n\n return dst;\n}\n\nlet xAxis;\nlet yAxis;\nlet zAxis;\n\n/**\n * Computes a 4-by-4 look-at transformation.\n *\n * This is a matrix which positions the camera itself. If you want\n * a view matrix (a matrix which moves things in front of the camera)\n * take the inverse of this.\n *\n * @param {module:twgl/v3.Vec3} eye The position of the eye.\n * @param {module:twgl/v3.Vec3} target The position meant to be viewed.\n * @param {module:twgl/v3.Vec3} up A vector pointing up.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The look-at matrix.\n * @memberOf module:twgl/m4\n */\nfunction lookAt(eye, target, up, dst) {\n dst = dst || new MatType(16);\n\n xAxis = xAxis || create$1();\n yAxis = yAxis || create$1();\n zAxis = zAxis || create$1();\n\n normalize(\n subtract(eye, target, zAxis), zAxis);\n normalize(cross(up, zAxis, xAxis), xAxis);\n normalize(cross(zAxis, xAxis, yAxis), yAxis);\n\n dst[ 0] = xAxis[0];\n dst[ 1] = xAxis[1];\n dst[ 2] = xAxis[2];\n dst[ 3] = 0;\n dst[ 4] = yAxis[0];\n dst[ 5] = yAxis[1];\n dst[ 6] = yAxis[2];\n dst[ 7] = 0;\n dst[ 8] = zAxis[0];\n dst[ 9] = zAxis[1];\n dst[10] = zAxis[2];\n dst[11] = 0;\n dst[12] = eye[0];\n dst[13] = eye[1];\n dst[14] = eye[2];\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which translates by the given vector v.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translation matrix.\n * @memberOf module:twgl/m4\n */\nfunction translation(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Translates the given 4-by-4 matrix by the given vector v.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translated matrix.\n * @memberOf module:twgl/m4\n */\nfunction translate(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n if (m !== dst) {\n dst[ 0] = m00;\n dst[ 1] = m01;\n dst[ 2] = m02;\n dst[ 3] = m03;\n dst[ 4] = m10;\n dst[ 5] = m11;\n dst[ 6] = m12;\n dst[ 7] = m13;\n dst[ 8] = m20;\n dst[ 9] = m21;\n dst[10] = m22;\n dst[11] = m23;\n }\n\n dst[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30;\n dst[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31;\n dst[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32;\n dst[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationX(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = c;\n dst[ 6] = s;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = -s;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the x-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateX(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[4] = c * m10 + s * m20;\n dst[5] = c * m11 + s * m21;\n dst[6] = c * m12 + s * m22;\n dst[7] = c * m13 + s * m23;\n dst[8] = c * m20 - s * m10;\n dst[9] = c * m21 - s * m11;\n dst[10] = c * m22 - s * m12;\n dst[11] = c * m23 - s * m13;\n\n if (m !== dst) {\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationY(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = 0;\n dst[ 2] = -s;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = s;\n dst[ 9] = 0;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the y-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateY(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 - s * m20;\n dst[ 1] = c * m01 - s * m21;\n dst[ 2] = c * m02 - s * m22;\n dst[ 3] = c * m03 - s * m23;\n dst[ 8] = c * m20 + s * m00;\n dst[ 9] = c * m21 + s * m01;\n dst[10] = c * m22 + s * m02;\n dst[11] = c * m23 + s * m03;\n\n if (m !== dst) {\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationZ(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = s;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = -s;\n dst[ 5] = c;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the z-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateZ(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 + s * m10;\n dst[ 1] = c * m01 + s * m11;\n dst[ 2] = c * m02 + s * m12;\n dst[ 3] = c * m03 + s * m13;\n dst[ 4] = c * m10 - s * m00;\n dst[ 5] = c * m11 - s * m01;\n dst[ 6] = c * m12 - s * m02;\n dst[ 7] = c * m13 - s * m03;\n\n if (m !== dst) {\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the given axis by the given\n * angle.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A matrix which rotates angle radians\n * around the axis.\n * @memberOf module:twgl/m4\n */\nfunction axisRotation(axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n dst[ 0] = xx + (1 - xx) * c;\n dst[ 1] = x * y * oneMinusCosine + z * s;\n dst[ 2] = x * z * oneMinusCosine - y * s;\n dst[ 3] = 0;\n dst[ 4] = x * y * oneMinusCosine - z * s;\n dst[ 5] = yy + (1 - yy) * c;\n dst[ 6] = y * z * oneMinusCosine + x * s;\n dst[ 7] = 0;\n dst[ 8] = x * z * oneMinusCosine + y * s;\n dst[ 9] = y * z * oneMinusCosine - x * s;\n dst[10] = zz + (1 - zz) * c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the given axis by the\n * given angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction axisRotate(m, axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n const r00 = xx + (1 - xx) * c;\n const r01 = x * y * oneMinusCosine + z * s;\n const r02 = x * z * oneMinusCosine - y * s;\n const r10 = x * y * oneMinusCosine - z * s;\n const r11 = yy + (1 - yy) * c;\n const r12 = y * z * oneMinusCosine + x * s;\n const r20 = x * z * oneMinusCosine + y * s;\n const r21 = y * z * oneMinusCosine - x * s;\n const r22 = zz + (1 - zz) * c;\n\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n\n dst[ 0] = r00 * m00 + r01 * m10 + r02 * m20;\n dst[ 1] = r00 * m01 + r01 * m11 + r02 * m21;\n dst[ 2] = r00 * m02 + r01 * m12 + r02 * m22;\n dst[ 3] = r00 * m03 + r01 * m13 + r02 * m23;\n dst[ 4] = r10 * m00 + r11 * m10 + r12 * m20;\n dst[ 5] = r10 * m01 + r11 * m11 + r12 * m21;\n dst[ 6] = r10 * m02 + r11 * m12 + r12 * m22;\n dst[ 7] = r10 * m03 + r11 * m13 + r12 * m23;\n dst[ 8] = r20 * m00 + r21 * m10 + r22 * m20;\n dst[ 9] = r20 * m01 + r21 * m11 + r22 * m21;\n dst[10] = r20 * m02 + r21 * m12 + r22 * m22;\n dst[11] = r20 * m03 + r21 * m13 + r22 * m23;\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which scales in each dimension by an amount given by\n * the corresponding entry in the given vector; assumes the vector has three\n * entries.\n * @param {module:twgl/v3.Vec3} v A vector of\n * three entries specifying the factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaling matrix.\n * @memberOf module:twgl/m4\n */\nfunction scaling(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = v[0];\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = v[1];\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = v[2];\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Scales the given 4-by-4 matrix in each dimension by an amount\n * given by the corresponding entry in the given vector; assumes the vector has\n * three entries.\n * @param {module:twgl/m4.Mat4} m The matrix to be modified.\n * @param {module:twgl/v3.Vec3} v A vector of three entries specifying the\n * factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaled matrix.\n * @memberOf module:twgl/m4\n */\nfunction scale(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[ 0] = v0 * m[0 * 4 + 0];\n dst[ 1] = v0 * m[0 * 4 + 1];\n dst[ 2] = v0 * m[0 * 4 + 2];\n dst[ 3] = v0 * m[0 * 4 + 3];\n dst[ 4] = v1 * m[1 * 4 + 0];\n dst[ 5] = v1 * m[1 * 4 + 1];\n dst[ 6] = v1 * m[1 * 4 + 2];\n dst[ 7] = v1 * m[1 * 4 + 3];\n dst[ 8] = v2 * m[2 * 4 + 0];\n dst[ 9] = v2 * m[2 * 4 + 1];\n dst[10] = v2 * m[2 * 4 + 2];\n dst[11] = v2 * m[2 * 4 + 3];\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries,\n * interprets the vector as a point, transforms that point by the matrix, and\n * returns the result as a vector with 3 entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The point.\n * @param {module:twgl/v3.Vec3} [dst] optional vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed point.\n * @memberOf module:twgl/m4\n */\nfunction transformPoint(m, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const d = v0 * m[0 * 4 + 3] + v1 * m[1 * 4 + 3] + v2 * m[2 * 4 + 3] + m[3 * 4 + 3];\n\n dst[0] = (v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0] + m[3 * 4 + 0]) / d;\n dst[1] = (v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1] + m[3 * 4 + 1]) / d;\n dst[2] = (v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2] + m[3 * 4 + 2]) / d;\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a\n * direction, transforms that direction by the matrix, and returns the result;\n * assumes the transformation of 3-dimensional space represented by the matrix\n * is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The direction.\n * @param {module:twgl/v3.Vec3} [dst] optional Vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed direction.\n * @memberOf module:twgl/m4\n */\nfunction transformDirection(m, v, dst) {\n dst = dst || create$1();\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0];\n dst[1] = v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1];\n dst[2] = v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector\n * as a normal to a surface, and computes a vector which is normal upon\n * transforming that surface by the matrix. The effect of this function is the\n * same as transforming v (as a direction) by the inverse-transpose of m. This\n * function assumes the transformation of 3-dimensional space represented by the\n * matrix is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The normal.\n * @param {module:twgl/v3.Vec3} [dst] The direction. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed normal.\n * @memberOf module:twgl/m4\n */\nfunction transformNormal$1(m, v, dst) {\n dst = dst || create$1();\n const mi = inverse(m);\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\nvar m4 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n axisRotate: axisRotate,\n axisRotation: axisRotation,\n copy: copy,\n create: create,\n frustum: frustum,\n getAxis: getAxis,\n getTranslation: getTranslation,\n identity: identity,\n inverse: inverse,\n lookAt: lookAt,\n multiply: multiply,\n negate: negate,\n ortho: ortho,\n perspective: perspective,\n rotateX: rotateX,\n rotateY: rotateY,\n rotateZ: rotateZ,\n rotationX: rotationX,\n rotationY: rotationY,\n rotationZ: rotationZ,\n scale: scale,\n scaling: scaling,\n setAxis: setAxis,\n setDefaultType: setDefaultType,\n setTranslation: setTranslation,\n transformDirection: transformDirection,\n transformNormal: transformNormal$1,\n transformPoint: transformPoint,\n translate: translate,\n translation: translation,\n transpose: transpose\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* DataType */\nconst BYTE$2 = 0x1400;\nconst UNSIGNED_BYTE$3 = 0x1401;\nconst SHORT$2 = 0x1402;\nconst UNSIGNED_SHORT$3 = 0x1403;\nconst INT$3 = 0x1404;\nconst UNSIGNED_INT$3 = 0x1405;\nconst FLOAT$3 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4$1 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1$1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5$1 = 0x8363;\nconst HALF_FLOAT$1 = 0x140B;\nconst UNSIGNED_INT_2_10_10_10_REV$1 = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV$1 = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV$1 = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV$1 = 0x8DAD;\nconst UNSIGNED_INT_24_8$1 = 0x84FA;\n\nconst glTypeToTypedArray = {};\n{\n const tt = glTypeToTypedArray;\n tt[BYTE$2] = Int8Array;\n tt[UNSIGNED_BYTE$3] = Uint8Array;\n tt[SHORT$2] = Int16Array;\n tt[UNSIGNED_SHORT$3] = Uint16Array;\n tt[INT$3] = Int32Array;\n tt[UNSIGNED_INT$3] = Uint32Array;\n tt[FLOAT$3] = Float32Array;\n tt[UNSIGNED_SHORT_4_4_4_4$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_5_5_1$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_6_5$1] = Uint16Array;\n tt[HALF_FLOAT$1] = Uint16Array;\n tt[UNSIGNED_INT_2_10_10_10_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_10F_11F_11F_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_5_9_9_9_REV$1] = Uint32Array;\n tt[FLOAT_32_UNSIGNED_INT_24_8_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_24_8$1] = Uint32Array;\n}\n\n/**\n * Get the GL type for a typedArray\n * @param {ArrayBufferView} typedArray a typedArray\n * @return {number} the GL type for array. For example pass in an `Int8Array` and `gl.BYTE` will\n * be returned. Pass in a `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArray(typedArray) {\n if (typedArray instanceof Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArray instanceof Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArray instanceof Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArray instanceof Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArray instanceof Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArray instanceof Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the GL type for a typedArray type\n * @param {ArrayBufferView} typedArrayType a typedArray constructor\n * @return {number} the GL type for type. For example pass in `Int8Array` and `gl.BYTE` will\n * be returned. Pass in `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArrayType === Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArrayType === Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArrayType === Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArrayType === Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the typed array constructor for a given GL type\n * @param {number} type the GL type. (eg: `gl.UNSIGNED_INT`)\n * @return {function} the constructor for a the corresponding typed array. (eg. `Uint32Array`).\n * @memberOf module:twgl/typedArray\n */\nfunction getTypedArrayTypeForGLType(type) {\n const CTOR = glTypeToTypedArray[type];\n if (!CTOR) {\n throw new Error('unknown gl type');\n }\n return CTOR;\n}\n\nconst isArrayBuffer$1 = typeof SharedArrayBuffer !== 'undefined'\n ? function isArrayBufferOrSharedArrayBuffer(a) {\n return a && a.buffer && (a.buffer instanceof ArrayBuffer || a.buffer instanceof SharedArrayBuffer);\n }\n : function isArrayBuffer(a) {\n return a && a.buffer && a.buffer instanceof ArrayBuffer;\n };\n\nvar typedarrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getGLTypeForTypedArray: getGLTypeForTypedArray,\n getGLTypeForTypedArrayType: getGLTypeForTypedArrayType,\n getTypedArrayTypeForGLType: getTypedArrayTypeForGLType,\n isArrayBuffer: isArrayBuffer$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint no-console: \"off\" */\n\n/**\n * Copy named properties\n *\n * @param {string[]} names names of properties to copy\n * @param {object} src object to copy properties from\n * @param {object} dst object to copy properties to\n * @private\n */\nfunction copyNamedProperties(names, src, dst) {\n names.forEach(function(name) {\n const value = src[name];\n if (value !== undefined) {\n dst[name] = value;\n }\n });\n}\n\n/**\n * Copies properties from source to dest only if a matching key is in dest\n *\n * @param {Object.} src the source\n * @param {Object.} dst the dest\n * @private\n */\nfunction copyExistingProperties(src, dst) {\n Object.keys(dst).forEach(function(key) {\n if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) { /* eslint no-prototype-builtins: 0 */\n dst[key] = src[key];\n }\n });\n}\n\nfunction error$1(...args) {\n console.error(...args);\n}\n\nfunction warn$1(...args) {\n console.warn(...args);\n}\n\nconst isTypeWeakMaps = new Map();\n\nfunction isType(object, type) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n let weakMap = isTypeWeakMaps.get(type);\n if (!weakMap) {\n weakMap = new WeakMap();\n isTypeWeakMaps.set(type, weakMap);\n }\n let isOfType = weakMap.get(object);\n if (isOfType === undefined) {\n const s = Object.prototype.toString.call(object);\n isOfType = s.substring(8, s.length - 1) === type;\n weakMap.set(object, isOfType);\n }\n return isOfType;\n}\n\nfunction isBuffer(gl, t) {\n return typeof WebGLBuffer !== 'undefined' && isType(t, 'WebGLBuffer');\n}\n\nfunction isRenderbuffer(gl, t) {\n return typeof WebGLRenderbuffer !== 'undefined' && isType(t, 'WebGLRenderbuffer');\n}\n\nfunction isTexture(gl, t) {\n return typeof WebGLTexture !== 'undefined' && isType(t, 'WebGLTexture');\n}\n\nfunction isSampler(gl, t) {\n return typeof WebGLSampler !== 'undefined' && isType(t, 'WebGLSampler');\n}\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst STATIC_DRAW = 0x88e4;\nconst ARRAY_BUFFER$1 = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$2 = 0x8893;\nconst BUFFER_SIZE = 0x8764;\n\nconst BYTE$1 = 0x1400;\nconst UNSIGNED_BYTE$2 = 0x1401;\nconst SHORT$1 = 0x1402;\nconst UNSIGNED_SHORT$2 = 0x1403;\nconst INT$2 = 0x1404;\nconst UNSIGNED_INT$2 = 0x1405;\nconst FLOAT$2 = 0x1406;\nconst defaults$2 = {\n attribPrefix: \"\",\n};\n\n/**\n * Sets the default attrib prefix\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * var arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * @deprecated see {@link module:twgl.setDefaults}\n * @param {string} prefix prefix for attribs\n * @memberOf module:twgl/attributes\n */\nfunction setAttributePrefix(prefix) {\n defaults$2.attribPrefix = prefix;\n}\n\nfunction setDefaults$2(newDefaults) {\n copyExistingProperties(newDefaults, defaults$2);\n}\n\nfunction setBufferFromTypedArray(gl, type, buffer, array, drawType) {\n gl.bindBuffer(type, buffer);\n gl.bufferData(type, array, drawType || STATIC_DRAW);\n}\n\n/**\n * Given typed array creates a WebGLBuffer and copies the typed array\n * into it.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|WebGLBuffer} typedArray the typed array. Note: If a WebGLBuffer is passed in it will just be returned. No action will be taken\n * @param {number} [type] the GL bind type for the buffer. Default = `gl.ARRAY_BUFFER`.\n * @param {number} [drawType] the GL draw type for the buffer. Default = 'gl.STATIC_DRAW`.\n * @return {WebGLBuffer} the created WebGLBuffer\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromTypedArray(gl, typedArray, type, drawType) {\n if (isBuffer(gl, typedArray)) {\n return typedArray;\n }\n type = type || ARRAY_BUFFER$1;\n const buffer = gl.createBuffer();\n setBufferFromTypedArray(gl, type, buffer, typedArray, drawType);\n return buffer;\n}\n\nfunction isIndices(name) {\n return name === \"indices\";\n}\n\n// This is really just a guess. Though I can't really imagine using\n// anything else? Maybe for some compression?\nfunction getNormalizationForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return true; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return true; } // eslint-disable-line\n return false;\n}\n\nfunction getArray$1(array) {\n return array.length ? array : array.data;\n}\n\nconst texcoordRE = /coord|texture/i;\nconst colorRE = /color|colour/i;\n\nfunction guessNumComponentsFromName(name, length) {\n let numComponents;\n if (texcoordRE.test(name)) {\n numComponents = 2;\n } else if (colorRE.test(name)) {\n numComponents = 4;\n } else {\n numComponents = 3; // position, normals, indices ...\n }\n\n if (length % numComponents > 0) {\n throw new Error(`Can not guess numComponents for attribute '${name}'. Tried ${numComponents} but ${length} values is not evenly divisible by ${numComponents}. You should specify it.`);\n }\n\n return numComponents;\n}\n\nfunction getNumComponents$1(array, arrayName, numValues) {\n return array.numComponents || array.size || guessNumComponentsFromName(arrayName, numValues || getArray$1(array).length);\n}\n\nfunction makeTypedArray(array, name) {\n if (isArrayBuffer$1(array)) {\n return array;\n }\n\n if (isArrayBuffer$1(array.data)) {\n return array.data;\n }\n\n if (Array.isArray(array)) {\n array = {\n data: array,\n };\n }\n\n let Type = array.type ? typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type) : undefined;\n if (!Type) {\n if (isIndices(name)) {\n Type = Uint16Array;\n } else {\n Type = Float32Array;\n }\n }\n return new Type(array.data);\n}\n\nfunction glTypeFromGLTypeOrTypedArrayType(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? glTypeOrTypedArrayCtor\n : glTypeOrTypedArrayCtor ? getGLTypeForTypedArrayType(glTypeOrTypedArrayCtor) : FLOAT$2;\n}\n\nfunction typedArrayTypeFromGLTypeOrTypedArrayCtor(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? getTypedArrayTypeForGLType(glTypeOrTypedArrayCtor)\n : glTypeOrTypedArrayCtor || Float32Array;\n}\n\nfunction attribBufferFromBuffer(gl, array/*, arrayName */) {\n return {\n buffer: array.buffer,\n numValues: 2 * 3 * 4, // safely divided by 2, 3, 4\n type: glTypeFromGLTypeOrTypedArrayType(array.type),\n arrayType: typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type),\n };\n}\n\nfunction attribBufferFromSize(gl, array/*, arrayName*/) {\n const numValues = array.data || array;\n const arrayType = typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type);\n const numBytes = numValues * arrayType.BYTES_PER_ELEMENT;\n const buffer = gl.createBuffer();\n gl.bindBuffer(ARRAY_BUFFER$1, buffer);\n gl.bufferData(ARRAY_BUFFER$1, numBytes, array.drawType || STATIC_DRAW);\n return {\n buffer,\n numValues,\n type: getGLTypeForTypedArrayType(arrayType),\n arrayType,\n };\n}\n\nfunction attribBufferFromArrayLike(gl, array, arrayName) {\n const typedArray = makeTypedArray(array, arrayName);\n return {\n arrayType: typedArray.constructor,\n buffer: createBufferFromTypedArray(gl, typedArray, undefined, array.drawType),\n type: getGLTypeForTypedArray(typedArray),\n numValues: 0,\n };\n}\n\n/**\n * The info for an attribute. This is effectively just the arguments to `gl.vertexAttribPointer` plus the WebGLBuffer\n * for the attribute.\n *\n * @typedef {Object} AttribInfo\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {number} [numComponents] the number of components for this attribute.\n * @property {number} [size] synonym for `numComponents`.\n * @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`\n * @property {boolean} [normalize] whether or not to normalize the data. Default = false\n * @property {number} [offset] offset into buffer in bytes. Default = 0\n * @property {number} [stride] the stride in bytes per element. Default = 0\n * @property {number} [divisor] the divisor in instances. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you're using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {WebGLBuffer} buffer the buffer that contains the data for this attribute\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {(Int8ArrayConstructor|Uint8ArrayConstructor|Int16ArrayConstructor|Uint16ArrayConstructor|Int32ArrayConstructor|Uint32ArrayConstructor|Float32ArrayConstructor)} TypedArrayConstructor\n */\n\n/**\n * Use this type of array spec when TWGL can't guess the type or number of components of an array\n * @typedef {Object} FullArraySpec\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {(number|number[]|ArrayBufferView)} [data] The data of the array. A number alone becomes the number of elements of type.\n * @property {number} [numComponents] number of components for `vertexAttribPointer`. Default is based on the name of the array.\n * If `coord` is in the name assumes `numComponents = 2`.\n * If `color` is in the name assumes `numComponents = 4`.\n * otherwise assumes `numComponents = 3`\n * @property {number|TypedArrayConstructor} [type] type. This is used if `data` is a JavaScript array, or `buffer` is passed in, or `data` is a number.\n * It can either be the constructor for a typedarray. (eg. `Uint8Array`) OR a WebGL type, (eg `gl.UNSIGNED_BYTE`).\n * For example if you want colors in a `Uint8Array` you might have a `FullArraySpec` like `{ type: gl.UNSIGNED_BYTE, data: [255,0,255,255, ...], }`.\n * @property {number} [size] synonym for `numComponents`.\n * @property {boolean} [normalize] normalize for `vertexAttribPointer`. Default is true if type is `Int8Array` or `Uint8Array` otherwise false.\n * @property {number} [stride] stride for `vertexAttribPointer`. Default = 0\n * @property {number} [offset] offset for `vertexAttribPointer`. Default = 0\n * @property {number} [divisor] divisor for `vertexAttribDivisor`. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {string} [attrib] name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.\n * @property {string} [name] synonym for `attrib`.\n * @property {string} [attribName] synonym for `attrib`.\n * @property {WebGLBuffer} [buffer] Buffer to use for this attribute. This lets you use your own buffer\n * but you will need to supply `numComponents` and `type`. You can effectively pass an `AttribInfo`\n * to provide this. Example:\n *\n * const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {\n * position: [1, 2, 3, ... ],\n * });\n * const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {\n * position: bufferInfo1.attribs.position, // use the same buffer from bufferInfo1\n * });\n *\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * An individual array in {@link module:twgl.Arrays}\n *\n * When passed to {@link module:twgl.createBufferInfoFromArrays} if an ArraySpec is `number[]` or `ArrayBufferView`\n * the types will be guessed based on the name. `indices` will be `Uint16Array`, everything else will\n * be `Float32Array`. If an ArraySpec is a number it's the number of floats for an empty (zeroed) buffer.\n *\n * @typedef {(number|number[]|ArrayBufferView|module:twgl.FullArraySpec)} ArraySpec\n * @memberOf module:twgl\n */\n\n/**\n * This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your\n * attributes have a common prefix you can specify it by calling {@link module:twgl.setAttributePrefix}.\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * Objects with various fields. See {@link module:twgl.FullArraySpec}.\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * @typedef {Object.} Arrays\n * @memberOf module:twgl\n */\n\n\n/**\n * Creates a set of attribute data and WebGLBuffers from set of arrays\n *\n * Given\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * returns something like\n *\n * var attribs = {\n * position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, },\n * };\n *\n * notes:\n *\n * * Arrays can take various forms\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * @param {WebGLRenderingContext} gl The webgl rendering context.\n * @param {module:twgl.Arrays} arrays The arrays\n * @param {module:twgl.BufferInfo} [srcBufferInfo] a BufferInfo to copy from\n * This lets you share buffers. Any arrays you supply will override\n * the buffers from srcBufferInfo.\n * @return {Object.} the attribs\n * @memberOf module:twgl/attributes\n */\nfunction createAttribsFromArrays(gl, arrays) {\n const attribs = {};\n Object.keys(arrays).forEach(function(arrayName) {\n if (!isIndices(arrayName)) {\n const array = arrays[arrayName];\n const attribName = array.attrib || array.name || array.attribName || (defaults$2.attribPrefix + arrayName);\n if (array.value) {\n if (!Array.isArray(array.value) && !isArrayBuffer$1(array.value)) {\n throw new Error('array.value is not array or typedarray');\n }\n attribs[attribName] = {\n value: array.value,\n };\n } else {\n let fn;\n if (array.buffer && array.buffer instanceof WebGLBuffer) {\n fn = attribBufferFromBuffer;\n } else if (typeof array === \"number\" || typeof array.data === \"number\") {\n fn = attribBufferFromSize;\n } else {\n fn = attribBufferFromArrayLike;\n }\n const {buffer, type, numValues, arrayType} = fn(gl, array, arrayName);\n const normalization = array.normalize !== undefined ? array.normalize : getNormalizationForTypedArrayType(arrayType);\n const numComponents = getNumComponents$1(array, arrayName, numValues);\n attribs[attribName] = {\n buffer: buffer,\n numComponents: numComponents,\n type: type,\n normalize: normalization,\n stride: array.stride || 0,\n offset: array.offset || 0,\n divisor: array.divisor === undefined ? undefined : array.divisor,\n drawType: array.drawType,\n };\n }\n }\n });\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n return attribs;\n}\n\n/**\n * Sets the contents of a buffer attached to an attribInfo\n *\n * This is helper function to dynamically update a buffer.\n *\n * Let's say you make a bufferInfo\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n * var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);\n *\n * And you want to dynamically update the positions. You could do this\n *\n * // assuming arrays.position has already been updated with new data.\n * twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);\n *\n * @param {WebGLRenderingContext} gl\n * @param {AttribInfo} attribInfo The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix\n * the name of the attribute will include the prefix.\n * @param {ArraySpec} array Note: it is arguably inefficient to pass in anything but a typed array because anything\n * else will have to be converted to a typed array before it can be used by WebGL. During init time that\n * inefficiency is usually not important but if you're updating data dynamically best to be efficient.\n * @param {number} [offset] an optional offset into the buffer. This is only an offset into the WebGL buffer\n * not the array. To pass in an offset into the array itself use a typed array and create an `ArrayBufferView`\n * for the portion of the array you want to use.\n *\n * var someArray = new Float32Array(1000); // an array with 1000 floats\n * var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray\n *\n * Now you can pass `someSubArray` into setAttribInfoBufferFromArray`\n * @memberOf module:twgl/attributes\n */\nfunction setAttribInfoBufferFromArray(gl, attribInfo, array, offset) {\n array = makeTypedArray(array);\n if (offset !== undefined) {\n gl.bindBuffer(ARRAY_BUFFER$1, attribInfo.buffer);\n gl.bufferSubData(ARRAY_BUFFER$1, offset, array);\n } else {\n setBufferFromTypedArray(gl, ARRAY_BUFFER$1, attribInfo.buffer, array, attribInfo.drawType);\n }\n}\n\nfunction getBytesPerValueForGLType(gl, type) {\n if (type === BYTE$1) return 1; // eslint-disable-line\n if (type === UNSIGNED_BYTE$2) return 1; // eslint-disable-line\n if (type === SHORT$1) return 2; // eslint-disable-line\n if (type === UNSIGNED_SHORT$2) return 2; // eslint-disable-line\n if (type === INT$2) return 4; // eslint-disable-line\n if (type === UNSIGNED_INT$2) return 4; // eslint-disable-line\n if (type === FLOAT$2) return 4; // eslint-disable-line\n return 0;\n}\n\n// Tries to get the number of elements from a set of arrays.\nconst positionKeys = ['position', 'positions', 'a_position'];\nfunction getNumElementsFromNonIndexedArrays(arrays) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in arrays) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(arrays)[0];\n }\n const array = arrays[key];\n const length = getArray$1(array).length;\n if (length === undefined) {\n return 1; // There's no arrays\n }\n const numComponents = getNumComponents$1(array, key);\n const numElements = length / numComponents;\n if (length % numComponents > 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\nfunction getNumElementsFromAttributes(gl, attribs) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in attribs) {\n break;\n }\n key = defaults$2.attribPrefix + key;\n if (key in attribs) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(attribs)[0];\n }\n const attrib = attribs[key];\n if (!attrib.buffer) {\n return 1; // There's no buffer\n }\n gl.bindBuffer(ARRAY_BUFFER$1, attrib.buffer);\n const numBytes = gl.getBufferParameter(ARRAY_BUFFER$1, BUFFER_SIZE);\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n\n const bytesPerValue = getBytesPerValueForGLType(gl, attrib.type);\n const totalElements = numBytes / bytesPerValue;\n const numComponents = attrib.numComponents || attrib.size;\n // TODO: check stride\n const numElements = totalElements / numComponents;\n if (numElements % 1 !== 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\n/**\n * @typedef {Object} BufferInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.\n * @property {Object.} [attribs] The attribs appropriate to call `setAttributes`\n * @memberOf module:twgl\n */\n\n/**\n * Creates a BufferInfo from an object of arrays.\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * Given an object like\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * Creates an BufferInfo like this\n *\n * bufferInfo = {\n * numElements: 4, // or whatever the number of elements is\n * indices: WebGLBuffer, // this property will not exist if there are no indices\n * attribs: {\n * position: { buffer: WebGLBuffer, numComponents: 3, },\n * normal: { buffer: WebGLBuffer, numComponents: 3, },\n * texcoord: { buffer: WebGLBuffer, numComponents: 2, },\n * },\n * };\n *\n * The properties of arrays can be JavaScript arrays in which case the number of components\n * will be guessed.\n *\n * var arrays = {\n * position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],\n * texcoord: [0, 0, 0, 1, 1, 0, 1, 1],\n * normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],\n * indices: [0, 1, 2, 1, 2, 3],\n * };\n *\n * They can also be TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n *\n * Or AugmentedTypedArrays\n *\n * var positions = createAugmentedTypedArray(3, 4);\n * var texcoords = createAugmentedTypedArray(2, 4);\n * var normals = createAugmentedTypedArray(3, 4);\n * var indices = createAugmentedTypedArray(3, 2, Uint16Array);\n *\n * positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);\n * texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);\n * normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);\n * indices.push([0, 1, 2, 1, 2, 3]);\n *\n * var arrays = {\n * position: positions,\n * texcoord: texcoords,\n * normal: normals,\n * indices: indices,\n * };\n *\n * For the last example it is equivalent to\n *\n * var bufferInfo = {\n * attribs: {\n * position: { numComponents: 3, buffer: gl.createBuffer(), },\n * texcoord: { numComponents: 2, buffer: gl.createBuffer(), },\n * normal: { numComponents: 3, buffer: gl.createBuffer(), },\n * },\n * indices: gl.createBuffer(),\n * numElements: 6,\n * };\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.position.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.texcoord.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.normal.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);\n * gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.Arrays} arrays Your data\n * @param {module:twgl.BufferInfo} [srcBufferInfo] An existing\n * buffer info to start from. WebGLBuffers etc specified\n * in the srcBufferInfo will be used in a new BufferInfo\n * with any arrays specified overriding the ones in\n * srcBufferInfo.\n * @return {module:twgl.BufferInfo} A BufferInfo\n * @memberOf module:twgl/attributes\n */\nfunction createBufferInfoFromArrays(gl, arrays, srcBufferInfo) {\n const newAttribs = createAttribsFromArrays(gl, arrays);\n const bufferInfo = Object.assign({}, srcBufferInfo ? srcBufferInfo : {});\n bufferInfo.attribs = Object.assign({}, srcBufferInfo ? srcBufferInfo.attribs : {}, newAttribs);\n const indices = arrays.indices;\n if (indices) {\n const newIndices = makeTypedArray(indices, \"indices\");\n bufferInfo.indices = createBufferFromTypedArray(gl, newIndices, ELEMENT_ARRAY_BUFFER$2);\n bufferInfo.numElements = newIndices.length;\n bufferInfo.elementType = getGLTypeForTypedArray(newIndices);\n } else if (!bufferInfo.numElements) {\n bufferInfo.numElements = getNumElementsFromAttributes(gl, bufferInfo.attribs);\n }\n\n return bufferInfo;\n}\n\n/**\n * Creates a buffer from an array, typed array, or array spec\n *\n * Given something like this\n *\n * [1, 2, 3],\n *\n * or\n *\n * new Uint16Array([1,2,3]);\n *\n * or\n *\n * {\n * data: [1, 2, 3],\n * type: Uint8Array,\n * }\n *\n * returns a WebGLBuffer that contains the given data.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.ArraySpec} array an array, typed array, or array spec.\n * @param {string} arrayName name of array. Used to guess the type if type can not be derived otherwise.\n * @return {WebGLBuffer} a WebGLBuffer containing the data in array.\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromArray(gl, array, arrayName) {\n const type = arrayName === \"indices\" ? ELEMENT_ARRAY_BUFFER$2 : ARRAY_BUFFER$1;\n const typedArray = makeTypedArray(array, arrayName);\n return createBufferFromTypedArray(gl, typedArray, type);\n}\n\n/**\n * Creates buffers from arrays or typed arrays\n *\n * Given something like this\n *\n * var arrays = {\n * positions: [1, 2, 3],\n * normals: [0, 0, 1],\n * }\n *\n * returns something like\n *\n * buffers = {\n * positions: WebGLBuffer,\n * normals: WebGLBuffer,\n * }\n *\n * If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.Arrays} arrays\n * @return {Object} returns an object with one WebGLBuffer per array\n * @memberOf module:twgl/attributes\n */\nfunction createBuffersFromArrays(gl, arrays) {\n const buffers = { };\n Object.keys(arrays).forEach(function(key) {\n buffers[key] = createBufferFromArray(gl, arrays[key], key);\n });\n\n // Ugh!\n if (arrays.indices) {\n buffers.numElements = arrays.indices.length;\n buffers.elementType = getGLTypeForTypedArray(makeTypedArray(arrays.indices));\n } else {\n buffers.numElements = getNumElementsFromNonIndexedArrays(arrays);\n }\n\n return buffers;\n}\n\nvar attributes = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttribsFromArrays: createAttribsFromArrays,\n createBuffersFromArrays: createBuffersFromArrays,\n createBufferFromArray: createBufferFromArray,\n createBufferFromTypedArray: createBufferFromTypedArray,\n createBufferInfoFromArrays: createBufferInfoFromArrays,\n setAttribInfoBufferFromArray: setAttribInfoBufferFromArray,\n setAttributePrefix: setAttributePrefix,\n setAttributeDefaults_: setDefaults$2,\n getNumComponents_: getNumComponents$1,\n getArray_: getArray$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst getArray = getArray$1; // eslint-disable-line\nconst getNumComponents = getNumComponents$1; // eslint-disable-line\n\n/**\n * @typedef {(Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array)} TypedArray\n */\n\n/**\n * Add `push` to a typed array. It just keeps a 'cursor'\n * and allows use to `push` values into the array so we\n * don't have to manually compute offsets\n * @param {TypedArray} typedArray TypedArray to augment\n * @param {number} numComponents number of components.\n * @private\n */\nfunction augmentTypedArray(typedArray, numComponents) {\n let cursor = 0;\n typedArray.push = function() {\n for (let ii = 0; ii < arguments.length; ++ii) {\n const value = arguments[ii];\n if (value instanceof Array || isArrayBuffer$1(value)) {\n for (let jj = 0; jj < value.length; ++jj) {\n typedArray[cursor++] = value[jj];\n }\n } else {\n typedArray[cursor++] = value;\n }\n }\n };\n typedArray.reset = function(opt_index) {\n cursor = opt_index || 0;\n };\n typedArray.numComponents = numComponents;\n Object.defineProperty(typedArray, 'numElements', {\n get: function() {\n return this.length / this.numComponents | 0;\n },\n });\n return typedArray;\n}\n\n/**\n * creates a typed array with a `push` function attached\n * so that you can easily *push* values.\n *\n * `push` can take multiple arguments. If an argument is an array each element\n * of the array will be added to the typed array.\n *\n * Example:\n *\n * const array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values\n * array.push(1, 2, 3);\n * array.push([4, 5, 6]);\n * // array now contains [1, 2, 3, 4, 5, 6]\n *\n * Also has `numComponents` and `numElements` properties.\n *\n * @param {number} numComponents number of components\n * @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`.\n * @param {constructor} opt_type A constructor for the type. Default = `Float32Array`.\n * @return {ArrayBufferView} A typed array.\n * @memberOf module:twgl/primitives\n */\nfunction createAugmentedTypedArray(numComponents, numElements, opt_type) {\n const Type = opt_type || Float32Array;\n return augmentTypedArray(new Type(numComponents * numElements), numComponents);\n}\n\nfunction allButIndices(name) {\n return name !== \"indices\";\n}\n\n/**\n * Given indexed vertices creates a new set of vertices un-indexed by expanding the indexed vertices.\n * @param {Object.} vertices The indexed vertices to deindex\n * @return {Object.} The deindexed vertices\n * @memberOf module:twgl/primitives\n */\nfunction deindexVertices(vertices) {\n const indices = vertices.indices;\n const newVertices = {};\n const numElements = indices.length;\n\n function expandToUnindexed(channel) {\n const srcBuffer = vertices[channel];\n const numComponents = srcBuffer.numComponents;\n const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor);\n for (let ii = 0; ii < numElements; ++ii) {\n const ndx = indices[ii];\n const offset = ndx * numComponents;\n for (let jj = 0; jj < numComponents; ++jj) {\n dstBuffer.push(srcBuffer[offset + jj]);\n }\n }\n newVertices[channel] = dstBuffer;\n }\n\n Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed);\n\n return newVertices;\n}\n\n/**\n * flattens the normals of deindexed vertices in place.\n * @param {Object.} vertices The deindexed vertices who's normals to flatten\n * @return {Object.} The flattened vertices (same as was passed in)\n * @memberOf module:twgl/primitives\n */\nfunction flattenNormals(vertices) {\n if (vertices.indices) {\n throw new Error('can not flatten normals of indexed vertices. deindex them first');\n }\n\n const normals = vertices.normal;\n const numNormals = normals.length;\n for (let ii = 0; ii < numNormals; ii += 9) {\n // pull out the 3 normals for this triangle\n const nax = normals[ii + 0];\n const nay = normals[ii + 1];\n const naz = normals[ii + 2];\n\n const nbx = normals[ii + 3];\n const nby = normals[ii + 4];\n const nbz = normals[ii + 5];\n\n const ncx = normals[ii + 6];\n const ncy = normals[ii + 7];\n const ncz = normals[ii + 8];\n\n // add them\n let nx = nax + nbx + ncx;\n let ny = nay + nby + ncy;\n let nz = naz + nbz + ncz;\n\n // normalize them\n const length = Math.sqrt(nx * nx + ny * ny + nz * nz);\n\n nx /= length;\n ny /= length;\n nz /= length;\n\n // copy them back in\n normals[ii + 0] = nx;\n normals[ii + 1] = ny;\n normals[ii + 2] = nz;\n\n normals[ii + 3] = nx;\n normals[ii + 4] = ny;\n normals[ii + 5] = nz;\n\n normals[ii + 6] = nx;\n normals[ii + 7] = ny;\n normals[ii + 8] = nz;\n }\n\n return vertices;\n}\n\nfunction applyFuncToV3Array(array, matrix, fn) {\n const len = array.length;\n const tmp = new Float32Array(3);\n for (let ii = 0; ii < len; ii += 3) {\n fn(matrix, [array[ii], array[ii + 1], array[ii + 2]], tmp);\n array[ii ] = tmp[0];\n array[ii + 1] = tmp[1];\n array[ii + 2] = tmp[2];\n }\n}\n\nfunction transformNormal(mi, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Reorients directions by the given matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientDirections(array, matrix) {\n applyFuncToV3Array(array, matrix, transformDirection);\n return array;\n}\n\n/**\n * Reorients normals by the inverse-transpose of the given\n * matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientNormals(array, matrix) {\n applyFuncToV3Array(array, inverse(matrix), transformNormal);\n return array;\n}\n\n/**\n * Reorients positions by the given matrix. In other words, it\n * multiplies each vertex by the given matrix.\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientPositions(array, matrix) {\n applyFuncToV3Array(array, matrix, transformPoint);\n return array;\n}\n\n/**\n * @typedef {(number[]|TypedArray)} NativeArrayOrTypedArray\n */\n\n/**\n * Reorients arrays by the given matrix. Assumes arrays have\n * names that contains 'pos' could be reoriented as positions,\n * 'binorm' or 'tan' as directions, and 'norm' as normals.\n *\n * @param {Object.} arrays The vertices to reorient\n * @param {module:twgl/m4.Mat4} matrix matrix to reorient by.\n * @return {Object.} same arrays that were passed in.\n * @memberOf module:twgl/primitives\n */\nfunction reorientVertices(arrays, matrix) {\n Object.keys(arrays).forEach(function(name) {\n const array = arrays[name];\n if (name.indexOf(\"pos\") >= 0) {\n reorientPositions(array, matrix);\n } else if (name.indexOf(\"tan\") >= 0 || name.indexOf(\"binorm\") >= 0) {\n reorientDirections(array, matrix);\n } else if (name.indexOf(\"norm\") >= 0) {\n reorientNormals(array, matrix);\n }\n });\n return arrays;\n}\n\n/**\n * Creates XY quad BufferInfo\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad BufferInfo\n * @memberOf module:twgl/primitives\n * @function createXYQuadBuffers\n */\n\n/**\n * Creates XY quad Buffers\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {module:twgl.BufferInfo} the created XY Quad buffers\n * @memberOf module:twgl/primitives\n * @function createXYQuadBufferInfo\n */\n\n/**\n * Creates XY quad vertices\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0, 0.5);\n *\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad vertices\n * @memberOf module:twgl/primitives\n */\nfunction createXYQuadVertices(size, xOffset, yOffset) {\n size = size || 2;\n xOffset = xOffset || 0;\n yOffset = yOffset || 0;\n size *= 0.5;\n return {\n position: {\n numComponents: 2,\n data: [\n xOffset + -1 * size, yOffset + -1 * size,\n xOffset + 1 * size, yOffset + -1 * size,\n xOffset + -1 * size, yOffset + 1 * size,\n xOffset + 1 * size, yOffset + 1 * size,\n ],\n },\n normal: [\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n ],\n texcoord: [\n 0, 0,\n 1, 0,\n 0, 1,\n 1, 1,\n ],\n indices: [ 0, 1, 2, 2, 1, 3 ],\n };\n}\n\n/**\n * Creates XZ plane BufferInfo.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {module:twgl.BufferInfo} The created plane BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createPlaneBufferInfo\n */\n\n/**\n * Creates XZ plane buffers.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane buffers.\n * @memberOf module:twgl/primitives\n * @function createPlaneBuffers\n */\n\n/**\n * Creates XZ plane vertices.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createPlaneVertices(\n width,\n depth,\n subdivisionsWidth,\n subdivisionsDepth,\n matrix) {\n width = width || 1;\n depth = depth || 1;\n subdivisionsWidth = subdivisionsWidth || 1;\n subdivisionsDepth = subdivisionsDepth || 1;\n matrix = matrix || identity();\n\n const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n for (let z = 0; z <= subdivisionsDepth; z++) {\n for (let x = 0; x <= subdivisionsWidth; x++) {\n const u = x / subdivisionsWidth;\n const v = z / subdivisionsDepth;\n positions.push(\n width * u - width * 0.5,\n 0,\n depth * v - depth * 0.5);\n normals.push(0, 1, 0);\n texcoords.push(u, v);\n }\n }\n\n const numVertsAcross = subdivisionsWidth + 1;\n const indices = createAugmentedTypedArray(\n 3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array);\n\n for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line\n for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (z + 0) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x,\n (z + 0) * numVertsAcross + x + 1);\n\n // Make triangle 2 of quad.\n indices.push(\n (z + 1) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x + 1,\n (z + 0) * numVertsAcross + x + 1);\n }\n }\n\n const arrays = reorientVertices({\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n }, matrix);\n return arrays;\n}\n\n/**\n * Creates sphere BufferInfo.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {module:twgl.BufferInfo} The created sphere BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createSphereBufferInfo\n */\n\n/**\n * Creates sphere buffers.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere buffers.\n * @memberOf module:twgl/primitives\n * @function createSphereBuffers\n */\n\n/**\n * Creates sphere vertices.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createSphereVertices(\n radius,\n subdivisionsAxis,\n subdivisionsHeight,\n opt_startLatitudeInRadians,\n opt_endLatitudeInRadians,\n opt_startLongitudeInRadians,\n opt_endLongitudeInRadians) {\n if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {\n throw new Error('subdivisionAxis and subdivisionHeight must be > 0');\n }\n\n opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0;\n opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI;\n opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0;\n opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2);\n\n const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians;\n const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians;\n\n // We are going to generate our sphere by iterating through its\n // spherical coordinates and generating 2 triangles for each quad on a\n // ring of the sphere.\n const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n // Generate the individual vertices in our vertex buffer.\n for (let y = 0; y <= subdivisionsHeight; y++) {\n for (let x = 0; x <= subdivisionsAxis; x++) {\n // Generate a vertex based on its spherical coordinates\n const u = x / subdivisionsAxis;\n const v = y / subdivisionsHeight;\n const theta = longRange * u + opt_startLongitudeInRadians;\n const phi = latRange * v + opt_startLatitudeInRadians;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const ux = cosTheta * sinPhi;\n const uy = cosPhi;\n const uz = sinTheta * sinPhi;\n positions.push(radius * ux, radius * uy, radius * uz);\n normals.push(ux, uy, uz);\n texcoords.push(1 - u, v);\n }\n }\n\n const numVertsAround = subdivisionsAxis + 1;\n const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array);\n for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line\n for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (y + 0) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x);\n\n // Make triangle 2 of quad.\n indices.push(\n (y + 1) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x + 1);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Array of the indices of corners of each face of a cube.\n * @type {Array.}\n * @private\n */\nconst CUBE_FACE_INDICES = [\n [3, 7, 5, 1], // right\n [6, 2, 0, 4], // left\n [6, 7, 3, 2], // ??\n [0, 1, 5, 4], // ??\n [7, 6, 4, 5], // front\n [2, 3, 1, 0], // back\n];\n\n/**\n * Creates a BufferInfo for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCubeBufferInfo\n */\n\n/**\n * Creates the buffers and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCubeBuffers\n */\n\n/**\n * Creates the vertices and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCubeVertices(size) {\n size = size || 1;\n const k = size / 2;\n\n const cornerVertices = [\n [-k, -k, -k],\n [+k, -k, -k],\n [-k, +k, -k],\n [+k, +k, -k],\n [-k, -k, +k],\n [+k, -k, +k],\n [-k, +k, +k],\n [+k, +k, +k],\n ];\n\n const faceNormals = [\n [+1, +0, +0],\n [-1, +0, +0],\n [+0, +1, +0],\n [+0, -1, +0],\n [+0, +0, +1],\n [+0, +0, -1],\n ];\n\n const uvCoords = [\n [1, 0],\n [0, 0],\n [0, 1],\n [1, 1],\n ];\n\n const numVertices = 6 * 4;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2 , numVertices);\n const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array);\n\n for (let f = 0; f < 6; ++f) {\n const faceIndices = CUBE_FACE_INDICES[f];\n for (let v = 0; v < 4; ++v) {\n const position = cornerVertices[faceIndices[v]];\n const normal = faceNormals[f];\n const uv = uvCoords[v];\n\n // Each face needs all four vertices because the normals and texture\n // coordinates are not all the same.\n positions.push(position);\n normals.push(normal);\n texcoords.push(uv);\n\n }\n // Two triangles make a square face.\n const offset = 4 * f;\n indices.push(offset + 0, offset + 1, offset + 2);\n indices.push(offset + 0, offset + 2, offset + 3);\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates a BufferInfo for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created cone BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBufferInfo\n */\n\n/**\n * Creates buffers for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone buffers.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBuffers\n */\n\n/**\n * Creates vertices for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis. .\n *\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTruncatedConeVertices(\n bottomRadius,\n topRadius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n opt_topCap,\n opt_bottomCap) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (verticalSubdivisions < 1) {\n throw new Error('verticalSubdivisions must be 1 or greater');\n }\n\n const topCap = (opt_topCap === undefined) ? true : opt_topCap;\n const bottomCap = (opt_bottomCap === undefined) ? true : opt_bottomCap;\n\n const extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);\n\n const numVertices = (radialSubdivisions + 1) * (verticalSubdivisions + 1 + extra);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, radialSubdivisions * (verticalSubdivisions + extra / 2) * 2, Uint16Array);\n\n const vertsAroundEdge = radialSubdivisions + 1;\n\n // The slant of the cone is constant across its surface\n const slant = Math.atan2(bottomRadius - topRadius, height);\n const cosSlant = Math.cos(slant);\n const sinSlant = Math.sin(slant);\n\n const start = topCap ? -2 : 0;\n const end = verticalSubdivisions + (bottomCap ? 2 : 0);\n\n for (let yy = start; yy <= end; ++yy) {\n let v = yy / verticalSubdivisions;\n let y = height * v;\n let ringRadius;\n if (yy < 0) {\n y = 0;\n v = 1;\n ringRadius = bottomRadius;\n } else if (yy > verticalSubdivisions) {\n y = height;\n v = 1;\n ringRadius = topRadius;\n } else {\n ringRadius = bottomRadius +\n (topRadius - bottomRadius) * (yy / verticalSubdivisions);\n }\n if (yy === -2 || yy === verticalSubdivisions + 2) {\n ringRadius = 0;\n v = 0;\n }\n y -= height / 2;\n for (let ii = 0; ii < vertsAroundEdge; ++ii) {\n const sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions);\n const cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions);\n positions.push(sin * ringRadius, y, cos * ringRadius);\n if (yy < 0) {\n normals.push(0, -1, 0);\n } else if (yy > verticalSubdivisions) {\n normals.push(0, 1, 0);\n } else if (ringRadius === 0.0) {\n normals.push(0, 0, 0);\n } else {\n normals.push(sin * cosSlant, sinSlant, cos * cosSlant);\n }\n texcoords.push((ii / radialSubdivisions), 1 - v);\n }\n }\n\n for (let yy = 0; yy < verticalSubdivisions + extra; ++yy) { // eslint-disable-line\n if (yy === 1 && topCap || yy === verticalSubdivisions + extra - 2 && bottomCap) {\n continue;\n }\n for (let ii = 0; ii < radialSubdivisions; ++ii) { // eslint-disable-line\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 0) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii);\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 0 + ii);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Expands RLE data\n * @param {number[]} rleData data in format of run-length, x, y, z, run-length, x, y, z\n * @param {number[]} [padding] value to add each entry with.\n * @return {number[]} the expanded rleData\n * @private\n */\nfunction expandRLEData(rleData, padding) {\n padding = padding || [];\n const data = [];\n for (let ii = 0; ii < rleData.length; ii += 4) {\n const runLength = rleData[ii];\n const element = rleData.slice(ii + 1, ii + 4);\n element.push.apply(element, padding);\n for (let jj = 0; jj < runLength; ++jj) {\n data.push.apply(data, element);\n }\n }\n return data;\n}\n\n/**\n * Creates 3D 'F' BufferInfo.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function create3DFBufferInfo\n */\n\n/**\n * Creates 3D 'F' buffers.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function create3DFBuffers\n */\n\n/**\n * Creates 3D 'F' vertices.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color arrays.\n *\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction create3DFVertices() {\n\n const positions = [\n // left column front\n 0, 0, 0,\n 0, 150, 0,\n 30, 0, 0,\n 0, 150, 0,\n 30, 150, 0,\n 30, 0, 0,\n\n // top rung front\n 30, 0, 0,\n 30, 30, 0,\n 100, 0, 0,\n 30, 30, 0,\n 100, 30, 0,\n 100, 0, 0,\n\n // middle rung front\n 30, 60, 0,\n 30, 90, 0,\n 67, 60, 0,\n 30, 90, 0,\n 67, 90, 0,\n 67, 60, 0,\n\n // left column back\n 0, 0, 30,\n 30, 0, 30,\n 0, 150, 30,\n 0, 150, 30,\n 30, 0, 30,\n 30, 150, 30,\n\n // top rung back\n 30, 0, 30,\n 100, 0, 30,\n 30, 30, 30,\n 30, 30, 30,\n 100, 0, 30,\n 100, 30, 30,\n\n // middle rung back\n 30, 60, 30,\n 67, 60, 30,\n 30, 90, 30,\n 30, 90, 30,\n 67, 60, 30,\n 67, 90, 30,\n\n // top\n 0, 0, 0,\n 100, 0, 0,\n 100, 0, 30,\n 0, 0, 0,\n 100, 0, 30,\n 0, 0, 30,\n\n // top rung front\n 100, 0, 0,\n 100, 30, 0,\n 100, 30, 30,\n 100, 0, 0,\n 100, 30, 30,\n 100, 0, 30,\n\n // under top rung\n 30, 30, 0,\n 30, 30, 30,\n 100, 30, 30,\n 30, 30, 0,\n 100, 30, 30,\n 100, 30, 0,\n\n // between top rung and middle\n 30, 30, 0,\n 30, 60, 30,\n 30, 30, 30,\n 30, 30, 0,\n 30, 60, 0,\n 30, 60, 30,\n\n // top of middle rung\n 30, 60, 0,\n 67, 60, 30,\n 30, 60, 30,\n 30, 60, 0,\n 67, 60, 0,\n 67, 60, 30,\n\n // front of middle rung\n 67, 60, 0,\n 67, 90, 30,\n 67, 60, 30,\n 67, 60, 0,\n 67, 90, 0,\n 67, 90, 30,\n\n // bottom of middle rung.\n 30, 90, 0,\n 30, 90, 30,\n 67, 90, 30,\n 30, 90, 0,\n 67, 90, 30,\n 67, 90, 0,\n\n // front of bottom\n 30, 90, 0,\n 30, 150, 30,\n 30, 90, 30,\n 30, 90, 0,\n 30, 150, 0,\n 30, 150, 30,\n\n // bottom\n 0, 150, 0,\n 0, 150, 30,\n 30, 150, 30,\n 0, 150, 0,\n 30, 150, 30,\n 30, 150, 0,\n\n // left side\n 0, 0, 0,\n 0, 0, 30,\n 0, 150, 30,\n 0, 0, 0,\n 0, 150, 30,\n 0, 150, 0,\n ];\n\n const texcoords = [\n // left column front\n 0.22, 0.19,\n 0.22, 0.79,\n 0.34, 0.19,\n 0.22, 0.79,\n 0.34, 0.79,\n 0.34, 0.19,\n\n // top rung front\n 0.34, 0.19,\n 0.34, 0.31,\n 0.62, 0.19,\n 0.34, 0.31,\n 0.62, 0.31,\n 0.62, 0.19,\n\n // middle rung front\n 0.34, 0.43,\n 0.34, 0.55,\n 0.49, 0.43,\n 0.34, 0.55,\n 0.49, 0.55,\n 0.49, 0.43,\n\n // left column back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // middle rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // top rung front\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // under top rung\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // between top rung and middle\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // top of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // front of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom of middle rung.\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // front of bottom\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // left side\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n ];\n\n const normals = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 0, 0, 1,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 0, 0, -1,\n\n // top\n 6, 0, 1, 0,\n\n // top rung front\n 6, 1, 0, 0,\n\n // under top rung\n 6, 0, -1, 0,\n\n // between top rung and middle\n 6, 1, 0, 0,\n\n // top of middle rung\n 6, 0, 1, 0,\n\n // front of middle rung\n 6, 1, 0, 0,\n\n // bottom of middle rung.\n 6, 0, -1, 0,\n\n // front of bottom\n 6, 1, 0, 0,\n\n // bottom\n 6, 0, -1, 0,\n\n // left side\n 6, -1, 0, 0,\n ]);\n\n const colors = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 200, 70, 120,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 80, 70, 200,\n\n // top\n 6, 70, 200, 210,\n\n // top rung front\n 6, 200, 200, 70,\n\n // under top rung\n 6, 210, 100, 70,\n\n // between top rung and middle\n 6, 210, 160, 70,\n\n // top of middle rung\n 6, 70, 180, 210,\n\n // front of middle rung\n 6, 100, 70, 210,\n\n // bottom of middle rung.\n 6, 76, 210, 100,\n\n // front of bottom\n 6, 140, 210, 80,\n\n // bottom\n 6, 90, 130, 110,\n\n // left side\n 6, 160, 160, 220,\n ], [255]);\n\n const numVerts = positions.length / 3;\n\n const arrays = {\n position: createAugmentedTypedArray(3, numVerts),\n texcoord: createAugmentedTypedArray(2, numVerts),\n normal: createAugmentedTypedArray(3, numVerts),\n color: createAugmentedTypedArray(4, numVerts, Uint8Array),\n indices: createAugmentedTypedArray(3, numVerts / 3, Uint16Array),\n };\n\n arrays.position.push(positions);\n arrays.texcoord.push(texcoords);\n arrays.normal.push(normals);\n arrays.color.push(colors);\n\n for (let ii = 0; ii < numVerts; ++ii) {\n arrays.indices.push(ii);\n }\n\n return arrays;\n}\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCresentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCrescentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCrescentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\n function createCrescentVertices(\n verticalRadius,\n outerRadius,\n innerRadius,\n thickness,\n subdivisionsDown,\n startOffset,\n endOffset) {\n if (subdivisionsDown <= 0) {\n throw new Error('subdivisionDown must be > 0');\n }\n\n startOffset = startOffset || 0;\n endOffset = endOffset || 1;\n\n const subdivisionsThick = 2;\n\n const offsetRange = endOffset - startOffset;\n const numVertices = (subdivisionsDown + 1) * 2 * (2 + subdivisionsThick);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n function lerp(a, b, s) {\n return a + (b - a) * s;\n }\n\n function createArc(arcRadius, x, normalMult, normalAdd, uMult, uAdd) {\n for (let z = 0; z <= subdivisionsDown; z++) {\n const uBack = x / (subdivisionsThick - 1);\n const v = z / subdivisionsDown;\n const xBack = (uBack - 0.5) * 2;\n const angle = (startOffset + (v * offsetRange)) * Math.PI;\n const s = Math.sin(angle);\n const c = Math.cos(angle);\n const radius = lerp(verticalRadius, arcRadius, s);\n const px = xBack * thickness;\n const py = c * verticalRadius;\n const pz = s * radius;\n positions.push(px, py, pz);\n const n = add(multiply$1([0, s, c], normalMult), normalAdd);\n normals.push(n);\n texcoords.push(uBack * uMult + uAdd, v);\n }\n }\n\n // Generate the individual vertices in our vertex buffer.\n for (let x = 0; x < subdivisionsThick; x++) {\n const uBack = (x / (subdivisionsThick - 1) - 0.5) * 2;\n createArc(outerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(outerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 0);\n createArc(innerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(innerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 1);\n }\n\n // Do outer surface.\n const indices = createAugmentedTypedArray(3, (subdivisionsDown * 2) * (2 + subdivisionsThick), Uint16Array);\n\n function createSurface(leftArcOffset, rightArcOffset) {\n for (let z = 0; z < subdivisionsDown; ++z) {\n // Make triangle 1 of quad.\n indices.push(\n leftArcOffset + z + 0,\n leftArcOffset + z + 1,\n rightArcOffset + z + 0);\n\n // Make triangle 2 of quad.\n indices.push(\n leftArcOffset + z + 1,\n rightArcOffset + z + 1,\n rightArcOffset + z + 0);\n }\n }\n\n const numVerticesDown = subdivisionsDown + 1;\n // front\n createSurface(numVerticesDown * 0, numVerticesDown * 4);\n // right\n createSurface(numVerticesDown * 5, numVerticesDown * 7);\n // back\n createSurface(numVerticesDown * 6, numVerticesDown * 2);\n // left\n createSurface(numVerticesDown * 3, numVerticesDown * 1);\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates cylinder BufferInfo. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCylinderBufferInfo\n */\n\n /**\n * Creates cylinder buffers. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCylinderBuffers\n */\n\n /**\n * Creates cylinder vertices. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCylinderVertices(\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap) {\n return createTruncatedConeVertices(\n radius,\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap);\n}\n\n/**\n * Creates BufferInfo for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTorusBufferInfo\n */\n\n/**\n * Creates buffers for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createTorusBuffers\n */\n\n/**\n * Creates vertices for a torus\n *\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTorusVertices(\n radius,\n thickness,\n radialSubdivisions,\n bodySubdivisions,\n startAngle,\n endAngle) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (bodySubdivisions < 3) {\n throw new Error('verticalSubdivisions must be 3 or greater');\n }\n\n startAngle = startAngle || 0;\n endAngle = endAngle || Math.PI * 2;\n const range = endAngle - startAngle;\n\n const radialParts = radialSubdivisions + 1;\n const bodyParts = bodySubdivisions + 1;\n const numVertices = radialParts * bodyParts;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array);\n\n for (let slice = 0; slice < bodyParts; ++slice) {\n const v = slice / bodySubdivisions;\n const sliceAngle = v * Math.PI * 2;\n const sliceSin = Math.sin(sliceAngle);\n const ringRadius = radius + sliceSin * thickness;\n const ny = Math.cos(sliceAngle);\n const y = ny * thickness;\n for (let ring = 0; ring < radialParts; ++ring) {\n const u = ring / radialSubdivisions;\n const ringAngle = startAngle + u * range;\n const xSin = Math.sin(ringAngle);\n const zCos = Math.cos(ringAngle);\n const x = xSin * ringRadius;\n const z = zCos * ringRadius;\n const nx = xSin * sliceSin;\n const nz = zCos * sliceSin;\n positions.push(x, y, z);\n normals.push(nx, ny, nz);\n texcoords.push(u, 1 - v);\n }\n }\n\n for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line\n for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line\n const nextRingIndex = 1 + ring;\n const nextSliceIndex = 1 + slice;\n indices.push(radialParts * slice + ring,\n radialParts * nextSliceIndex + ring,\n radialParts * slice + nextRingIndex);\n indices.push(radialParts * nextSliceIndex + ring,\n radialParts * nextSliceIndex + nextRingIndex,\n radialParts * slice + nextRingIndex);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n\n/**\n * Creates a disc BufferInfo. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createDiscBufferInfo\n */\n\n/**\n * Creates disc buffers. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createDiscBuffers\n */\n\n/**\n * Creates disc vertices. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createDiscVertices(\n radius,\n divisions,\n stacks,\n innerRadius,\n stackPower) {\n if (divisions < 3) {\n throw new Error('divisions must be at least 3');\n }\n\n stacks = stacks ? stacks : 1;\n stackPower = stackPower ? stackPower : 1;\n innerRadius = innerRadius ? innerRadius : 0;\n\n // Note: We don't share the center vertex because that would\n // mess up texture coordinates.\n const numVertices = (divisions + 1) * (stacks + 1);\n\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array);\n\n let firstIndex = 0;\n const radiusSpan = radius - innerRadius;\n const pointsPerStack = divisions + 1;\n\n // Build the disk one stack at a time.\n for (let stack = 0; stack <= stacks; ++stack) {\n const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower);\n\n for (let i = 0; i <= divisions; ++i) {\n const theta = 2.0 * Math.PI * i / divisions;\n const x = stackRadius * Math.cos(theta);\n const z = stackRadius * Math.sin(theta);\n\n positions.push(x, 0, z);\n normals.push(0, 1, 0);\n texcoords.push(1 - (i / divisions), stack / stacks);\n if (stack > 0 && i !== divisions) {\n // a, b, c and d are the indices of the vertices of a quad. unless\n // the current stack is the one closest to the center, in which case\n // the vertices a and b connect to the center vertex.\n const a = firstIndex + (i + 1);\n const b = firstIndex + i;\n const c = firstIndex + i - pointsPerStack;\n const d = firstIndex + (i + 1) - pointsPerStack;\n\n // Make a quad of the vertices a, b, c, d.\n indices.push(a, b, c);\n indices.push(a, c, d);\n }\n }\n\n firstIndex += divisions + 1;\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * creates a random integer between 0 and range - 1 inclusive.\n * @param {number} range\n * @return {number} random value between 0 and range - 1 inclusive.\n * @private\n */\nfunction randInt(range) {\n return Math.random() * range | 0;\n}\n\n/**\n * Used to supply random colors\n * @callback RandomColorFunc\n * @param {number} ndx index of triangle/quad if unindexed or index of vertex if indexed\n * @param {number} channel 0 = red, 1 = green, 2 = blue, 3 = alpha\n * @return {number} a number from 0 to 255\n * @memberOf module:twgl/primitives\n */\n\n/**\n * @typedef {Object} RandomVerticesOptions\n * @property {number} [vertsPerColor] Defaults to 3 for non-indexed vertices\n * @property {module:twgl/primitives.RandomColorFunc} [rand] A function to generate random numbers\n * @memberOf module:twgl/primitives\n */\n\n/**\n * Creates an augmentedTypedArray of random vertex colors.\n * If the vertices are indexed (have an indices array) then will\n * just make random colors. Otherwise assumes they are triangles\n * and makes one random color for every 3 vertices.\n * @param {Object.} vertices Vertices as returned from one of the createXXXVertices functions.\n * @param {module:twgl/primitives.RandomVerticesOptions} [options] options.\n * @return {Object.} same vertices as passed in with `color` added.\n * @memberOf module:twgl/primitives\n */\nfunction makeRandomVertexColors(vertices, options) {\n options = options || {};\n const numElements = vertices.position.numElements;\n const vColors = createAugmentedTypedArray(4, numElements, Uint8Array);\n const rand = options.rand || function(ndx, channel) {\n return channel < 3 ? randInt(256) : 255;\n };\n vertices.color = vColors;\n if (vertices.indices) {\n // just make random colors if index\n for (let ii = 0; ii < numElements; ++ii) {\n vColors.push(rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3));\n }\n } else {\n // make random colors per triangle\n const numVertsPerColor = options.vertsPerColor || 3;\n const numSets = numElements / numVertsPerColor;\n for (let ii = 0; ii < numSets; ++ii) { // eslint-disable-line\n const color = [rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3)];\n for (let jj = 0; jj < numVertsPerColor; ++jj) {\n vColors.push(color);\n }\n }\n }\n return vertices;\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a buffers for them\n * @private\n */\nfunction createBufferFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1));\n return createBuffersFromArrays(gl, arrays);\n };\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a bufferInfo object for them\n * @private\n */\nfunction createBufferInfoFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1));\n return createBufferInfoFromArrays(gl, arrays);\n };\n}\n\nconst arraySpecPropertyNames = [\n \"numComponents\",\n \"size\",\n \"type\",\n \"normalize\",\n \"stride\",\n \"offset\",\n \"attrib\",\n \"name\",\n \"attribName\",\n];\n\n/**\n * Copy elements from one array to another\n *\n * @param {Array|TypedArray} src source array\n * @param {Array|TypedArray} dst dest array\n * @param {number} dstNdx index in dest to copy src\n * @param {number} [offset] offset to add to copied values\n * @private\n */\nfunction copyElements(src, dst, dstNdx, offset) {\n offset = offset || 0;\n const length = src.length;\n for (let ii = 0; ii < length; ++ii) {\n dst[dstNdx + ii] = src[ii] + offset;\n }\n}\n\n/**\n * Creates an array of the same time\n *\n * @param {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} srcArray array who's type to copy\n * @param {number} length size of new array\n * @return {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} array with same type as srcArray\n * @private\n */\nfunction createArrayOfSameType(srcArray, length) {\n const arraySrc = getArray(srcArray);\n const newArray = new arraySrc.constructor(length);\n let newArraySpec = newArray;\n // If it appears to have been augmented make new one augmented\n if (arraySrc.numComponents && arraySrc.numElements) {\n augmentTypedArray(newArray, arraySrc.numComponents);\n }\n // If it was a full spec make new one a full spec\n if (srcArray.data) {\n newArraySpec = {\n data: newArray,\n };\n copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec);\n }\n return newArraySpec;\n}\n\n/**\n * Concatenates sets of vertices\n *\n * Assumes the vertices match in composition. For example\n * if one set of vertices has positions, normals, and indices\n * all sets of vertices must have positions, normals, and indices\n * and of the same type.\n *\n * Example:\n *\n * const cubeVertices = twgl.primitives.createCubeVertices(2);\n * const sphereVertices = twgl.primitives.createSphereVertices(1, 10, 10);\n * // move the sphere 2 units up\n * twgl.primitives.reorientVertices(\n * sphereVertices, twgl.m4.translation([0, 2, 0]));\n * // merge the sphere with the cube\n * const cubeSphereVertices = twgl.primitives.concatVertices(\n * [cubeVertices, sphereVertices]);\n * // turn them into WebGL buffers and attrib data\n * const bufferInfo = twgl.createBufferInfoFromArrays(gl, cubeSphereVertices);\n *\n * @param {module:twgl.Arrays[]} arrays Array of arrays of vertices\n * @return {module:twgl.Arrays} The concatenated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction concatVertices(arrayOfArrays) {\n const names = {};\n let baseName;\n // get names of all arrays.\n // and numElements for each set of vertices\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n Object.keys(arrays).forEach(function(name) { // eslint-disable-line\n if (!names[name]) {\n names[name] = [];\n }\n if (!baseName && name !== 'indices') {\n baseName = name;\n }\n const arrayInfo = arrays[name];\n const numComponents = getNumComponents(arrayInfo, name);\n const array = getArray(arrayInfo);\n const numElements = array.length / numComponents;\n names[name].push(numElements);\n });\n }\n\n // compute length of combined array\n // and return one for reference\n function getLengthOfCombinedArrays(name) {\n let length = 0;\n let arraySpec;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n length += array.length;\n if (!arraySpec || arrayInfo.data) {\n arraySpec = arrayInfo;\n }\n }\n return {\n length: length,\n spec: arraySpec,\n };\n }\n\n function copyArraysToNewArray(name, base, newArray) {\n let baseIndex = 0;\n let offset = 0;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n if (name === 'indices') {\n copyElements(array, newArray, offset, baseIndex);\n baseIndex += base[ii];\n } else {\n copyElements(array, newArray, offset);\n }\n offset += array.length;\n }\n }\n\n const base = names[baseName];\n\n const newArrays = {};\n Object.keys(names).forEach(function(name) {\n const info = getLengthOfCombinedArrays(name);\n const newArraySpec = createArrayOfSameType(info.spec, info.length);\n copyArraysToNewArray(name, base, getArray(newArraySpec));\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\n/**\n * Creates a duplicate set of vertices\n *\n * This is useful for calling reorientVertices when you\n * also want to keep the original available\n *\n * @param {module:twgl.Arrays} arrays of vertices\n * @return {module:twgl.Arrays} The duplicated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction duplicateVertices(arrays) {\n const newArrays = {};\n Object.keys(arrays).forEach(function(name) {\n const arraySpec = arrays[name];\n const srcArray = getArray(arraySpec);\n const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length);\n copyElements(srcArray, getArray(newArraySpec), 0);\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\nconst create3DFBufferInfo = createBufferInfoFunc(create3DFVertices);\nconst create3DFBuffers = createBufferFunc(create3DFVertices);\nconst createCubeBufferInfo = createBufferInfoFunc(createCubeVertices);\nconst createCubeBuffers = createBufferFunc(createCubeVertices);\nconst createPlaneBufferInfo = createBufferInfoFunc(createPlaneVertices);\nconst createPlaneBuffers = createBufferFunc(createPlaneVertices);\nconst createSphereBufferInfo = createBufferInfoFunc(createSphereVertices);\nconst createSphereBuffers = createBufferFunc(createSphereVertices);\nconst createTruncatedConeBufferInfo = createBufferInfoFunc(createTruncatedConeVertices);\nconst createTruncatedConeBuffers = createBufferFunc(createTruncatedConeVertices);\nconst createXYQuadBufferInfo = createBufferInfoFunc(createXYQuadVertices);\nconst createXYQuadBuffers = createBufferFunc(createXYQuadVertices);\nconst createCrescentBufferInfo = createBufferInfoFunc(createCrescentVertices);\nconst createCrescentBuffers = createBufferFunc(createCrescentVertices);\nconst createCylinderBufferInfo = createBufferInfoFunc(createCylinderVertices);\nconst createCylinderBuffers = createBufferFunc(createCylinderVertices);\nconst createTorusBufferInfo = createBufferInfoFunc(createTorusVertices);\nconst createTorusBuffers = createBufferFunc(createTorusVertices);\nconst createDiscBufferInfo = createBufferInfoFunc(createDiscVertices);\nconst createDiscBuffers = createBufferFunc(createDiscVertices);\n\n// these were mis-spelled until 4.12\nconst createCresentBufferInfo = createCrescentBufferInfo;\nconst createCresentBuffers = createCrescentBuffers;\nconst createCresentVertices = createCrescentVertices;\n\nvar primitives = /*#__PURE__*/Object.freeze({\n __proto__: null,\n create3DFBufferInfo: create3DFBufferInfo,\n create3DFBuffers: create3DFBuffers,\n create3DFVertices: create3DFVertices,\n createAugmentedTypedArray: createAugmentedTypedArray,\n createCubeBufferInfo: createCubeBufferInfo,\n createCubeBuffers: createCubeBuffers,\n createCubeVertices: createCubeVertices,\n createPlaneBufferInfo: createPlaneBufferInfo,\n createPlaneBuffers: createPlaneBuffers,\n createPlaneVertices: createPlaneVertices,\n createSphereBufferInfo: createSphereBufferInfo,\n createSphereBuffers: createSphereBuffers,\n createSphereVertices: createSphereVertices,\n createTruncatedConeBufferInfo: createTruncatedConeBufferInfo,\n createTruncatedConeBuffers: createTruncatedConeBuffers,\n createTruncatedConeVertices: createTruncatedConeVertices,\n createXYQuadBufferInfo: createXYQuadBufferInfo,\n createXYQuadBuffers: createXYQuadBuffers,\n createXYQuadVertices: createXYQuadVertices,\n createCresentBufferInfo: createCresentBufferInfo,\n createCresentBuffers: createCresentBuffers,\n createCresentVertices: createCresentVertices,\n createCrescentBufferInfo: createCrescentBufferInfo,\n createCrescentBuffers: createCrescentBuffers,\n createCrescentVertices: createCrescentVertices,\n createCylinderBufferInfo: createCylinderBufferInfo,\n createCylinderBuffers: createCylinderBuffers,\n createCylinderVertices: createCylinderVertices,\n createTorusBufferInfo: createTorusBufferInfo,\n createTorusBuffers: createTorusBuffers,\n createTorusVertices: createTorusVertices,\n createDiscBufferInfo: createDiscBufferInfo,\n createDiscBuffers: createDiscBuffers,\n createDiscVertices: createDiscVertices,\n deindexVertices: deindexVertices,\n flattenNormals: flattenNormals,\n makeRandomVertexColors: makeRandomVertexColors,\n reorientDirections: reorientDirections,\n reorientNormals: reorientNormals,\n reorientPositions: reorientPositions,\n reorientVertices: reorientVertices,\n concatVertices: concatVertices,\n duplicateVertices: duplicateVertices\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Gets the gl version as a number\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {number} version of gl\n * @private\n */\n//function getVersionAsNumber(gl) {\n// return parseFloat(gl.getParameter(gl.VERSION).substr(6));\n//}\n\n/**\n * Check if context is WebGL 2.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 2.0\n * @memberOf module:twgl\n */\nfunction isWebGL2(gl) {\n // This is the correct check but it's slow\n // return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0\") === 0;\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGL2RenderingContext;\n return !!gl.texStorage2D;\n}\n\n/**\n * Check if context is WebGL 1.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 1.0\n * @memberOf module:twgl\n */\nfunction isWebGL1(gl) {\n // This is the correct check but it's slow\n // const version = getVersionAsNumber(gl);\n // return version <= 1.0 && version > 0.0; // because as of 2016/5 Edge returns 0.96\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGLRenderingContext;\n return !gl.texStorage2D;\n}\n\n/**\n * Gets a string for WebGL enum\n *\n * Note: Several enums are the same. Without more\n * context (which function) it's impossible to always\n * give the correct enum. As it is, for matching values\n * it gives all enums. Checking the WebGL2RenderingContext\n * that means\n *\n * 0 = ZERO | POINT | NONE | NO_ERROR\n * 1 = ONE | LINES | SYNC_FLUSH_COMMANDS_BIT\n * 32777 = BLEND_EQUATION_RGB | BLEND_EQUATION_RGB\n * 36662 = COPY_READ_BUFFER | COPY_READ_BUFFER_BINDING\n * 36663 = COPY_WRITE_BUFFER | COPY_WRITE_BUFFER_BINDING\n * 36006 = FRAMEBUFFER_BINDING | DRAW_FRAMEBUFFER_BINDING\n *\n * It's also not useful for bits really unless you pass in individual bits.\n * In other words\n *\n * const bits = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;\n * twgl.glEnumToString(gl, bits); // not going to work\n *\n * Note that some enums only exist on extensions. If you\n * want them to show up you need to pass the extension at least\n * once. For example\n *\n * const ext = gl.getExtension('WEBGL_compressed_texture_s3tc');\n * if (ext) {\n * twgl.glEnumToString(ext, 0); // just prime the function\n *\n * ..later..\n *\n * const internalFormat = ext.COMPRESSED_RGB_S3TC_DXT1_EXT;\n * console.log(twgl.glEnumToString(gl, internalFormat));\n *\n * Notice I didn't have to pass the extension the second time. This means\n * you can have place that generically gets an enum for texture formats for example.\n * and as long as you primed the function with the extensions\n *\n * If you're using `twgl.addExtensionsToContext` to enable your extensions\n * then twgl will automatically get the extension's enums.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext or any extension object\n * @param {number} value the value of the enum you want to look up.\n * @return {string} enum string or hex value\n * @memberOf module:twgl\n * @function glEnumToString\n */\nconst glEnumToString = (function() {\n const haveEnumsForType = {};\n const enums = {};\n\n function addEnums(gl) {\n const type = gl.constructor.name;\n if (!haveEnumsForType[type]) {\n for (const key in gl) {\n if (typeof gl[key] === 'number') {\n const existing = enums[gl[key]];\n enums[gl[key]] = existing ? `${existing} | ${key}` : key;\n }\n }\n haveEnumsForType[type] = true;\n }\n }\n\n return function glEnumToString(gl, value) {\n addEnums(gl);\n return enums[value] || (typeof value === 'number' ? `0x${value.toString(16)}` : value);\n };\n}());\n\nvar utils = /*#__PURE__*/Object.freeze({\n __proto__: null,\n glEnumToString: glEnumToString,\n isWebGL1: isWebGL1,\n isWebGL2: isWebGL2\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults$1 = {\n textureColor: new Uint8Array([128, 192, 255, 255]),\n textureOptions: {},\n crossOrigin: undefined,\n};\nconst isArrayBuffer = isArrayBuffer$1;\n\n// Should we make this on demand?\nconst getShared2DContext = function() {\n let s_ctx;\n return function getShared2DContext() {\n s_ctx = s_ctx ||\n ((typeof document !== 'undefined' && document.createElement)\n ? document.createElement(\"canvas\").getContext(\"2d\")\n : null);\n return s_ctx;\n };\n}();\n\n// NOTE: Chrome supports 2D canvas in a Worker (behind flag as of v64 but\n// not only does Firefox NOT support it but Firefox freezes immediately\n// if you try to create one instead of just returning null and continuing.\n// : (global.OffscreenCanvas && (new global.OffscreenCanvas(1, 1)).getContext(\"2d\")); // OffscreenCanvas may not support 2d\n\n// NOTE: We can maybe remove some of the need for the 2d canvas. In WebGL2\n// we can use the various unpack settings. Otherwise we could try using\n// the ability of an ImageBitmap to be cut. Unfortunately cutting an ImageBitmap\n// is async and the current TWGL code expects a non-Async result though that\n// might not be a problem. ImageBitmap though is not available in Edge or Safari\n// as of 2018-01-02\n\n/* PixelFormat */\nconst ALPHA = 0x1906;\nconst RGB = 0x1907;\nconst RGBA$1 = 0x1908;\nconst LUMINANCE = 0x1909;\nconst LUMINANCE_ALPHA = 0x190A;\nconst DEPTH_COMPONENT$1 = 0x1902;\nconst DEPTH_STENCIL$1 = 0x84F9;\n\n/* TextureWrapMode */\n// const REPEAT = 0x2901;\n// const MIRRORED_REPEAT = 0x8370;\nconst CLAMP_TO_EDGE$1 = 0x812f;\n\n/* TextureMagFilter */\nconst NEAREST = 0x2600;\nconst LINEAR$1 = 0x2601;\n\n/* TextureMinFilter */\n// const NEAREST_MIPMAP_NEAREST = 0x2700;\n// const LINEAR_MIPMAP_NEAREST = 0x2701;\n// const NEAREST_MIPMAP_LINEAR = 0x2702;\n// const LINEAR_MIPMAP_LINEAR = 0x2703;\n\n/* Texture Target */\nconst TEXTURE_2D$2 = 0x0de1;\nconst TEXTURE_CUBE_MAP$1 = 0x8513;\nconst TEXTURE_3D$1 = 0x806f;\nconst TEXTURE_2D_ARRAY$1 = 0x8c1a;\n\n/* Cubemap Targets */\nconst TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;\nconst TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;\nconst TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;\nconst TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a;\n\n/* Texture Parameters */\nconst TEXTURE_MIN_FILTER = 0x2801;\nconst TEXTURE_MAG_FILTER = 0x2800;\nconst TEXTURE_WRAP_S = 0x2802;\nconst TEXTURE_WRAP_T = 0x2803;\nconst TEXTURE_WRAP_R = 0x8072;\nconst TEXTURE_MIN_LOD = 0x813a;\nconst TEXTURE_MAX_LOD = 0x813b;\nconst TEXTURE_BASE_LEVEL = 0x813c;\nconst TEXTURE_MAX_LEVEL = 0x813d;\nconst TEXTURE_COMPARE_MODE = 0x884C;\nconst TEXTURE_COMPARE_FUNC = 0x884D;\n\n/* Pixel store */\nconst UNPACK_ALIGNMENT = 0x0cf5;\nconst UNPACK_ROW_LENGTH = 0x0cf2;\nconst UNPACK_IMAGE_HEIGHT = 0x806e;\nconst UNPACK_SKIP_PIXELS = 0x0cf4;\nconst UNPACK_SKIP_ROWS = 0x0cf3;\nconst UNPACK_SKIP_IMAGES = 0x806d;\nconst UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;\nconst UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;\nconst UNPACK_FLIP_Y_WEBGL = 0x9240;\n\nconst R8 = 0x8229;\nconst R8_SNORM = 0x8F94;\nconst R16F = 0x822D;\nconst R32F = 0x822E;\nconst R8UI = 0x8232;\nconst R8I = 0x8231;\nconst RG16UI = 0x823A;\nconst RG16I = 0x8239;\nconst RG32UI = 0x823C;\nconst RG32I = 0x823B;\nconst RG8 = 0x822B;\nconst RG8_SNORM = 0x8F95;\nconst RG16F = 0x822F;\nconst RG32F = 0x8230;\nconst RG8UI = 0x8238;\nconst RG8I = 0x8237;\nconst R16UI = 0x8234;\nconst R16I = 0x8233;\nconst R32UI = 0x8236;\nconst R32I = 0x8235;\nconst RGB8 = 0x8051;\nconst SRGB8 = 0x8C41;\nconst RGB565$1 = 0x8D62;\nconst RGB8_SNORM = 0x8F96;\nconst R11F_G11F_B10F = 0x8C3A;\nconst RGB9_E5 = 0x8C3D;\nconst RGB16F = 0x881B;\nconst RGB32F = 0x8815;\nconst RGB8UI = 0x8D7D;\nconst RGB8I = 0x8D8F;\nconst RGB16UI = 0x8D77;\nconst RGB16I = 0x8D89;\nconst RGB32UI = 0x8D71;\nconst RGB32I = 0x8D83;\nconst RGBA8 = 0x8058;\nconst SRGB8_ALPHA8 = 0x8C43;\nconst RGBA8_SNORM = 0x8F97;\nconst RGB5_A1$1 = 0x8057;\nconst RGBA4$1 = 0x8056;\nconst RGB10_A2 = 0x8059;\nconst RGBA16F = 0x881A;\nconst RGBA32F = 0x8814;\nconst RGBA8UI = 0x8D7C;\nconst RGBA8I = 0x8D8E;\nconst RGB10_A2UI = 0x906F;\nconst RGBA16UI = 0x8D76;\nconst RGBA16I = 0x8D88;\nconst RGBA32I = 0x8D82;\nconst RGBA32UI = 0x8D70;\n\nconst DEPTH_COMPONENT16$1 = 0x81A5;\nconst DEPTH_COMPONENT24$1 = 0x81A6;\nconst DEPTH_COMPONENT32F$1 = 0x8CAC;\nconst DEPTH32F_STENCIL8$1 = 0x8CAD;\nconst DEPTH24_STENCIL8$1 = 0x88F0;\n\n/* DataType */\nconst BYTE = 0x1400;\nconst UNSIGNED_BYTE$1 = 0x1401;\nconst SHORT = 0x1402;\nconst UNSIGNED_SHORT$1 = 0x1403;\nconst INT$1 = 0x1404;\nconst UNSIGNED_INT$1 = 0x1405;\nconst FLOAT$1 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5 = 0x8363;\nconst HALF_FLOAT = 0x140B;\nconst HALF_FLOAT_OES = 0x8D61; // Thanks Khronos for making this different >:(\nconst UNSIGNED_INT_2_10_10_10_REV = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;\nconst UNSIGNED_INT_24_8 = 0x84FA;\n\nconst RG = 0x8227;\nconst RG_INTEGER = 0x8228;\nconst RED = 0x1903;\nconst RED_INTEGER = 0x8D94;\nconst RGB_INTEGER = 0x8D98;\nconst RGBA_INTEGER = 0x8D99;\n\nconst formatInfo = {};\n{\n // NOTE: this is named `numColorComponents` vs `numComponents` so we can let Uglify mangle\n // the name.\n const f = formatInfo;\n f[ALPHA] = { numColorComponents: 1, };\n f[LUMINANCE] = { numColorComponents: 1, };\n f[LUMINANCE_ALPHA] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RED] = { numColorComponents: 1, };\n f[RED_INTEGER] = { numColorComponents: 1, };\n f[RG] = { numColorComponents: 2, };\n f[RG_INTEGER] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGB_INTEGER] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RGBA_INTEGER] = { numColorComponents: 4, };\n f[DEPTH_COMPONENT$1] = { numColorComponents: 1, };\n f[DEPTH_STENCIL$1] = { numColorComponents: 2, };\n}\n\n/**\n * @typedef {Object} TextureFormatDetails\n * @property {number} textureFormat format to pass texImage2D and similar functions.\n * @property {boolean} colorRenderable true if you can render to this format of texture.\n * @property {boolean} textureFilterable true if you can filter the texture, false if you can ony use `NEAREST`.\n * @property {number[]} type Array of possible types you can pass to texImage2D and similar function\n * @property {Object.} bytesPerElementMap A map of types to bytes per element\n * @private\n */\n\nlet s_textureInternalFormatInfo;\nfunction getTextureInternalFormatInfo(internalFormat) {\n if (!s_textureInternalFormatInfo) {\n // NOTE: these properties need unique names so we can let Uglify mangle the name.\n const t = {};\n // unsized formats\n t[ALPHA] = { textureFormat: ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE] = { textureFormat: LUMINANCE, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE_ALPHA] = { textureFormat: LUMINANCE_ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [2, 4, 4, 8], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[RGB] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 6, 6, 12, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_5_6_5], };\n t[RGBA$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 8, 8, 16, 2, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1], };\n t[DEPTH_COMPONENT$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_INT$1, UNSIGNED_SHORT$1], };\n\n // sized formats\n t[R8] = { textureFormat: RED, colorRenderable: true, textureFilterable: true, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8_SNORM] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [1], type: [BYTE], };\n t[R16F] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [4, 2], type: [FLOAT$1, HALF_FLOAT], };\n t[R32F] = { textureFormat: RED, colorRenderable: false, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[R8UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [BYTE], };\n t[R16UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_SHORT$1], };\n t[R16I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [SHORT], };\n t[R32UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[R32I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [INT$1], };\n t[RG8] = { textureFormat: RG, colorRenderable: true, textureFilterable: true, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8_SNORM] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [2], type: [BYTE], };\n t[RG16F] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [8, 4], type: [FLOAT$1, HALF_FLOAT], };\n t[RG32F] = { textureFormat: RG, colorRenderable: false, textureFilterable: false, bytesPerElement: [8], type: [FLOAT$1], };\n t[RG8UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [BYTE], };\n t[RG16UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_SHORT$1], };\n t[RG16I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [SHORT], };\n t[RG32UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_INT$1], };\n t[RG32I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [INT$1], };\n t[RGB8] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[SRGB8] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB565$1] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_6_5], };\n t[RGB8_SNORM] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [BYTE], };\n t[R11F_G11F_B10F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_10F_11F_11F_REV], };\n t[RGB9_E5] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_5_9_9_9_REV], };\n t[RGB16F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6], type: [FLOAT$1, HALF_FLOAT], };\n t[RGB32F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [FLOAT$1], };\n t[RGB8UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB8I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [BYTE], };\n t[RGB16UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [UNSIGNED_SHORT$1], };\n t[RGB16I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [SHORT], };\n t[RGB32UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [UNSIGNED_INT$1], };\n t[RGB32I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [INT$1], };\n t[RGBA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[SRGB8_ALPHA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8_SNORM] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [4], type: [BYTE], };\n t[RGB5_A1$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2, 4], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA4$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_4_4_4_4], };\n t[RGB10_A2] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [16, 8], type: [FLOAT$1, HALF_FLOAT], };\n t[RGBA32F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: false, bytesPerElement: [16], type: [FLOAT$1], };\n t[RGBA8UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [BYTE], };\n t[RGB10_A2UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_SHORT$1], };\n t[RGBA16I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [SHORT], };\n t[RGBA32I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [INT$1], };\n t[RGBA32UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [UNSIGNED_INT$1], };\n // Sized Internal\n t[DEPTH_COMPONENT16$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_SHORT$1, UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT24$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT32F$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[DEPTH24_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_24_8], };\n t[DEPTH32F_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT_32_UNSIGNED_INT_24_8_REV], };\n\n Object.keys(t).forEach(function(internalFormat) {\n const info = t[internalFormat];\n info.bytesPerElementMap = {};\n info.bytesPerElement.forEach(function(bytesPerElement, ndx) {\n const type = info.type[ndx];\n info.bytesPerElementMap[type] = bytesPerElement;\n });\n });\n s_textureInternalFormatInfo = t;\n }\n return s_textureInternalFormatInfo[internalFormat];\n}\n\n/**\n * Gets the number of bytes per element for a given internalFormat / type\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @param {number} type The type parameter for texImage2D etc..\n * @return {number} the number of bytes per element for the given internalFormat, type combo\n * @memberOf module:twgl/textures\n */\nfunction getBytesPerElementForInternalFormat(internalFormat, type) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n const bytesPerElement = info.bytesPerElementMap[type];\n if (bytesPerElement === undefined) {\n throw \"unknown internal format\";\n }\n return bytesPerElement;\n}\n\n/**\n * Info related to a specific texture internalFormat as returned\n * from {@link module:twgl/textures.getFormatAndTypeForInternalFormat}.\n *\n * @typedef {Object} TextureFormatInfo\n * @property {number} format Format to pass to texImage2D and related functions\n * @property {number} type Type to pass to texImage2D and related functions\n * @memberOf module:twgl/textures\n */\n\n/**\n * Gets the format and type for a given internalFormat\n *\n * @param {number} internalFormat The internal format\n * @return {module:twgl/textures.TextureFormatInfo} the corresponding format and type,\n * @memberOf module:twgl/textures\n */\nfunction getFormatAndTypeForInternalFormat(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return {\n format: info.textureFormat,\n type: info.type[0],\n };\n}\n\n/**\n * Returns true if value is power of 2\n * @param {number} value number to check.\n * @return true if value is power of 2\n * @private\n */\nfunction isPowerOf2(value) {\n return (value & (value - 1)) === 0;\n}\n\n/**\n * Gets whether or not we can generate mips for the given\n * internal format.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number} width The width parameter from texImage2D etc..\n * @param {number} height The height parameter from texImage2D etc..\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canGenerateMipmap(gl, width, height, internalFormat) {\n if (!isWebGL2(gl)) {\n return isPowerOf2(width) && isPowerOf2(height);\n }\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.colorRenderable && info.textureFilterable;\n}\n\n/**\n * Gets whether or not we can generate mips for the given format\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canFilter(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.textureFilterable;\n}\n\n/**\n * Gets the number of components for a given image format.\n * @param {number} format the format.\n * @return {number} the number of components for the format.\n * @memberOf module:twgl/textures\n */\nfunction getNumComponentsForFormat(format) {\n const info = formatInfo[format];\n if (!info) {\n throw \"unknown format: \" + format;\n }\n return info.numColorComponents;\n}\n\n/**\n * Gets the texture type for a given array type.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @return {number} the gl texture type\n * @private\n */\nfunction getTextureTypeForArrayType(gl, src, defaultType) {\n if (isArrayBuffer(src)) {\n return getGLTypeForTypedArray(src);\n }\n return defaultType || UNSIGNED_BYTE$1;\n}\n\nfunction guessDimensions(gl, target, width, height, numElements) {\n if (numElements % 1 !== 0) {\n throw \"can't guess dimensions\";\n }\n if (!width && !height) {\n const size = Math.sqrt(numElements / (target === TEXTURE_CUBE_MAP$1 ? 6 : 1));\n if (size % 1 === 0) {\n width = size;\n height = size;\n } else {\n width = numElements;\n height = 1;\n }\n } else if (!height) {\n height = numElements / width;\n if (height % 1) {\n throw \"can't guess dimensions\";\n }\n } else if (!width) {\n width = numElements / height;\n if (width % 1) {\n throw \"can't guess dimensions\";\n }\n }\n return {\n width: width,\n height: height,\n };\n}\n\n/**\n * Sets the default texture color.\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * @param {number[]} color Array of 4 values in the range 0 to 1\n * @deprecated see {@link module:twgl.setDefaults}\n * @memberOf module:twgl/textures\n */\nfunction setDefaultTextureColor(color) {\n defaults$1.textureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\nfunction setDefaults$1(newDefaults) {\n copyExistingProperties(newDefaults, defaults$1);\n if (newDefaults.textureColor) {\n setDefaultTextureColor(newDefaults.textureColor);\n }\n}\n\n/**\n * A function to generate the source for a texture.\n * @callback TextureFunc\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options the texture options\n * @return {*} Returns any of the things documented for `src` for {@link module:twgl.TextureOptions}.\n * @memberOf module:twgl\n */\n\n/**\n * Texture options passed to most texture functions. Each function will use whatever options\n * are appropriate for its needs. This lets you pass the same options to all functions.\n *\n * Note: A `TexImageSource` is defined in the WebGL spec as a `HTMLImageElement`, `HTMLVideoElement`,\n * `HTMLCanvasElement`, `ImageBitmap`, or `ImageData`.\n *\n * @typedef {Object} TextureOptions\n * @property {number} [target] the type of texture `gl.TEXTURE_2D` or `gl.TEXTURE_CUBE_MAP`. Defaults to `gl.TEXTURE_2D`.\n * @property {number} [level] the mip level to affect. Defaults to 0. Note, if set auto will be considered false unless explicitly set to true.\n * @property {number} [width] the width of the texture. Only used if src is an array or typed array or null.\n * @property {number} [height] the height of a texture. Only used if src is an array or typed array or null.\n * @property {number} [depth] the depth of a texture. Only used if src is an array or type array or null and target is `TEXTURE_3D` .\n * @property {number} [min] the min filter setting (eg. `gl.LINEAR`). Defaults to `gl.NEAREST_MIPMAP_LINEAR`\n * or if texture is not a power of 2 on both dimensions then defaults to `gl.LINEAR`.\n * @property {number} [mag] the mag filter setting (eg. `gl.LINEAR`). Defaults to `gl.LINEAR`\n * @property {number} [minMag] both the min and mag filter settings.\n * @property {number} [internalFormat] internal format for texture. Defaults to `gl.RGBA`\n * @property {number} [format] format for texture. Defaults to `gl.RGBA`.\n * @property {number} [type] type for texture. Defaults to `gl.UNSIGNED_BYTE` unless `src` is ArrayBufferView. If `src`\n * is ArrayBufferView defaults to type that matches ArrayBufferView type.\n * @property {number} [wrap] Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to `gl.REPEAT` for 2D unless src is WebGL1 and src not npot and `gl.CLAMP_TO_EDGE` for cube\n * @property {number} [wrapS] Texture wrapping for S. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapT] Texture wrapping for T. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapR] Texture wrapping for R. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [minLod] TEXTURE_MIN_LOD setting\n * @property {number} [maxLod] TEXTURE_MAX_LOD setting\n * @property {number} [baseLevel] TEXTURE_BASE_LEVEL setting\n * @property {number} [maxLevel] TEXTURE_MAX_LEVEL setting\n * @property {number} [compareFunc] TEXTURE_COMPARE_FUNC setting\n * @property {number} [compareMode] TEXTURE_COMPARE_MODE setting\n * @property {number} [unpackAlignment] The `gl.UNPACK_ALIGNMENT` used when uploading an array. Defaults to 1.\n * @property {number[]|ArrayBufferView} [color] Color to initialize this texture with if loading an image asynchronously.\n * The default use a blue 1x1 pixel texture. You can set another default by calling `twgl.setDefaults`\n * or you can set an individual texture's initial color by setting this property. Example: `[1, .5, .5, 1]` = pink\n * @property {number} [premultiplyAlpha] Whether or not to premultiply alpha. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [flipY] Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [colorspaceConversion] Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {boolean} [auto] If `undefined` or `true`, in WebGL1, texture filtering is set automatically for non-power of 2 images and\n * mips are generated for power of 2 images. In WebGL2 mips are generated if they can be. Note: if `level` is set above\n * then then `auto` is assumed to be `false` unless explicity set to `true`.\n * @property {number[]} [cubeFaceOrder] The order that cube faces are pulled out of an img or set of images. The default is\n *\n * [gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]\n *\n * @property {(number[]|ArrayBufferView|TexImageSource|TexImageSource[]|string|string[]|module:twgl.TextureFunc)} [src] source for texture\n *\n * If `string` then it's assumed to be a URL to an image. The image will be downloaded async. A usable\n * 1x1 pixel texture will be returned immediately. The texture will be updated once the image has downloaded.\n * If `target` is `gl.TEXTURE_CUBE_MAP` will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.\n * The pieces will be uploaded in `cubeFaceOrder`\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_CUBE_MAP` then it must have 6 entries, one for each face of a cube map.\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_2D_ARRAY` then each entry is a slice of the a 2d array texture\n * and will be scaled to the specified width and height OR to the size of the first image that loads.\n *\n * If `TexImageSource` then it wil be used immediately to create the contents of the texture. Examples `HTMLImageElement`,\n * `HTMLCanvasElement`, `HTMLVideoElement`.\n *\n * If `number[]` or `ArrayBufferView` it's assumed to be data for a texture. If `width` or `height` is\n * not specified it is guessed as follows. First the number of elements is computed by `src.length / numComponents`\n * where `numComponents` is derived from `format`. If `target` is `gl.TEXTURE_CUBE_MAP` then `numElements` is divided\n * by 6. Then\n *\n * * If neither `width` nor `height` are specified and `sqrt(numElements)` is an integer then width and height\n * are set to `sqrt(numElements)`. Otherwise `width = numElements` and `height = 1`.\n *\n * * If only one of `width` or `height` is specified then the other equals `numElements / specifiedDimension`.\n *\n * If `number[]` will be converted to `type`.\n *\n * If `src` is a function it will be called with a `WebGLRenderingContext` and these options.\n * Whatever it returns is subject to these rules. So it can return a string url, an `HTMLElement`\n * an array etc...\n *\n * If `src` is undefined then an empty texture will be created of size `width` by `height`.\n *\n * @property {string} [crossOrigin] What to set the crossOrigin property of images when they are downloaded.\n * default: undefined. Also see {@link module:twgl.setDefaults}.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets any packing state that will be set based on the options.\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setPackState(gl, options) {\n if (options.colorspaceConversion !== undefined) {\n gl.pixelStorei(UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion);\n }\n if (options.premultiplyAlpha !== undefined) {\n gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha);\n }\n if (options.flipY !== undefined) {\n gl.pixelStorei(UNPACK_FLIP_Y_WEBGL, options.flipY);\n }\n}\n\n/**\n * Set skip state to defaults\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setSkipStateToDefault(gl) {\n gl.pixelStorei(UNPACK_ALIGNMENT, 4);\n if (isWebGL2(gl)) {\n gl.pixelStorei(UNPACK_ROW_LENGTH, 0);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_PIXELS, 0);\n gl.pixelStorei(UNPACK_SKIP_ROWS, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n }\n}\n\n/**\n * Sets the parameters of a texture or sampler\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number|WebGLSampler} target texture target or sampler\n * @param {function()} parameteriFn texParameteri or samplerParameteri fn\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @private\n */\nfunction setTextureSamplerParameters(gl, target, parameteriFn, options) {\n if (options.minMag) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.minMag);\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.minMag);\n }\n if (options.min) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.min);\n }\n if (options.mag) {\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.mag);\n }\n if (options.wrap) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrap);\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrap);\n if (target === TEXTURE_3D$1 || isSampler(gl, target)) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrap);\n }\n }\n if (options.wrapR) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrapR);\n }\n if (options.wrapS) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrapS);\n }\n if (options.wrapT) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrapT);\n }\n if (options.minLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MIN_LOD, options.minLod);\n }\n if (options.maxLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LOD, options.maxLod);\n }\n if (options.baseLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_BASE_LEVEL, options.baseLevel);\n }\n if (options.maxLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LEVEL, options.maxLevel);\n }\n if (options.compareFunc !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_FUNC, options.compareFunc);\n }\n if (options.compareMode !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_MODE, options.compareMode);\n }\n}\n\n/**\n * Sets the texture parameters of a texture.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureParameters(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n setTextureSamplerParameters(gl, target, gl.texParameteri, options);\n}\n\n/**\n * Sets the sampler parameters of a sampler.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLSampler} sampler the WebGLSampler to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setSamplerParameters(gl, sampler, options) {\n setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);\n}\n\n/**\n * Creates a new sampler object and sets parameters.\n *\n * Example:\n *\n * const sampler = twgl.createSampler(gl, {\n * minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER\n * wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per sampler.\n * @return {Object.} the created samplers by name\n * @private\n */\nfunction createSampler(gl, options) {\n const sampler = gl.createSampler();\n setSamplerParameters(gl, sampler, options);\n return sampler;\n}\n\n/**\n * Creates a multiple sampler objects and sets parameters on each.\n *\n * Example:\n *\n * const samplers = twgl.createSamplers(gl, {\n * nearest: {\n * minMag: gl.NEAREST,\n * },\n * nearestClampS: {\n * minMag: gl.NEAREST,\n * wrapS: gl.CLAMP_TO_NEAREST,\n * },\n * linear: {\n * minMag: gl.LINEAR,\n * },\n * nearestClamp: {\n * minMag: gl.NEAREST,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClamp: {\n * minMag: gl.LINEAR,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClampT: {\n * minMag: gl.LINEAR,\n * wrapT: gl.CLAMP_TO_EDGE,\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler\n * @private\n */\nfunction createSamplers(gl, samplerOptions) {\n const samplers = {};\n Object.keys(samplerOptions).forEach(function(name) {\n samplers[name] = createSampler(gl, samplerOptions[name]);\n });\n return samplers;\n}\n\n/**\n * Makes a 1x1 pixel\n * If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`.\n * @param {(number[]|ArrayBufferView)} [color] The color using 0-1 values\n * @return {Uint8Array} Unit8Array with color.\n * @private\n */\nfunction make1Pixel(color) {\n color = color || defaults$1.textureColor;\n if (isArrayBuffer(color)) {\n return color;\n }\n return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\n/**\n * Sets filtering or generates mips for texture based on width or height\n * If width or height is not passed in uses `options.width` and//or `options.height`\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @param {number} [width] width of texture\n * @param {number} [height] height of texture\n * @param {number} [internalFormat] The internalFormat parameter from texImage2D etc..\n * @memberOf module:twgl/textures\n */\nfunction setTextureFilteringForSize(gl, tex, options, width, height, internalFormat) {\n options = options || defaults$1.textureOptions;\n internalFormat = internalFormat || RGBA$1;\n const target = options.target || TEXTURE_2D$2;\n width = width || options.width;\n height = height || options.height;\n gl.bindTexture(target, tex);\n if (canGenerateMipmap(gl, width, height, internalFormat)) {\n gl.generateMipmap(target);\n } else {\n const filtering = canFilter(internalFormat) ? LINEAR$1 : NEAREST;\n gl.texParameteri(target, TEXTURE_MIN_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_MAG_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n}\n\nfunction shouldAutomaticallySetTextureFilteringForSize(options) {\n return options.auto === true || (options.auto === undefined && options.level === undefined);\n}\n\n/**\n * Gets an array of cubemap face enums\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @return {number[]} cubemap face enums\n * @private\n */\nfunction getCubeFaceOrder(gl, options) {\n options = options || {};\n return options.cubeFaceOrder || [\n TEXTURE_CUBE_MAP_POSITIVE_X,\n TEXTURE_CUBE_MAP_NEGATIVE_X,\n TEXTURE_CUBE_MAP_POSITIVE_Y,\n TEXTURE_CUBE_MAP_NEGATIVE_Y,\n TEXTURE_CUBE_MAP_POSITIVE_Z,\n TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ];\n}\n\n/**\n * @typedef {Object} FaceInfo\n * @property {number} face gl enum for texImage2D\n * @property {number} ndx face index (0 - 5) into source data\n * @ignore\n */\n\n/**\n * Gets an array of FaceInfos\n * There's a bug in some NVidia drivers that will crash the driver if\n * `gl.TEXTURE_CUBE_MAP_POSITIVE_X` is not uploaded first. So, we take\n * the user's desired order from his faces to WebGL and make sure we\n * do the faces in WebGL order\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @return {FaceInfo[]} cubemap face infos. Arguably the `face` property of each element is redundant but\n * it's needed internally to sort the array of `ndx` properties by `face`.\n * @private\n */\nfunction getCubeFacesWithNdx(gl, options) {\n const faces = getCubeFaceOrder(gl, options);\n // work around bug in NVidia drivers. We have to upload the first face first else the driver crashes :(\n const facesWithNdx = faces.map(function(face, ndx) {\n return { face: face, ndx: ndx };\n });\n facesWithNdx.sort(function(a, b) {\n return a.face - b.face;\n });\n return facesWithNdx;\n}\n\n/**\n * Set a texture from the contents of an element. Will also set\n * texture filtering or generate mips based on the dimensions of the element\n * unless `options.auto === false`. If `target === gl.TEXTURE_CUBE_MAP` will\n * attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {HTMLElement} element a canvas, img, or video element.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @kind function\n */\nfunction setTextureFromElement(gl, tex, element, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n const level = options.level || 0;\n let width = element.width;\n let height = element.height;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // guess the parts\n const imgWidth = element.width;\n const imgHeight = element.height;\n let size;\n let slices;\n if (imgWidth / 6 === imgHeight) {\n // It's 6x1\n size = imgHeight;\n slices = [0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0];\n } else if (imgHeight / 6 === imgWidth) {\n // It's 1x6\n size = imgWidth;\n slices = [0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];\n } else if (imgWidth / 3 === imgHeight / 2) {\n // It's 3x2\n size = imgWidth / 3;\n slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];\n } else if (imgWidth / 2 === imgHeight / 3) {\n // It's 2x3\n size = imgWidth / 2;\n slices = [0, 0, 1, 0, 0, 1, 1, 1, 0, 2, 1, 2];\n } else {\n throw \"can't figure out cube map from element: \" + (element.src ? element.src : element.nodeName);\n }\n const ctx = getShared2DContext();\n if (ctx) {\n ctx.canvas.width = size;\n ctx.canvas.height = size;\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n ctx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);\n gl.texImage2D(f.face, level, internalFormat, format, type, ctx.canvas);\n });\n // Free up the canvas memory\n ctx.canvas.width = 1;\n ctx.canvas.height = 1;\n } else if (typeof createImageBitmap !== 'undefined') {\n // NOTE: It seems like we should prefer ImageBitmap because unlike canvas it's\n // note lossy? (alpha is not premultiplied? although I'm not sure what\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n // We can't easily use a default texture color here as it would have to match\n // the type across all faces where as with a 2D one there's only one face\n // so we're replacing everything all at once. It also has to be the correct size.\n // On the other hand we need all faces to be the same size so as one face loads\n // the rest match else the texture will be un-renderable.\n gl.texImage2D(f.face, level, internalFormat, size, size, 0, format, type, null);\n createImageBitmap(element, xOffset, yOffset, size, size, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n })\n .then(function(imageBitmap) {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n gl.texImage2D(f.face, level, internalFormat, format, type, imageBitmap);\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n });\n });\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n const smallest = Math.min(element.width, element.height);\n const largest = Math.max(element.width, element.height);\n const depth = largest / smallest;\n if (depth % 1 !== 0) {\n throw \"can not compute 3D dimensions of element\";\n }\n const xMult = element.width === largest ? 1 : 0;\n const yMult = element.height === largest ? 1 : 0;\n gl.pixelStorei(UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(UNPACK_ROW_LENGTH, element.width);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n gl.texImage3D(target, level, internalFormat, smallest, smallest, smallest, 0, format, type, null);\n for (let d = 0; d < depth; ++d) {\n const srcX = d * smallest * xMult;\n const srcY = d * smallest * yMult;\n gl.pixelStorei(UNPACK_SKIP_PIXELS, srcX);\n gl.pixelStorei(UNPACK_SKIP_ROWS, srcY);\n gl.texSubImage3D(target, level, 0, 0, d, smallest, smallest, 1, format, type, element);\n }\n setSkipStateToDefault(gl);\n } else {\n gl.texImage2D(target, level, internalFormat, format, type, element);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n}\n\nfunction noop() {\n}\n\n/**\n * Checks whether the url's origin is the same so that we can set the `crossOrigin`\n * @param {string} url url to image\n * @returns {boolean} true if the window's origin is the same as image's url\n * @private\n */\nfunction urlIsSameOrigin(url) {\n if (typeof document !== 'undefined') {\n // for IE really\n const a = document.createElement('a');\n a.href = url;\n return a.hostname === location.hostname &&\n a.port === location.port &&\n a.protocol === location.protocol;\n } else {\n const localOrigin = (new URL(location.href)).origin;\n const urlOrigin = (new URL(url, location.href)).origin;\n return urlOrigin === localOrigin;\n }\n}\n\nfunction setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin) {\n return crossOrigin === undefined && !urlIsSameOrigin(url)\n ? 'anonymous'\n : crossOrigin;\n}\n\n/**\n * Loads an image\n * @param {string} url url to image\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @return {HTMLImageElement} the image being loaded.\n * @private\n */\nfunction loadImage(url, crossOrigin, callback) {\n callback = callback || noop;\n let img;\n crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults$1.crossOrigin;\n crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin);\n if (typeof Image !== 'undefined') {\n img = new Image();\n if (crossOrigin !== undefined) {\n img.crossOrigin = crossOrigin;\n }\n\n const clearEventHandlers = function clearEventHandlers() {\n img.removeEventListener('error', onError); // eslint-disable-line\n img.removeEventListener('load', onLoad); // eslint-disable-line\n img = null;\n };\n\n const onError = function onError() {\n const msg = \"couldn't load image: \" + url;\n error$1(msg);\n callback(msg, img);\n clearEventHandlers();\n };\n\n const onLoad = function onLoad() {\n callback(null, img);\n clearEventHandlers();\n };\n\n img.addEventListener('error', onError);\n img.addEventListener('load', onLoad);\n img.src = url;\n return img;\n } else if (typeof ImageBitmap !== 'undefined') {\n let err;\n let bm;\n const cb = function cb() {\n callback(err, bm);\n };\n\n const options = {};\n if (crossOrigin) {\n options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin\n }\n fetch(url, options).then(function(response) {\n if (!response.ok) {\n throw response;\n }\n return response.blob();\n }).then(function(blob) {\n return createImageBitmap(blob, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n });\n }).then(function(bitmap) {\n // not sure if this works. We don't want\n // to catch the user's error. So, call\n // the callback in a timeout so we're\n // not in this scope inside the promise.\n bm = bitmap;\n setTimeout(cb);\n }).catch(function(e) {\n err = e;\n setTimeout(cb);\n });\n img = null;\n }\n return img;\n}\n\n/**\n * check if object is a TexImageSource\n *\n * @param {Object} obj Object to test\n * @return {boolean} true if object is a TexImageSource\n * @private\n */\nfunction isTexImageSource(obj) {\n return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) ||\n (typeof ImageData !== 'undefined' && obj instanceof ImageData) ||\n (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement);\n}\n\n/**\n * if obj is an TexImageSource then just\n * uses it otherwise if obj is a string\n * then load it first.\n *\n * @param {string|TexImageSource} obj\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @private\n */\nfunction loadAndUseImage(obj, crossOrigin, callback) {\n if (isTexImageSource(obj)) {\n setTimeout(function() {\n callback(null, obj);\n });\n return obj;\n }\n\n return loadImage(obj, crossOrigin, callback);\n}\n\n/**\n * Sets a texture to a 1x1 pixel color. If `options.color === false` is nothing happens. If it's not set\n * the default texture color is used which can be set by calling `setDefaultTextureColor`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction setTextureTo1PixelColor(gl, tex, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n if (options.color === false) {\n return;\n }\n // Assume it's a URL\n // Put 1x1 pixels in texture. That makes it renderable immediately regardless of filtering.\n const color = make1Pixel(options.color);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, 0, RGBA$1, 1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n } else {\n gl.texImage2D(target, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n}\n\n/**\n * The src image(s) used to create a texture.\n *\n * When you call {@link module:twgl.createTexture} or {@link module:twgl.createTextures}\n * you can pass in urls for images to load into the textures. If it's a single url\n * then this will be a single HTMLImageElement. If it's an array of urls used for a cubemap\n * this will be a corresponding array of images for the cubemap.\n *\n * @typedef {HTMLImageElement|HTMLImageElement[]} TextureSrc\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback TextureReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} texture the texture.\n * @param {module:twgl.TextureSrc} source image(s) used to as the src for the texture\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when all images have finished downloading and been uploaded into their respective textures\n * @callback TexturesReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {Object.} textures the created textures by name. Same as returned by {@link module:twgl.createTextures}.\n * @param {Object.} sources the image(s) used for the texture by name.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback CubemapReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each face.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback ThreeDReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each slice.\n * @memberOf module:twgl\n */\n\n/**\n * Loads a texture from an image from a Url as specified in `options.src`\n * If `options.color !== false` will set the texture to a 1x1 pixel color so that the texture is\n * immediately useable. It will be updated with the contents of the image once the image has finished\n * downloading. Filtering options will be set as appropriate for image unless `options.auto === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A function to be called when the image has finished loading. err will\n * be non null if there was an error.\n * @return {HTMLImageElement} the image being downloaded.\n * @memberOf module:twgl/textures\n */\nfunction loadTextureFromUrl(gl, tex, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) {\n if (err) {\n callback(err, tex, img);\n } else {\n setTextureFromElement(gl, tex, img, options);\n callback(null, tex, img);\n }\n });\n return img;\n}\n\n/**\n * Loads a cubemap from 6 urls or TexImageSources as specified in `options.src`. Will set the cubemap to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.CubemapReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadCubemapFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n if (urls.length !== 6) {\n throw \"there must be 6 urls for a cubemap\";\n }\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D$2;\n if (target !== TEXTURE_CUBE_MAP$1) {\n throw \"target must be TEXTURE_CUBE_MAP\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = 6;\n const errors = [];\n const faces = getCubeFaceOrder(gl, options);\n let imgs; // eslint-disable-line\n\n function uploadImg(faceTarget) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n if (img.width !== img.height) {\n errors.push(\"cubemap face img is not a square: \" + img.src);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n // So assuming this is the first image we now have one face that's img sized\n // and 5 faces that are 1x1 pixel so size the other faces\n if (numToLoad === 5) {\n // use the default order\n getCubeFaceOrder().forEach(function(otherTarget) {\n // Should we re-use the same face or a color?\n gl.texImage2D(otherTarget, level, internalFormat, format, type, img);\n });\n } else {\n gl.texImage2D(faceTarget, level, internalFormat, format, type, img);\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(faces[ndx]));\n });\n}\n\n/**\n * Loads a 2d array or 3d texture from urls OR TexImageSources as specified in `options.src`.\n * Will set the texture to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n *\n * If the width and height is not specified the width and height of the first\n * image loaded will be used. Note that since images are loaded async\n * which image downloads first is unknown.\n *\n * If an image is not the same size as the width and height it will be scaled\n * to that width and height.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.ThreeDReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadSlicesFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D_ARRAY$1;\n if (target !== TEXTURE_3D$1 && target !== TEXTURE_2D_ARRAY$1) {\n throw \"target must be TEXTURE_3D or TEXTURE_2D_ARRAY\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = urls.length;\n const errors = [];\n let imgs; // eslint-disable-line\n const level = options.level || 0;\n let width = options.width;\n let height = options.height;\n const depth = urls.length;\n let firstImage = true;\n\n function uploadImg(slice) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n if (firstImage) {\n firstImage = false;\n width = options.width || img.width;\n height = options.height || img.height;\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n\n // put it in every slice otherwise some slices will be 0,0,0,0\n for (let s = 0; s < depth; ++s) {\n gl.texSubImage3D(target, level, 0, 0, s, width, height, 1, format, type, img);\n }\n } else {\n let src = img;\n let ctx;\n if (img.width !== width || img.height !== height) {\n // Size the image to fix\n ctx = getShared2DContext();\n src = ctx.canvas;\n ctx.canvas.width = width;\n ctx.canvas.height = height;\n ctx.drawImage(img, 0, 0, width, height);\n }\n\n gl.texSubImage3D(target, level, 0, 0, slice, width, height, 1, format, type, src);\n\n // free the canvas memory\n if (ctx && src === ctx.canvas) {\n ctx.canvas.width = 0;\n ctx.canvas.height = 0;\n }\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(ndx));\n });\n}\n\n/**\n * Sets a texture from an array or typed array. If the width or height is not provided will attempt to\n * guess the size. See {@link module:twgl.TextureOptions}.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {(number[]|ArrayBufferView)} src An array or typed arry with texture data.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureFromArray(gl, tex, src, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n let width = options.width;\n let height = options.height;\n let depth = options.depth;\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n if (!isArrayBuffer(src)) {\n const Type = getTypedArrayTypeForGLType(type);\n src = new Type(src);\n } else if (src instanceof Uint8ClampedArray) {\n src = new Uint8Array(src.buffer);\n }\n\n const bytesPerElement = getBytesPerElementForInternalFormat(internalFormat, type);\n const numElements = src.byteLength / bytesPerElement; // TODO: check UNPACK_ALIGNMENT?\n if (numElements % 1) {\n throw \"length wrong size for format: \" + glEnumToString(gl, format);\n }\n let dimensions;\n if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n if (!width && !height && !depth) {\n const size = Math.cbrt(numElements);\n if (size % 1 !== 0) {\n throw \"can't guess cube size of array of numElements: \" + numElements;\n }\n width = size;\n height = size;\n depth = size;\n } else if (width && (!height || !depth)) {\n dimensions = guessDimensions(gl, target, height, depth, numElements / width);\n height = dimensions.width;\n depth = dimensions.height;\n } else if (height && (!width || !depth)) {\n dimensions = guessDimensions(gl, target, width, depth, numElements / height);\n width = dimensions.width;\n depth = dimensions.height;\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements / depth);\n width = dimensions.width;\n height = dimensions.height;\n }\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements);\n width = dimensions.width;\n height = dimensions.height;\n }\n setSkipStateToDefault(gl);\n gl.pixelStorei(UNPACK_ALIGNMENT, options.unpackAlignment || 1);\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n const elementsPerElement = bytesPerElement / src.BYTES_PER_ELEMENT;\n const faceSize = numElements / 6 * elementsPerElement;\n\n getCubeFacesWithNdx(gl, options).forEach(f => {\n const offset = faceSize * f.ndx;\n const data = src.subarray(offset, offset + faceSize);\n gl.texImage2D(f.face, level, internalFormat, width, height, 0, format, type, data);\n });\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, src);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, src);\n }\n return {\n width: width,\n height: height,\n depth: depth,\n type: type,\n };\n}\n\n/**\n * Sets a texture with no contents of a certain size. In other words calls `gl.texImage2D` with `null`.\n * You must set `options.width` and `options.height`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setEmptyTexture(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n}\n\n/**\n * Creates a texture based on the options passed in.\n *\n * Note: may reset UNPACK_ALIGNMENT, UNPACK_ROW_LENGTH, UNPACK_IMAGE_HEIGHT, UNPACK_SKIP_IMAGES\n * UNPACK_SKIP_PIXELS, and UNPACK_SKIP_ROWS\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture.\n * @return {WebGLTexture} the created texture.\n * @memberOf module:twgl/textures\n */\nfunction createTexture(gl, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n const tex = gl.createTexture();\n const target = options.target || TEXTURE_2D$2;\n let width = options.width || 1;\n let height = options.height || 1;\n const internalFormat = options.internalFormat || RGBA$1;\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // this should have been the default for cubemaps :(\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n let src = options.src;\n if (src) {\n if (typeof src === \"function\") {\n src = src(gl, options);\n }\n if (typeof (src) === \"string\") {\n loadTextureFromUrl(gl, tex, options, callback);\n } else if (isArrayBuffer(src) ||\n (Array.isArray(src) && (\n typeof src[0] === 'number' ||\n Array.isArray(src[0]) ||\n isArrayBuffer(src[0]))\n )\n ) {\n const dimensions = setTextureFromArray(gl, tex, src, options);\n width = dimensions.width;\n height = dimensions.height;\n } else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) {\n if (target === TEXTURE_CUBE_MAP$1) {\n loadCubemapFromUrls(gl, tex, options, callback);\n } else {\n loadSlicesFromUrls(gl, tex, options, callback);\n }\n } else { // if (isTexImageSource(src))\n setTextureFromElement(gl, tex, src, options);\n width = src.width;\n height = src.height;\n }\n } else {\n setEmptyTexture(gl, tex, options);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n return tex;\n}\n\n/**\n * Resizes a texture based on the options passed in.\n *\n * Note: This is not a generic resize anything function.\n * It's mostly used by {@link module:twgl.resizeFramebufferInfo}\n * It will use `options.src` if it exists to try to determine a `type`\n * otherwise it will assume `gl.UNSIGNED_BYTE`. No data is provided\n * for the texture. Texture parameters will be set accordingly\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the texture to resize\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {number} [width] the new width. If not passed in will use `options.width`\n * @param {number} [height] the new height. If not passed in will use `options.height`\n * @param {number} [depth] the new depth. If not passed in will use `options.depth`\n * @memberOf module:twgl/textures\n */\nfunction resizeTexture(gl, tex, options, width, height, depth) {\n width = width || options.width;\n height = height || options.height;\n depth = depth || options.depth;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n let type;\n const src = options.src;\n if (!src) {\n type = options.type || formatType.type;\n } else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) {\n type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n } else {\n type = options.type || formatType.type;\n }\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null);\n }\n}\n\n/**\n * Check if a src is an async request.\n * if src is a string we're going to download an image\n * if src is an array of strings we're going to download cubemap images\n * @param {*} src The src from a TextureOptions\n * @returns {bool} true if src is async.\n * @private\n */\nfunction isAsyncSrc(src) {\n return typeof src === 'string' ||\n (Array.isArray(src) && typeof src[0] === 'string');\n}\n\n/**\n * Creates a bunch of textures based on the passed in options.\n *\n * Example:\n *\n * const textures = twgl.createTextures(gl, {\n * // a power of 2 image\n * hftIcon: { src: \"images/hft-icon-16.png\", mag: gl.NEAREST },\n * // a non-power of 2 image\n * clover: { src: \"images/clover.jpg\" },\n * // From a canvas\n * fromCanvas: { src: ctx.canvas },\n * // A cubemap from 6 images\n * yokohama: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: [\n * 'images/yokohama/posx.jpg',\n * 'images/yokohama/negx.jpg',\n * 'images/yokohama/posy.jpg',\n * 'images/yokohama/negy.jpg',\n * 'images/yokohama/posz.jpg',\n * 'images/yokohama/negz.jpg',\n * ],\n * },\n * // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1)\n * goldengate: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: 'images/goldengate.jpg',\n * },\n * // A 2x2 pixel texture from a JavaScript array\n * checker: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * src: [\n * 255,255,255,255,\n * 192,192,192,255,\n * 192,192,192,255,\n * 255,255,255,255,\n * ],\n * },\n * // a 1x2 pixel texture from a typed array.\n * stripe: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * format: gl.LUMINANCE,\n * src: new Uint8Array([\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * ]),\n * width: 1,\n * },\n * });\n *\n * Now\n *\n * * `textures.hftIcon` will be a 2d texture\n * * `textures.clover` will be a 2d texture\n * * `textures.fromCanvas` will be a 2d texture\n * * `textures.yohohama` will be a cubemap texture\n * * `textures.goldengate` will be a cubemap texture\n * * `textures.checker` will be a 2d texture\n * * `textures.stripe` will be a 2d texture\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per texture.\n * @param {module:twgl.TexturesReadyCallback} [callback] A callback called when all textures have been downloaded.\n * @return {Object.} the created textures by name\n * @memberOf module:twgl/textures\n */\nfunction createTextures(gl, textureOptions, callback) {\n callback = callback || noop;\n let numDownloading = 0;\n const errors = [];\n const textures = {};\n const images = {};\n\n function callCallbackIfReady() {\n if (numDownloading === 0) {\n setTimeout(function() {\n callback(errors.length ? errors : undefined, textures, images);\n }, 0);\n }\n }\n\n Object.keys(textureOptions).forEach(function(name) {\n const options = textureOptions[name];\n let onLoadFn;\n if (isAsyncSrc(options.src)) {\n onLoadFn = function(err, tex, img) {\n images[name] = img;\n --numDownloading;\n if (err) {\n errors.push(err);\n }\n callCallbackIfReady();\n };\n ++numDownloading;\n }\n textures[name] = createTexture(gl, options, onLoadFn);\n });\n\n // queue the callback if there are no images to download.\n // We do this because if your code is structured to wait for\n // images to download but then you comment out all the async\n // images your code would break.\n callCallbackIfReady();\n\n return textures;\n}\n\nvar textures = /*#__PURE__*/Object.freeze({\n __proto__: null,\n setTextureDefaults_: setDefaults$1,\n createSampler: createSampler,\n createSamplers: createSamplers,\n setSamplerParameters: setSamplerParameters,\n createTexture: createTexture,\n setEmptyTexture: setEmptyTexture,\n setTextureFromArray: setTextureFromArray,\n loadTextureFromUrl: loadTextureFromUrl,\n setTextureFromElement: setTextureFromElement,\n setTextureFilteringForSize: setTextureFilteringForSize,\n setTextureParameters: setTextureParameters,\n setDefaultTextureColor: setDefaultTextureColor,\n createTextures: createTextures,\n resizeTexture: resizeTexture,\n canGenerateMipmap: canGenerateMipmap,\n canFilter: canFilter,\n getNumComponentsForFormat: getNumComponentsForFormat,\n getBytesPerElementForInternalFormat: getBytesPerElementForInternalFormat,\n getFormatAndTypeForInternalFormat: getFormatAndTypeForInternalFormat\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Low level shader program related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.programs` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/programs\n */\n\nconst error = error$1;\nconst warn = warn$1;\nfunction getElementById(id) {\n return (typeof document !== 'undefined' && document.getElementById)\n ? document.getElementById(id)\n : null;\n}\n\nconst TEXTURE0 = 0x84c0;\nconst DYNAMIC_DRAW = 0x88e8;\n\nconst ARRAY_BUFFER = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$1 = 0x8893;\nconst UNIFORM_BUFFER = 0x8a11;\nconst TRANSFORM_FEEDBACK_BUFFER = 0x8c8e;\n\nconst TRANSFORM_FEEDBACK = 0x8e22;\n\nconst COMPILE_STATUS = 0x8b81;\nconst LINK_STATUS = 0x8b82;\nconst FRAGMENT_SHADER = 0x8b30;\nconst VERTEX_SHADER = 0x8b31;\nconst SEPARATE_ATTRIBS = 0x8c8d;\n\nconst ACTIVE_UNIFORMS = 0x8b86;\nconst ACTIVE_ATTRIBUTES = 0x8b89;\nconst TRANSFORM_FEEDBACK_VARYINGS = 0x8c83;\nconst ACTIVE_UNIFORM_BLOCKS = 0x8a36;\nconst UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44;\nconst UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46;\nconst UNIFORM_BLOCK_DATA_SIZE = 0x8a40;\nconst UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43;\n\nconst FLOAT = 0x1406;\nconst FLOAT_VEC2 = 0x8B50;\nconst FLOAT_VEC3 = 0x8B51;\nconst FLOAT_VEC4 = 0x8B52;\nconst INT = 0x1404;\nconst INT_VEC2 = 0x8B53;\nconst INT_VEC3 = 0x8B54;\nconst INT_VEC4 = 0x8B55;\nconst BOOL = 0x8B56;\nconst BOOL_VEC2 = 0x8B57;\nconst BOOL_VEC3 = 0x8B58;\nconst BOOL_VEC4 = 0x8B59;\nconst FLOAT_MAT2 = 0x8B5A;\nconst FLOAT_MAT3 = 0x8B5B;\nconst FLOAT_MAT4 = 0x8B5C;\nconst SAMPLER_2D = 0x8B5E;\nconst SAMPLER_CUBE = 0x8B60;\nconst SAMPLER_3D = 0x8B5F;\nconst SAMPLER_2D_SHADOW = 0x8B62;\nconst FLOAT_MAT2x3 = 0x8B65;\nconst FLOAT_MAT2x4 = 0x8B66;\nconst FLOAT_MAT3x2 = 0x8B67;\nconst FLOAT_MAT3x4 = 0x8B68;\nconst FLOAT_MAT4x2 = 0x8B69;\nconst FLOAT_MAT4x3 = 0x8B6A;\nconst SAMPLER_2D_ARRAY = 0x8DC1;\nconst SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;\nconst SAMPLER_CUBE_SHADOW = 0x8DC5;\nconst UNSIGNED_INT = 0x1405;\nconst UNSIGNED_INT_VEC2 = 0x8DC6;\nconst UNSIGNED_INT_VEC3 = 0x8DC7;\nconst UNSIGNED_INT_VEC4 = 0x8DC8;\nconst INT_SAMPLER_2D = 0x8DCA;\nconst INT_SAMPLER_3D = 0x8DCB;\nconst INT_SAMPLER_CUBE = 0x8DCC;\nconst INT_SAMPLER_2D_ARRAY = 0x8DCF;\nconst UNSIGNED_INT_SAMPLER_2D = 0x8DD2;\nconst UNSIGNED_INT_SAMPLER_3D = 0x8DD3;\nconst UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;\nconst UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;\n\nconst TEXTURE_2D$1 = 0x0DE1;\nconst TEXTURE_CUBE_MAP = 0x8513;\nconst TEXTURE_3D = 0x806F;\nconst TEXTURE_2D_ARRAY = 0x8C1A;\n\nconst typeMap = {};\n\n/**\n * Returns the corresponding bind point for a given sampler type\n * @private\n */\nfunction getBindPointForSamplerType(gl, type) {\n return typeMap[type].bindPoint;\n}\n\n// This kind of sucks! If you could compose functions as in `var fn = gl[name];`\n// this code could be a lot smaller but that is sadly really slow (T_T)\n\nfunction floatSetter(gl, location) {\n return function(v) {\n gl.uniform1f(location, v);\n };\n}\n\nfunction floatArraySetter(gl, location) {\n return function(v) {\n gl.uniform1fv(location, v);\n };\n}\n\nfunction floatVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2fv(location, v);\n };\n}\n\nfunction floatVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3fv(location, v);\n };\n}\n\nfunction floatVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4fv(location, v);\n };\n}\n\nfunction intSetter(gl, location) {\n return function(v) {\n gl.uniform1i(location, v);\n };\n}\n\nfunction intArraySetter(gl, location) {\n return function(v) {\n gl.uniform1iv(location, v);\n };\n}\n\nfunction intVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2iv(location, v);\n };\n}\n\nfunction intVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3iv(location, v);\n };\n}\n\nfunction intVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4iv(location, v);\n };\n}\n\nfunction uintSetter(gl, location) {\n return function(v) {\n gl.uniform1ui(location, v);\n };\n}\n\nfunction uintArraySetter(gl, location) {\n return function(v) {\n gl.uniform1uiv(location, v);\n };\n}\n\nfunction uintVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2uiv(location, v);\n };\n}\n\nfunction uintVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3uiv(location, v);\n };\n}\n\nfunction uintVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4uiv(location, v);\n };\n}\n\nfunction floatMat2Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2fv(location, false, v);\n };\n}\n\nfunction floatMat3Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3fv(location, false, v);\n };\n}\n\nfunction floatMat4Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4fv(location, false, v);\n };\n}\n\nfunction floatMat23Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x3fv(location, false, v);\n };\n}\n\nfunction floatMat32Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x2fv(location, false, v);\n };\n}\n\nfunction floatMat24Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x4fv(location, false, v);\n };\n}\n\nfunction floatMat42Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x2fv(location, false, v);\n };\n}\n\nfunction floatMat34Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x4fv(location, false, v);\n };\n}\n\nfunction floatMat43Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x3fv(location, false, v);\n };\n}\n\nfunction samplerSetter(gl, type, unit, location) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n return isWebGL2(gl) ? function(textureOrPair) {\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n gl.bindSampler(unit, sampler);\n } : function(texture) {\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n };\n}\n\nfunction samplerArraySetter(gl, type, unit, location, size) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n const units = new Int32Array(size);\n for (let ii = 0; ii < size; ++ii) {\n units[ii] = unit + ii;\n }\n\n return isWebGL2(gl) ? function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(textureOrPair, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.bindSampler(unit, sampler);\n gl.bindTexture(bindPoint, texture);\n });\n } : function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(texture, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n gl.bindTexture(bindPoint, texture);\n });\n };\n}\n\ntypeMap[FLOAT] = { Type: Float32Array, size: 4, setter: floatSetter, arraySetter: floatArraySetter, };\ntypeMap[FLOAT_VEC2] = { Type: Float32Array, size: 8, setter: floatVec2Setter, cols: 2, };\ntypeMap[FLOAT_VEC3] = { Type: Float32Array, size: 12, setter: floatVec3Setter, cols: 3, };\ntypeMap[FLOAT_VEC4] = { Type: Float32Array, size: 16, setter: floatVec4Setter, cols: 4, };\ntypeMap[INT] = { Type: Int32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[INT_VEC2] = { Type: Int32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[INT_VEC3] = { Type: Int32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[INT_VEC4] = { Type: Int32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[UNSIGNED_INT] = { Type: Uint32Array, size: 4, setter: uintSetter, arraySetter: uintArraySetter, };\ntypeMap[UNSIGNED_INT_VEC2] = { Type: Uint32Array, size: 8, setter: uintVec2Setter, cols: 2, };\ntypeMap[UNSIGNED_INT_VEC3] = { Type: Uint32Array, size: 12, setter: uintVec3Setter, cols: 3, };\ntypeMap[UNSIGNED_INT_VEC4] = { Type: Uint32Array, size: 16, setter: uintVec4Setter, cols: 4, };\ntypeMap[BOOL] = { Type: Uint32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[BOOL_VEC2] = { Type: Uint32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[BOOL_VEC3] = { Type: Uint32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[BOOL_VEC4] = { Type: Uint32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[FLOAT_MAT2] = { Type: Float32Array, size: 32, setter: floatMat2Setter, rows: 2, cols: 2, };\ntypeMap[FLOAT_MAT3] = { Type: Float32Array, size: 48, setter: floatMat3Setter, rows: 3, cols: 3, };\ntypeMap[FLOAT_MAT4] = { Type: Float32Array, size: 64, setter: floatMat4Setter, rows: 4, cols: 4, };\ntypeMap[FLOAT_MAT2x3] = { Type: Float32Array, size: 32, setter: floatMat23Setter, rows: 2, cols: 3, };\ntypeMap[FLOAT_MAT2x4] = { Type: Float32Array, size: 32, setter: floatMat24Setter, rows: 2, cols: 4, };\ntypeMap[FLOAT_MAT3x2] = { Type: Float32Array, size: 48, setter: floatMat32Setter, rows: 3, cols: 2, };\ntypeMap[FLOAT_MAT3x4] = { Type: Float32Array, size: 48, setter: floatMat34Setter, rows: 3, cols: 4, };\ntypeMap[FLOAT_MAT4x2] = { Type: Float32Array, size: 64, setter: floatMat42Setter, rows: 4, cols: 2, };\ntypeMap[FLOAT_MAT4x3] = { Type: Float32Array, size: 64, setter: floatMat43Setter, rows: 4, cols: 3, };\ntypeMap[SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[SAMPLER_2D_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_2D_ARRAY_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_CUBE_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[UNSIGNED_INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[UNSIGNED_INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\n\nfunction floatAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n switch (b.value.length) {\n case 4:\n gl.vertexAttrib4fv(index, b.value);\n break;\n case 3:\n gl.vertexAttrib3fv(index, b.value);\n break;\n case 2:\n gl.vertexAttrib2fv(index, b.value);\n break;\n case 1:\n gl.vertexAttrib1fv(index, b.value);\n break;\n default:\n throw new Error('the length of a float constant value must be between 1 and 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribPointer(\n index, b.numComponents || b.size, b.type || FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction intAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4iv(index, b.value);\n } else {\n throw new Error('The length of an integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction uintAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4uiv(index, b.value);\n } else {\n throw new Error('The length of an unsigned integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || UNSIGNED_INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction matAttribSetter(gl, index, typeInfo) {\n const defaultSize = typeInfo.size;\n const count = typeInfo.count;\n\n return function(b) {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n const numComponents = b.size || b.numComponents || defaultSize;\n const size = numComponents / count;\n const type = b.type || FLOAT;\n const typeInfo = typeMap[type];\n const stride = typeInfo.size * numComponents;\n const normalize = b.normalize || false;\n const offset = b.offset || 0;\n const rowOffset = stride / count;\n for (let i = 0; i < count; ++i) {\n gl.enableVertexAttribArray(index + i);\n gl.vertexAttribPointer(\n index + i, size, type, normalize, stride, offset + rowOffset * i);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index + i, b.divisor || 0);\n }\n }\n };\n}\n\n\n\nconst attrTypeMap = {};\nattrTypeMap[FLOAT] = { size: 4, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC2] = { size: 8, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC3] = { size: 12, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC4] = { size: 16, setter: floatAttribSetter, };\nattrTypeMap[INT] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[INT_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[INT_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[INT_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[UNSIGNED_INT] = { size: 4, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC2] = { size: 8, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC3] = { size: 12, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC4] = { size: 16, setter: uintAttribSetter, };\nattrTypeMap[BOOL] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[FLOAT_MAT2] = { size: 4, setter: matAttribSetter, count: 2, };\nattrTypeMap[FLOAT_MAT3] = { size: 9, setter: matAttribSetter, count: 3, };\nattrTypeMap[FLOAT_MAT4] = { size: 16, setter: matAttribSetter, count: 4, };\n\nconst errorRE = /ERROR:\\s*\\d+:(\\d+)/gi;\nfunction addLineNumbersWithError(src, log = '', lineOffset = 0) {\n // Note: Error message formats are not defined by any spec so this may or may not work.\n const matches = [...log.matchAll(errorRE)];\n const lineNoToErrorMap = new Map(matches.map((m, ndx) => {\n const lineNo = parseInt(m[1]);\n const next = matches[ndx + 1];\n const end = next ? next.index : log.length;\n const msg = log.substring(m.index, end);\n return [lineNo - 1, msg];\n }));\n return src.split('\\n').map((line, lineNo) => {\n const err = lineNoToErrorMap.get(lineNo);\n return `${lineNo + 1 + lineOffset}: ${line}${err ? `\\n\\n^^^ ${err}` : ''}`;\n }).join('\\n');\n}\n\n/**\n * Error Callback\n * @callback ErrorCallback\n * @param {string} msg error message.\n * @param {number} [lineOffset] amount to add to line number\n * @memberOf module:twgl\n */\n\n/**\n * Program Callback\n * @callback ProgramCallback\n * @param {string} [err] error message, falsy if no error\n * @param {WebGLProgram|module:twgl.ProgramInfo} [result] the program or programInfo\n */\n\nconst spaceRE = /^[ \\t]*\\n/;\n\n/**\n * Remove the first end of line because WebGL 2.0 requires\n * #version 300 es\n * as the first line. No whitespace allowed before that line\n * so\n *\n * \n *\n * Has one line before it which is invalid according to GLSL ES 3.00\n *\n * @param {string} shaderSource The source of the shader\n * @returns {{shaderSource: string, lineOffset: number}}\n * @private\n */\nfunction prepShaderSource(shaderSource) {\n let lineOffset = 0;\n if (spaceRE.test(shaderSource)) {\n lineOffset = 1;\n shaderSource = shaderSource.replace(spaceRE, '');\n }\n return {lineOffset, shaderSource};\n}\n\n/**\n * @param {module:twgl.ProgramOptions} progOptions\n * @param {string} msg\n * @return null\n * @private\n */\nfunction reportError(progOptions, msg) {\n progOptions.errorCallback(msg);\n if (progOptions.callback) {\n setTimeout(() => {\n progOptions.callback(`${msg}\\n${progOptions.errors.join('\\n')}`);\n });\n }\n return null;\n}\n\n/**\n * Check Shader status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {number} shaderType The shader type\n * @param {WebGLShader} shader The shader\n * @param {ErrorCallback} [errFn] function to receive error message.\n * @return {string} errors or empty string\n * @private\n */\nfunction checkShaderStatus(gl, shaderType, shader, errFn) {\n errFn = errFn || error;\n // Check the compile status\n const compiled = gl.getShaderParameter(shader, COMPILE_STATUS);\n if (!compiled) {\n // Something went wrong during compilation; get the error\n const lastError = gl.getShaderInfoLog(shader);\n const {lineOffset, shaderSource} = prepShaderSource(gl.getShaderSource(shader));\n const error = `${addLineNumbersWithError(shaderSource, lastError, lineOffset)}\\nError compiling ${glEnumToString(gl, shaderType)}: ${lastError}`;\n errFn(error);\n return error;\n }\n return '';\n}\n\n/**\n * @typedef {Object} FullProgramSpec\n * @property {string[]} shaders the shader source or element ids.\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {string[]|module:twgl.FullProgramSpec} ProgramSpec\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {Object} ProgramOptions\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * Gets the program options based on all these optional arguments\n * @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramOptions} an instance of ProgramOptions based on the arguments passed in\n * @private\n */\nfunction getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {\n let transformFeedbackVaryings;\n let transformFeedbackMode;\n let callback;\n if (typeof opt_locations === 'function') {\n opt_errorCallback = opt_locations;\n opt_locations = undefined;\n }\n if (typeof opt_attribs === 'function') {\n opt_errorCallback = opt_attribs;\n opt_attribs = undefined;\n } else if (opt_attribs && !Array.isArray(opt_attribs)) {\n const opt = opt_attribs;\n opt_errorCallback = opt.errorCallback;\n opt_attribs = opt.attribLocations;\n transformFeedbackVaryings = opt.transformFeedbackVaryings;\n transformFeedbackMode = opt.transformFeedbackMode;\n callback = opt.callback;\n }\n\n const errorCallback = opt_errorCallback || error;\n const errors = [];\n const options = {\n errorCallback(msg, ...args) {\n errors.push(msg);\n errorCallback(msg, ...args);\n },\n transformFeedbackVaryings,\n transformFeedbackMode,\n callback,\n errors,\n };\n\n {\n let attribLocations = {};\n if (Array.isArray(opt_attribs)) {\n opt_attribs.forEach(function(attrib, ndx) {\n attribLocations[attrib] = opt_locations ? opt_locations[ndx] : ndx;\n });\n } else {\n attribLocations = opt_attribs || {};\n }\n options.attribLocations = attribLocations;\n }\n\n return options;\n}\n\nconst defaultShaderType = [\n \"VERTEX_SHADER\",\n \"FRAGMENT_SHADER\",\n];\n\nfunction getShaderTypeFromScriptType(gl, scriptType) {\n if (scriptType.indexOf(\"frag\") >= 0) {\n return FRAGMENT_SHADER;\n } else if (scriptType.indexOf(\"vert\") >= 0) {\n return VERTEX_SHADER;\n }\n return undefined;\n}\n\nfunction deleteProgramAndShaders(gl, program, notThese) {\n const shaders = gl.getAttachedShaders(program);\n for (const shader of shaders) {\n if (notThese.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n gl.deleteProgram(program);\n}\n\nconst wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));\n\nfunction createProgramNoCheck(gl, shaders, programOptions) {\n const program = gl.createProgram();\n const {\n attribLocations,\n transformFeedbackVaryings,\n transformFeedbackMode,\n } = getProgramOptions(programOptions);\n\n for (let ndx = 0; ndx < shaders.length; ++ndx) {\n let shader = shaders[ndx];\n if (typeof shader === 'string') {\n const elem = getElementById(shader);\n const src = elem ? elem.text : shader;\n let type = gl[defaultShaderType[ndx]];\n if (elem && elem.type) {\n type = getShaderTypeFromScriptType(gl, elem.type) || type;\n }\n shader = gl.createShader(type);\n gl.shaderSource(shader, prepShaderSource(src).shaderSource);\n gl.compileShader(shader);\n gl.attachShader(program, shader);\n }\n }\n\n Object.entries(attribLocations).forEach(([attrib, loc]) => gl.bindAttribLocation(program, loc, attrib));\n\n {\n let varyings = transformFeedbackVaryings;\n if (varyings) {\n if (varyings.attribs) {\n varyings = varyings.attribs;\n }\n if (!Array.isArray(varyings)) {\n varyings = Object.keys(varyings);\n }\n gl.transformFeedbackVaryings(program, varyings, transformFeedbackMode || SEPARATE_ATTRIBS);\n }\n }\n\n gl.linkProgram(program);\n return program;\n}\n\n/**\n * Creates a program, attaches (and/or compiles) shaders, binds attrib locations, links the\n * program.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgram(gl, [vs, fs], options);\n * twgl.createProgram(gl, [vs, fs], opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error of a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgram(\n gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {\n // This code is really convoluted, because it may or may not be async\n // Maybe it would be better to have a separate function\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaderSet = new Set(shaders);\n const program = createProgramNoCheck(gl, shaders, progOptions);\n\n function hasErrors(gl, program) {\n const errors = getProgramErrors(gl, program, progOptions.errorCallback);\n if (errors) {\n deleteProgramAndShaders(gl, program, shaderSet);\n }\n return errors;\n }\n\n if (progOptions.callback) {\n waitForProgramLinkCompletionAsync(gl, program).then(() => {\n const errors = hasErrors(gl, program);\n progOptions.callback(errors, errors ? undefined : program);\n });\n return undefined;\n }\n\n return hasErrors(gl, program) ? undefined : program;\n}\n\n/**\n * This only works because the functions it wraps the first 2 arguments\n * are gl and any, followed by things that become programOptions\n * @private\n */\nfunction wrapCallbackFnToAsyncFn(fn) {\n return function(gl, arg1, ...args) {\n return new Promise((resolve, reject) => {\n const programOptions = getProgramOptions(...args);\n programOptions.callback = (err, program) => {\n if (err) {\n reject(err);\n } else {\n resolve(program);\n }\n };\n fn(gl, arg1, programOptions);\n });\n };\n}\n\n/**\n * Same as createProgram but returns a promise\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramAsync(gl, [vs, fs], options);\n * twgl.createProgramAsync(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created program\n * @memberOf module:twgl/programs\n */\nconst createProgramAsync = wrapCallbackFnToAsyncFn(createProgram);\n\n/**\n * Same as createProgramInfo but returns a promise\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created ProgramInfo\n * @memberOf module:twgl/programs\n */\nconst createProgramInfoAsync = wrapCallbackFnToAsyncFn(createProgramInfo);\n\nasync function waitForProgramLinkCompletionAsync(gl, program) {\n const ext = gl.getExtension('KHR_parallel_shader_compile');\n const checkFn = ext\n ? (gl, program) => gl.getProgramParameter(program, ext.COMPLETION_STATUS_KHR)\n : () => true;\n\n let waitTime = 0;\n do {\n await wait(waitTime); // must wait at least once\n waitTime = 1000 / 60;\n } while (!checkFn(gl, program));\n}\n\nasync function waitForAllProgramsLinkCompletionAsync(gl, programs) {\n for (const program of Object.values(programs)) {\n await waitForProgramLinkCompletionAsync(gl, program);\n }\n}\n\n/**\n * Check a program's link status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program Program to check\n * @param {ErrorCallback} [errFn] func for errors\n * @return {string?} errors if program is failed, else undefined\n * @private\n */\nfunction getProgramErrors(gl, program, errFn) {\n errFn = errFn || error;\n // Check the link status\n const linked = gl.getProgramParameter(program, LINK_STATUS);\n if (!linked) {\n // something went wrong with the link\n const lastError = gl.getProgramInfoLog(program);\n errFn(`Error in program linking: ${lastError}`);\n // print any errors from these shaders\n const shaders = gl.getAttachedShaders(program);\n const errors = shaders.map(shader => checkShaderStatus(gl, gl.getShaderParameter(shader, gl.SHADER_TYPE), shader, errFn));\n return `${lastError}\\n${errors.filter(_ => _).join('\\n')}`;\n }\n return undefined;\n}\n\n/**\n * Creates a program from 2 script tags.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_options);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderScriptIds Array of ids of the script\n * tags for the shaders. The first is assumed to be the\n * vertex shader, the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromScripts(\n gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaders = [];\n for (const scriptId of shaderScriptIds) {\n const shaderScript = getElementById(scriptId);\n if (!shaderScript) {\n return reportError(progOptions, `unknown script element: ${scriptId}`);\n }\n shaders.push(shaderScript.text);\n }\n return createProgram(gl, shaders, progOptions);\n}\n\n/**\n * Creates a program from 2 sources.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromSource(gl, [vs, fs], opt_options);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromSources(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n return createProgram(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);\n}\n\n/**\n * Returns true if attribute/uniform is a reserved/built in\n *\n * It makes no sense to me why GL returns these because it's\n * illegal to call `gl.getUniformLocation` and `gl.getAttribLocation`\n * with names that start with `gl_` (and `webgl_` in WebGL)\n *\n * I can only assume they are there because they might count\n * when computing the number of uniforms/attributes used when you want to\n * know if you are near the limit. That doesn't really make sense\n * to me but the fact that these get returned are in the spec.\n *\n * @param {WebGLActiveInfo} info As returned from `gl.getActiveUniform` or\n * `gl.getActiveAttrib`.\n * @return {bool} true if it's reserved\n * @private\n */\nfunction isBuiltIn(info) {\n const name = info.name;\n return name.startsWith(\"gl_\") || name.startsWith(\"webgl_\");\n}\n\nconst tokenRE = /(\\.|\\[|]|\\w+)/g;\nconst isDigit = s => s >= '0' && s <= '9';\nfunction addSetterToUniformTree(fullPath, setter, node, uniformSetters) {\n const tokens = fullPath.split(tokenRE).filter(s => s !== '');\n let tokenNdx = 0;\n let path = '';\n\n for (;;) {\n const token = tokens[tokenNdx++]; // has to be name or number\n path += token;\n const isArrayIndex = isDigit(token[0]);\n const accessor = isArrayIndex\n ? parseInt(token)\n : token;\n if (isArrayIndex) {\n path += tokens[tokenNdx++]; // skip ']'\n }\n const isLastToken = tokenNdx === tokens.length;\n if (isLastToken) {\n node[accessor] = setter;\n break;\n } else {\n const token = tokens[tokenNdx++]; // has to be . or [\n const isArray = token === '[';\n const child = node[accessor] || (isArray ? [] : {});\n node[accessor] = child;\n node = child;\n uniformSetters[path] = uniformSetters[path] || function(node) {\n return function(value) {\n setUniformTree(node, value);\n };\n }(child);\n path += token;\n }\n }\n}\n\n/**\n * Creates setter functions for all uniforms of a shader\n * program.\n *\n * @see {@link module:twgl.setUniforms}\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @returns {Object.} an object with a setter by name for each uniform\n * @memberOf module:twgl/programs\n */\nfunction createUniformSetters(gl, program) {\n let textureUnit = 0;\n\n /**\n * Creates a setter for a uniform of the given program with it's\n * location embedded in the setter.\n * @param {WebGLProgram} program\n * @param {WebGLUniformInfo} uniformInfo\n * @returns {function} the created setter.\n */\n function createUniformSetter(program, uniformInfo, location) {\n const isArray = uniformInfo.name.endsWith(\"[0]\");\n const type = uniformInfo.type;\n const typeInfo = typeMap[type];\n if (!typeInfo) {\n throw new Error(`unknown type: 0x${type.toString(16)}`); // we should never get here.\n }\n let setter;\n if (typeInfo.bindPoint) {\n // it's a sampler\n const unit = textureUnit;\n textureUnit += uniformInfo.size;\n if (isArray) {\n setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size);\n } else {\n setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size);\n }\n } else {\n if (typeInfo.arraySetter && isArray) {\n setter = typeInfo.arraySetter(gl, location);\n } else {\n setter = typeInfo.setter(gl, location);\n }\n }\n setter.location = location;\n return setter;\n }\n\n const uniformSetters = {};\n const uniformTree = {};\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n const uniformInfo = gl.getActiveUniform(program, ii);\n if (isBuiltIn(uniformInfo)) {\n continue;\n }\n let name = uniformInfo.name;\n // remove the array suffix.\n if (name.endsWith(\"[0]\")) {\n name = name.substr(0, name.length - 3);\n }\n const location = gl.getUniformLocation(program, uniformInfo.name);\n // the uniform will have no location if it's in a uniform block\n if (location) {\n const setter = createUniformSetter(program, uniformInfo, location);\n uniformSetters[name] = setter;\n addSetterToUniformTree(name, setter, uniformTree, uniformSetters);\n }\n }\n\n return uniformSetters;\n}\n\n/**\n * @typedef {Object} TransformFeedbackInfo\n * @property {number} index index of transform feedback\n * @property {number} type GL type\n * @property {number} size 1 - 4\n * @memberOf module:twgl\n */\n\n/**\n * Create TransformFeedbackInfo for passing to bindTransformFeedbackInfo.\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {Object}\n * @memberOf module:twgl\n */\nfunction createTransformFeedbackInfo(gl, program) {\n const info = {};\n const numVaryings = gl.getProgramParameter(program, TRANSFORM_FEEDBACK_VARYINGS);\n for (let ii = 0; ii < numVaryings; ++ii) {\n const varying = gl.getTransformFeedbackVarying(program, ii);\n info[varying.name] = {\n index: ii,\n type: varying.type,\n size: varying.size,\n };\n }\n return info;\n}\n\n/**\n * Binds buffers for transform feedback.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {(module:twgl.ProgramInfo|Object)} transformFeedbackInfo A ProgramInfo or TransformFeedbackInfo.\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @memberOf module:twgl\n */\nfunction bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfo) {\n if (transformFeedbackInfo.transformFeedbackInfo) {\n transformFeedbackInfo = transformFeedbackInfo.transformFeedbackInfo;\n }\n if (bufferInfo.attribs) {\n bufferInfo = bufferInfo.attribs;\n }\n for (const name in bufferInfo) {\n const varying = transformFeedbackInfo[name];\n if (varying) {\n const buf = bufferInfo[name];\n if (buf.offset) {\n gl.bindBufferRange(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer, buf.offset, buf.size);\n } else {\n gl.bindBufferBase(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer);\n }\n }\n }\n}\n\n/**\n * Creates a transform feedback and sets the buffers\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @return {WebGLTransformFeedback} the created transform feedback\n * @memberOf module:twgl\n */\nfunction createTransformFeedback(gl, programInfo, bufferInfo) {\n const tf = gl.createTransformFeedback();\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, tf);\n gl.useProgram(programInfo.program);\n bindTransformFeedbackInfo(gl, programInfo, bufferInfo);\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, null);\n return tf;\n}\n\n/**\n * @typedef {Object} UniformData\n * @property {string} name The name of the uniform\n * @property {number} type The WebGL type enum for this uniform\n * @property {number} size The number of elements for this uniform\n * @property {number} blockNdx The block index this uniform appears in\n * @property {number} offset The byte offset in the block for this uniform's value\n * @memberOf module:twgl\n */\n\n/**\n * The specification for one UniformBlockObject\n *\n * @typedef {Object} BlockSpec\n * @property {number} index The index of the block.\n * @property {number} size The size in bytes needed for the block\n * @property {number[]} uniformIndices The indices of the uniforms used by the block. These indices\n * correspond to entries in a UniformData array in the {@link module:twgl.UniformBlockSpec}.\n * @property {bool} usedByVertexShader Self explanatory\n * @property {bool} usedByFragmentShader Self explanatory\n * @property {bool} used Self explanatory\n * @memberOf module:twgl\n */\n\n/**\n * A `UniformBlockSpec` represents the data needed to create and bind\n * UniformBlockObjects for a given program\n *\n * @typedef {Object} UniformBlockSpec\n * @property {Object.} blockSpecs The BlockSpec for each block by block name\n * @property {UniformData[]} uniformData An array of data for each uniform by uniform index.\n * @memberOf module:twgl\n */\n\n/**\n * Creates a UniformBlockSpec for the given program.\n *\n * A UniformBlockSpec represents the data needed to create and bind\n * UniformBlockObjects\n *\n * @param {WebGL2RenderingContext} gl A WebGL2 Rendering Context\n * @param {WebGLProgram} program A WebGLProgram for a successfully linked program\n * @return {module:twgl.UniformBlockSpec} The created UniformBlockSpec\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockSpecFromProgram(gl, program) {\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n const uniformData = [];\n const uniformIndices = [];\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n uniformIndices.push(ii);\n uniformData.push({});\n const uniformInfo = gl.getActiveUniform(program, ii);\n uniformData[ii].name = uniformInfo.name;\n }\n\n [\n [ \"UNIFORM_TYPE\", \"type\" ],\n [ \"UNIFORM_SIZE\", \"size\" ], // num elements\n [ \"UNIFORM_BLOCK_INDEX\", \"blockNdx\" ],\n [ \"UNIFORM_OFFSET\", \"offset\", ],\n ].forEach(function(pair) {\n const pname = pair[0];\n const key = pair[1];\n gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function(value, ndx) {\n uniformData[ndx][key] = value;\n });\n });\n\n const blockSpecs = {};\n\n const numUniformBlocks = gl.getProgramParameter(program, ACTIVE_UNIFORM_BLOCKS);\n for (let ii = 0; ii < numUniformBlocks; ++ii) {\n const name = gl.getActiveUniformBlockName(program, ii);\n const blockSpec = {\n index: gl.getUniformBlockIndex(program, name),\n usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n size: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_DATA_SIZE),\n uniformIndices: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),\n };\n blockSpec.used = blockSpec.usedByVertexShader || blockSpec.usedByFragmentShader;\n blockSpecs[name] = blockSpec;\n }\n\n return {\n blockSpecs: blockSpecs,\n uniformData: uniformData,\n };\n}\n\nconst arraySuffixRE = /\\[\\d+\\]\\.$/; // better way to check?\n\nconst pad = (v, padding) => ((v + (padding - 1)) / padding | 0) * padding;\n\nfunction createUniformBlockUniformSetter(view, isArray, rows, cols) {\n if (isArray || rows) {\n cols = cols || 1;\n const numElements = view.length;\n const totalRows = numElements / 4;\n return function(value) {\n let dst = 0;\n let src = 0;\n for (let row = 0; row < totalRows; ++row) {\n for (let col = 0; col < cols; ++col) {\n view[dst++] = value[src++];\n }\n dst += 4 - cols;\n }\n };\n } else {\n return function(value) {\n if (value.length) {\n view.set(value);\n } else {\n view[0] = value;\n }\n };\n }\n}\n\n/**\n * Represents a UniformBlockObject including an ArrayBuffer with all the uniform values\n * and a corresponding WebGLBuffer to hold those values on the GPU\n *\n * @typedef {Object} UniformBlockInfo\n * @property {string} name The name of the block\n * @property {ArrayBuffer} array The array buffer that contains the uniform values\n * @property {Float32Array} asFloat A float view on the array buffer. This is useful\n * inspecting the contents of the buffer in the debugger.\n * @property {WebGLBuffer} buffer A WebGL buffer that will hold a copy of the uniform values for rendering.\n * @property {number} [offset] offset into buffer\n * @property {Object} uniforms A uniform name to ArrayBufferView map.\n * each Uniform has a correctly typed `ArrayBufferView` into array at the correct offset\n * and length of that uniform. So for example a float uniform would have a 1 float `Float32Array`\n * view. A single mat4 would have a 16 element `Float32Array` view. An ivec2 would have an\n * `Int32Array` view, etc.\n * @property {Object} setters A setter for this uniform.\n * The reason to use setters is elements of arrays are padded to vec4 sizes which\n * means if you want to set an array of 4 floats you'd need to set 16 values\n * (or set elements 0, 4, 8, 12). In other words\n * `someBlockInfo.uniforms.some4FloatArrayUniform.set([0, , , , 1, , , , 2, , , , 3])`\n * where as the setter handles just passing in [0, 1, 2, 3] either directly as in\n * `someBlockInfo.setter.some4FloatArrayUniform.set([0, 1, 2, 3])` (not recommended)\n * or via {@link module:twgl.setBlockUniforms}\n * @memberOf module:twgl\n */\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {WebGLProgram} program A WebGLProgram\n * @param {module:twgl.UniformBlockSpec} uniformBlockSpec. A UniformBlockSpec as returned\n * from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) {\n const blockSpecs = uniformBlockSpec.blockSpecs;\n const uniformData = uniformBlockSpec.uniformData;\n const blockSpec = blockSpecs[blockName];\n if (!blockSpec) {\n warn(\"no uniform block object named:\", blockName);\n return {\n name: blockName,\n uniforms: {},\n };\n }\n const array = new ArrayBuffer(blockSpec.size);\n const buffer = gl.createBuffer();\n const uniformBufferIndex = blockSpec.index;\n gl.bindBuffer(UNIFORM_BUFFER, buffer);\n gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex);\n\n let prefix = blockName + \".\";\n if (arraySuffixRE.test(prefix)) {\n prefix = prefix.replace(arraySuffixRE, \".\");\n }\n const uniforms = {};\n const setters = {};\n const setterTree = {};\n blockSpec.uniformIndices.forEach(function(uniformNdx) {\n const data = uniformData[uniformNdx];\n let name = data.name;\n if (name.startsWith(prefix)) {\n name = name.substr(prefix.length);\n }\n const isArray = name.endsWith('[0]');\n if (isArray) {\n name = name.substr(0, name.length - 3);\n }\n const typeInfo = typeMap[data.type];\n const Type = typeInfo.Type;\n const byteLength = isArray\n ? pad(typeInfo.size, 16) * data.size\n : typeInfo.size * data.size;\n const uniformView = new Type(array, data.offset, byteLength / Type.BYTES_PER_ELEMENT);\n uniforms[name] = uniformView;\n // Note: I'm not sure what to do here. The original\n // idea was to create TypedArray views into each part\n // of the block. This is useful, for example if you have\n // a block with { mat4: model; mat4 view; mat4 projection; }\n // you'll get a Float32Array for each one suitable for\n // passing to most JS math libraries including twgl's and glMatrix.js.\n //\n // But, if you have a an array of structures, especially if that\n // array is large, you get a whole bunch of TypedArray views.\n // Every one of them has overhead and switching between them all\n // is probably a cache miss. In that case it would really be better\n // to just have one view (asFloat) and have all the setters\n // just reference the correct portion. But, then you can't easily\n // treat a matrix, or a vec4, as a standalone thing like you can\n // with all the views.\n //\n // Another problem with the views is they are not shared. With\n // uniforms you have one set of setters. With UniformBlockInfo\n // you have a set of setters *pre block instance*. That's because\n // TypedArray views can't be mapped to different buffers.\n //\n // My gut right now is if you really want the speed and compactness\n // then you should probably roll your own solution. TWGL's goal\n // here is ease of use as AFAICT there is no simple generic efficient\n // solution.\n const setter = createUniformBlockUniformSetter(uniformView, isArray, typeInfo.rows, typeInfo.cols);\n setters[name] = setter;\n addSetterToUniformTree(name, setter, setterTree, setters);\n });\n return {\n name: blockName,\n array,\n asFloat: new Float32Array(array), // for debugging\n buffer,\n uniforms,\n setters,\n };\n}\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {module:twgl.ProgramInfo} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo}\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfo(gl, programInfo, blockName) {\n return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName);\n}\n\n/**\n * Binds a uniform block to the matching uniform block point.\n * Matches by blocks by name so blocks must have the same name not just the same\n * structure.\n *\n * If you have changed any values and you upload the values into the corresponding WebGLBuffer\n * call {@link module:twgl.setUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @return {bool} true if buffer was bound. If the programInfo has no block with the same block name\n * no buffer is bound.\n * @memberOf module:twgl/programs\n */\nfunction bindUniformBlock(gl, programInfo, uniformBlockInfo) {\n const uniformBlockSpec = programInfo.uniformBlockSpec || programInfo;\n const blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name];\n if (blockSpec) {\n const bufferBindIndex = blockSpec.index;\n gl.bindBufferRange(UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength);\n return true;\n }\n return false;\n}\n\n/**\n * Uploads the current uniform values to the corresponding WebGLBuffer\n * and binds that buffer to the program's corresponding bind point for the uniform block object.\n *\n * If you haven't changed any values and you only need to bind the uniform block object\n * call {@link module:twgl.bindUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @memberOf module:twgl/programs\n */\nfunction setUniformBlock(gl, programInfo, uniformBlockInfo) {\n if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) {\n gl.bufferData(UNIFORM_BUFFER, uniformBlockInfo.array, DYNAMIC_DRAW);\n }\n}\n\n/**\n * Sets values of a uniform block object\n *\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo A UniformBlockInfo as returned by {@link module:twgl.createUniformBlockInfo}.\n * @param {Object.} values A uniform name to value map where the value is correct for the given\n * type of uniform. So for example given a block like\n *\n * uniform SomeBlock {\n * float someFloat;\n * vec2 someVec2;\n * vec3 someVec3Array[2];\n * int someInt;\n * }\n *\n * You can set the values of the uniform block with\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * someFloat: 12.3,\n * someVec2: [1, 2],\n * someVec3Array: [1, 2, 3, 4, 5, 6],\n * someInt: 5,\n * }\n *\n * Arrays can be JavaScript arrays or typed arrays\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Lights {\n * Light lights[2];\n * };\n *\n * // in JavaScript\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices.\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * **IMPORTANT!**, packing in a UniformBlock is unintuitive.\n * For example the actual layout of `someVec3Array` above in memory\n * is `1, 2, 3, unused, 4, 5, 6, unused`. twgl takes in 6 values\n * as shown about and copies them, skipping the padding. This might\n * be confusing if you're already familiar with Uniform blocks.\n *\n * If you want to deal with the padding yourself you can access the array\n * buffer views directly. eg:\n *\n * someBlockInfo.someVec3Array.set([1, 2, 3, 0, 4, 5, 6, 0]);\n *\n * Any name that doesn't match will be ignored\n * @memberOf module:twgl/programs\n */\nfunction setBlockUniforms(uniformBlockInfo, values) {\n const setters = uniformBlockInfo.setters;\n for (const name in values) {\n const setter = setters[name];\n if (setter) {\n const value = values[name];\n setter(value);\n }\n }\n}\n\nfunction setUniformTree(tree, values) {\n for (const name in values) {\n const prop = tree[name];\n if (typeof prop === 'function') {\n prop(values[name]);\n } else {\n setUniformTree(tree[name], values[name]);\n }\n }\n}\n\n/**\n * Set uniforms and binds related textures.\n *\n * example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\"]);\n *\n * const tex1 = gl.createTexture();\n * const tex2 = gl.createTexture();\n *\n * ... assume we setup the textures with data ...\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the textures AND set the\n * uniforms.\n *\n * twgl.setUniforms(programInfo, uniforms);\n *\n * For the example above it is equivalent to\n *\n * let texUnit = 0;\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex1);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex2);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);\n * gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);\n * gl.uniformMatrix4fv(u_someMatrix, false, [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ]);\n *\n * Note it is perfectly reasonable to call `setUniforms` multiple times. For example\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * };\n *\n * const moreUniforms {\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * twgl.setUniforms(programInfo, uniforms);\n * twgl.setUniforms(programInfo, moreUniforms);\n *\n * You can also add WebGLSamplers to uniform samplers as in\n *\n * const uniforms = {\n * u_someSampler: {\n * texture: someWebGLTexture,\n * sampler: someWebGLSampler,\n * },\n * };\n *\n * In which case both the sampler and texture will be bound to the\n * same unit.\n *\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * uniforms.\n * You can pass multiple objects by putting them in an array or by calling with more arguments.For example\n *\n * const sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * const localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * twgl.setUniforms(programInfo, sharedUniforms, localUniforms);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, sharedUniforms);\n * twgl.setUniforms(programInfo, localUniforms};\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Light lights[2];\n *\n * // in JavaScript\n *\n * twgl.setUniforms(programInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setUniforms(programInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * @memberOf module:twgl/programs\n */\nfunction setUniforms(setters, ...args) { // eslint-disable-line\n const actualSetters = setters.uniformSetters || setters;\n const numArgs = args.length;\n for (let aNdx = 0; aNdx < numArgs; ++aNdx) {\n const values = args[aNdx];\n if (Array.isArray(values)) {\n const numValues = values.length;\n for (let ii = 0; ii < numValues; ++ii) {\n setUniforms(actualSetters, values[ii]);\n }\n } else {\n for (const name in values) {\n const setter = actualSetters[name];\n if (setter) {\n setter(values[name]);\n }\n }\n }\n }\n}\n\n/**\n * Alias for `setUniforms`\n * @function\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * @memberOf module:twgl/programs\n */\nconst setUniformsAndBindTextures = setUniforms;\n\n/**\n * Creates setter functions for all attributes of a shader\n * program. You can pass this to {@link module:twgl.setBuffersAndAttributes} to set all your buffers and attributes.\n *\n * @see {@link module:twgl.setAttributes} for example\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @return {Object.} an object with a setter for each attribute by name.\n * @memberOf module:twgl/programs\n */\nfunction createAttributeSetters(gl, program) {\n const attribSetters = {\n };\n\n const numAttribs = gl.getProgramParameter(program, ACTIVE_ATTRIBUTES);\n for (let ii = 0; ii < numAttribs; ++ii) {\n const attribInfo = gl.getActiveAttrib(program, ii);\n if (isBuiltIn(attribInfo)) {\n continue;\n }\n const index = gl.getAttribLocation(program, attribInfo.name);\n const typeInfo = attrTypeMap[attribInfo.type];\n const setter = typeInfo.setter(gl, index, typeInfo);\n setter.location = index;\n attribSetters[attribInfo.name] = setter;\n }\n\n return attribSetters;\n}\n\n/**\n * Sets attributes and binds buffers (deprecated... use {@link module:twgl.setBuffersAndAttributes})\n *\n * Example:\n *\n * const program = createProgramFromScripts(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const attribSetters = createAttributeSetters(program);\n *\n * const positionBuffer = gl.createBuffer();\n * const texcoordBuffer = gl.createBuffer();\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * };\n *\n * gl.useProgram(program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setAttributes(attribSetters, attribs);\n *\n * Properties of attribs. For each attrib you can add\n * properties:\n *\n * * type: the type of data in the buffer. Default = gl.FLOAT\n * * normalize: whether or not to normalize the data. Default = false\n * * stride: the stride. Default = 0\n * * offset: offset into the buffer. Default = 0\n * * divisor: the divisor for instances. Default = undefined\n *\n * For example if you had 3 value float positions, 2 value\n * float texcoord and 4 value uint8 colors you'd setup your\n * attribs like this\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * a_color: {\n * buffer: colorBuffer,\n * numComponents: 4,\n * type: gl.UNSIGNED_BYTE,\n * normalize: true,\n * },\n * };\n *\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} buffers AttribInfos mapped by attribute name.\n * @memberOf module:twgl/programs\n * @deprecated use {@link module:twgl.setBuffersAndAttributes}\n * @private\n */\nfunction setAttributes(setters, buffers) {\n for (const name in buffers) {\n const setter = setters[name];\n if (setter) {\n setter(buffers[name]);\n }\n }\n}\n\n/**\n * Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate\n *\n * Example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * };\n *\n * const bufferInfo = createBufferInfoFromArrays(gl, arrays);\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setBuffersAndAttributes(gl, programInfo, bufferInfo);\n *\n * For the example above it is equivalent to\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n * gl.enableVertexAttribArray(a_positionLocation);\n * gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);\n * gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);\n * gl.enableVertexAttribArray(a_texcoordLocation);\n * gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {(module:twgl.ProgramInfo|Object.)} setters A `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} or Attribute setters as returned from {@link module:twgl.createAttributeSetters}\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} buffers a `BufferInfo` as returned from {@link module:twgl.createBufferInfoFromArrays}.\n * or a `VertexArrayInfo` as returned from {@link module:twgl.createVertexArrayInfo}\n * @memberOf module:twgl/programs\n */\nfunction setBuffersAndAttributes(gl, programInfo, buffers) {\n if (buffers.vertexArrayObject) {\n gl.bindVertexArray(buffers.vertexArrayObject);\n } else {\n setAttributes(programInfo.attribSetters || programInfo, buffers.attribs);\n if (buffers.indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER$1, buffers.indices);\n }\n }\n}\n\n/**\n * @typedef {Object} ProgramInfo\n * @property {WebGLProgram} program A shader program\n * @property {Object} uniformSetters object of setters as returned from createUniformSetters,\n * @property {Object} attribSetters object of setters as returned from createAttribSetters,\n * @property {module:twgl.UniformBlockSpec} [uniformBlockSpec] a uniform block spec for making UniformBlockInfos with createUniformBlockInfo etc..\n * @property {Object} [transformFeedbackInfo] info for transform feedbacks\n * @memberOf module:twgl\n */\n\n/**\n * Creates a ProgramInfo from an existing program.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {module:twgl.ProgramInfo} The created ProgramInfo.\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfoFromProgram(gl, program) {\n const uniformSetters = createUniformSetters(gl, program);\n const attribSetters = createAttributeSetters(gl, program);\n const programInfo = {\n program,\n uniformSetters,\n attribSetters,\n };\n\n if (isWebGL2(gl)) {\n programInfo.uniformBlockSpec = createUniformBlockSpecFromProgram(gl, program);\n programInfo.transformFeedbackInfo = createTransformFeedbackInfo(gl, program);\n }\n\n return programInfo;\n}\n\nconst notIdRE = /\\s|{|}|;/;\n\n/**\n * Creates a ProgramInfo from 2 sources.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramInfo(gl, [vs, fs], options);\n * twgl.createProgramInfo(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramInfo?} The created ProgramInfo or null if it failed to link or compile\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfo(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const errors = [];\n shaderSources = shaderSources.map(function(source) {\n // Lets assume if there is no \\n it's an id\n if (!notIdRE.test(source)) {\n const script = getElementById(source);\n if (!script) {\n const err = `no element with id: ${source}`;\n progOptions.errorCallback(err);\n errors.push(err);\n } else {\n source = script.text;\n }\n }\n return source;\n });\n\n if (errors.length) {\n return reportError(progOptions, '');\n }\n\n const origCallback = progOptions.callback;\n if (origCallback) {\n progOptions.callback = (err, program) => {\n origCallback(err, err ? undefined : createProgramInfoFromProgram(gl, program));\n };\n }\n\n const program = createProgramFromSources(gl, shaderSources, progOptions);\n if (!program) {\n return null;\n }\n\n return createProgramInfoFromProgram(gl, program);\n}\n\nfunction checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions) {\n // check errors for everything.\n for (const [name, program] of Object.entries(programs)) {\n const options = {...programOptions};\n const spec = programSpecs[name];\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n const errors = getProgramErrors(gl, program, options.errorCallback);\n if (errors) {\n // delete everything we created\n for (const program of Object.values(programs)) {\n const shaders = gl.getAttachedShaders(program);\n gl.deleteProgram(program);\n for (const shader of shaders) {\n // Don't delete it if we didn't create it.\n if (!noDeleteShadersSet.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n }\n return errors;\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates multiple programs\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgram}\n *\n * Example:\n *\n * const programs = twgl.createPrograms(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createPrograms(gl, programSpecs, programOptions = {}) {\n // Remember existing shaders so that if there is an error we don't delete them\n const noDeleteShadersSet = new Set();\n\n // compile and link everything\n const programs = Object.fromEntries(Object.entries(programSpecs).map(([name, spec]) => {\n const options = {...programOptions};\n const shaders = Array.isArray(spec) ? spec : spec.shaders;\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n shaders.forEach(noDeleteShadersSet.add, noDeleteShadersSet);\n return [name, createProgramNoCheck(gl, shaders, options)];\n }));\n\n if (programOptions.callback) {\n waitForAllProgramsLinkCompletionAsync(gl, programs).then(() => {\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n programOptions.callback(errors, errors ? undefined : programs);\n });\n return undefined;\n }\n\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n return errors ? undefined : programs;\n}\n\n/**\n * Creates multiple programInfos\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgramInfo}\n *\n * Examples:\n *\n * const programInfos = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * or\n *\n * const {lambert, phong, particles} = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createProgramInfos(gl, programSpecs, programOptions) {\n programOptions = getProgramOptions(programOptions);\n\n function createProgramInfosForPrograms(gl, programs) {\n return Object.fromEntries(Object.entries(programs).map(([name, program]) =>\n [name, createProgramInfoFromProgram(gl, program)]\n ));\n }\n\n const origCallback = programOptions.callback;\n if (origCallback) {\n programOptions.callback = (err, programs) => {\n origCallback(err, err ? undefined : createProgramInfosForPrograms(gl, programs));\n };\n }\n\n const programs = createPrograms(gl, programSpecs, programOptions);\n if (origCallback || !programs) {\n return undefined;\n }\n\n return createProgramInfosForPrograms(gl, programs);\n}\n\n/**\n * Creates multiple programs asynchronously\n *\n * @see {@link module:twgl.createProgramAsync}\n *\n * Example:\n *\n * const programs = await twgl.createProgramsAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nconst createProgramsAsync = wrapCallbackFnToAsyncFn(createPrograms);\n\n/**\n * Creates multiple programInfos asynchronously\n *\n * @see {@link module:twgl.createProgramInfoAsync}\n *\n * Example:\n *\n * const programInfos = await twgl.createProgramInfosAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Promise>} the created programInfos by name\n */\nconst createProgramInfosAsync = wrapCallbackFnToAsyncFn(createProgramInfos);\n\nvar programs = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttributeSetters: createAttributeSetters,\n createProgram: createProgram,\n createProgramAsync: createProgramAsync,\n createPrograms: createPrograms,\n createProgramsAsync: createProgramsAsync,\n createProgramFromScripts: createProgramFromScripts,\n createProgramFromSources: createProgramFromSources,\n createProgramInfo: createProgramInfo,\n createProgramInfoAsync: createProgramInfoAsync,\n createProgramInfos: createProgramInfos,\n createProgramInfosAsync: createProgramInfosAsync,\n createProgramInfoFromProgram: createProgramInfoFromProgram,\n createUniformSetters: createUniformSetters,\n createUniformBlockSpecFromProgram: createUniformBlockSpecFromProgram,\n createUniformBlockInfoFromProgram: createUniformBlockInfoFromProgram,\n createUniformBlockInfo: createUniformBlockInfo,\n createTransformFeedback: createTransformFeedback,\n createTransformFeedbackInfo: createTransformFeedbackInfo,\n bindTransformFeedbackInfo: bindTransformFeedbackInfo,\n setAttributes: setAttributes,\n setBuffersAndAttributes: setBuffersAndAttributes,\n setUniforms: setUniforms,\n setUniformsAndBindTextures: setUniformsAndBindTextures,\n setUniformBlock: setUniformBlock,\n setBlockUniforms: setBlockUniforms,\n bindUniformBlock: bindUniformBlock\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst TRIANGLES = 0x0004;\nconst UNSIGNED_SHORT = 0x1403;\n\n/**\n * Drawing related functions\n *\n * For backward compatibility they are available at both `twgl.draw` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/draw\n */\n\n/**\n * Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate\n *\n * normally you'd call `gl.drawElements` or `gl.drawArrays` yourself\n * but calling this means if you switch from indexed data to non-indexed\n * data you don't have to remember to update your draw call.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} bufferInfo A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays} or\n * a VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @param {number} [type] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to `gl.TRIANGLES`\n * @param {number} [count] An optional count. Defaults to bufferInfo.numElements\n * @param {number} [offset] An optional offset. Defaults to 0.\n * @param {number} [instanceCount] An optional instanceCount. if set then `drawArraysInstanced` or `drawElementsInstanced` will be called\n * @memberOf module:twgl/draw\n */\nfunction drawBufferInfo(gl, bufferInfo, type, count, offset, instanceCount) {\n type = type === undefined ? TRIANGLES : type;\n const indices = bufferInfo.indices;\n const elementType = bufferInfo.elementType;\n const numElements = count === undefined ? bufferInfo.numElements : count;\n offset = offset === undefined ? 0 : offset;\n if (elementType || indices) {\n if (instanceCount !== undefined) {\n gl.drawElementsInstanced(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset, instanceCount);\n } else {\n gl.drawElements(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset);\n }\n } else {\n if (instanceCount !== undefined) {\n gl.drawArraysInstanced(type, offset, numElements, instanceCount);\n } else {\n gl.drawArrays(type, offset, numElements);\n }\n }\n}\n\n/**\n * A DrawObject is useful for putting objects in to an array and passing them to {@link module:twgl.drawObjectList}.\n *\n * You need either a `BufferInfo` or a `VertexArrayInfo`.\n *\n * @typedef {Object} DrawObject\n * @property {boolean} [active] whether or not to draw. Default = `true` (must be `false` to be not true). In other words `undefined` = `true`\n * @property {number} [type] type to draw eg. `gl.TRIANGLES`, `gl.LINES`, etc...\n * @property {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @property {module:twgl.BufferInfo} [bufferInfo] A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays}\n * @property {module:twgl.VertexArrayInfo} [vertexArrayInfo] A VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @property {Object} uniforms The values for the uniforms.\n * You can pass multiple objects by putting them in an array. For example\n *\n * var sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * var localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * var drawObj = {\n * ...\n * uniforms: [sharedUniforms, localUniforms],\n * };\n *\n * @property {number} [offset] the offset to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to 0.\n * @property {number} [count] the count to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to bufferInfo.numElements.\n * @property {number} [instanceCount] the number of instances. Defaults to undefined.\n * @memberOf module:twgl\n */\n\n/**\n * Draws a list of objects\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {DrawObject[]} objectsToDraw an array of objects to draw.\n * @memberOf module:twgl/draw\n */\nfunction drawObjectList(gl, objectsToDraw) {\n let lastUsedProgramInfo = null;\n let lastUsedBufferInfo = null;\n\n objectsToDraw.forEach(function(object) {\n if (object.active === false) {\n return;\n }\n\n const programInfo = object.programInfo;\n const bufferInfo = object.vertexArrayInfo || object.bufferInfo;\n let bindBuffers = false;\n const type = object.type === undefined ? TRIANGLES : object.type;\n\n if (programInfo !== lastUsedProgramInfo) {\n lastUsedProgramInfo = programInfo;\n gl.useProgram(programInfo.program);\n\n // We have to rebind buffers when changing programs because we\n // only bind buffers the program uses. So if 2 programs use the same\n // bufferInfo but the 1st one uses only positions the when the\n // we switch to the 2nd one some of the attributes will not be on.\n bindBuffers = true;\n }\n\n // Setup all the needed attributes.\n if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject && !bufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n lastUsedBufferInfo = bufferInfo;\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n }\n\n // Set the uniforms.\n setUniforms(programInfo, object.uniforms);\n\n // Draw\n drawBufferInfo(gl, bufferInfo, type, object.count, object.offset, object.instanceCount);\n });\n\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n}\n\nvar draw = /*#__PURE__*/Object.freeze({\n __proto__: null,\n drawBufferInfo: drawBufferInfo,\n drawObjectList: drawObjectList\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst FRAMEBUFFER = 0x8d40;\nconst RENDERBUFFER = 0x8d41;\nconst TEXTURE_2D = 0x0de1;\n\nconst UNSIGNED_BYTE = 0x1401;\n\n/* PixelFormat */\nconst DEPTH_COMPONENT = 0x1902;\nconst RGBA = 0x1908;\nconst DEPTH_COMPONENT24 = 0x81a6;\nconst DEPTH_COMPONENT32F = 0x8cac;\nconst DEPTH24_STENCIL8 = 0x88f0;\nconst DEPTH32F_STENCIL8 = 0x8cad;\n\n/* Framebuffer Object. */\nconst RGBA4 = 0x8056;\nconst RGB5_A1 = 0x8057;\nconst RGB565 = 0x8D62;\nconst DEPTH_COMPONENT16 = 0x81A5;\nconst STENCIL_INDEX = 0x1901;\nconst STENCIL_INDEX8 = 0x8D48;\nconst DEPTH_STENCIL = 0x84F9;\nconst COLOR_ATTACHMENT0 = 0x8CE0;\nconst DEPTH_ATTACHMENT = 0x8D00;\nconst STENCIL_ATTACHMENT = 0x8D20;\nconst DEPTH_STENCIL_ATTACHMENT = 0x821A;\n\n/* TextureWrapMode */\nconst CLAMP_TO_EDGE = 0x812F;\n\n/* TextureMagFilter */\nconst LINEAR = 0x2601;\n\n/**\n * The options for a framebuffer attachment.\n *\n * Note: For a `format` that is a texture include all the texture\n * options from {@link module:twgl.TextureOptions} for example\n * `min`, `mag`, `clamp`, etc... Note that unlike {@link module:twgl.TextureOptions}\n * `auto` defaults to `false` for attachment textures but `min` and `mag` default\n * to `gl.LINEAR` and `wrap` defaults to `CLAMP_TO_EDGE`\n *\n * @typedef {Object} AttachmentOptions\n * @property {number} [attachmentPoint] The attachment point. Defaults\n * to `gl.COLOR_ATTACHMENT0 + ndx` unless type is a depth or stencil type\n * then it's gl.DEPTH_ATTACHMENT or `gl.DEPTH_STENCIL_ATTACHMENT` depending\n * on the format or attachment type.\n * @property {number} [format] The format. If one of `gl.RGBA4`,\n * `gl.RGB565`, `gl.RGB5_A1`, `gl.DEPTH_COMPONENT16`,\n * `gl.STENCIL_INDEX8` or `gl.DEPTH_STENCIL` then will create a\n * renderbuffer. Otherwise will create a texture. Default = `gl.RGBA`\n * @property {number} [type] The type. Used for texture. Default = `gl.UNSIGNED_BYTE`.\n * @property {number} [target] The texture target for `gl.framebufferTexture2D`.\n * Defaults to `gl.TEXTURE_2D`. Set to appropriate face for cube maps.\n * @property {number} [samples] The number of samples. Default = 1\n * @property {number} [level] level for `gl.framebufferTexture2D`. Defaults to 0.\n * @property {number} [layer] layer for `gl.framebufferTextureLayer`. Defaults to undefined.\n * If set then `gl.framebufferTextureLayer` is called, if not then `gl.framebufferTexture2D`\n * @property {(WebGLRenderbuffer | WebGLTexture)} [attachment] An existing renderbuffer or texture.\n * If provided will attach this Object. This allows you to share\n * attachments across framebuffers.\n * @memberOf module:twgl\n * @mixes module:twgl.TextureOptions\n */\n\nconst defaultAttachments = [\n { format: RGBA, type: UNSIGNED_BYTE, min: LINEAR, wrap: CLAMP_TO_EDGE, },\n { format: DEPTH_STENCIL, },\n];\n\nconst attachmentsByFormat = {};\nattachmentsByFormat[DEPTH_STENCIL] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX] = STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX8] = STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT16] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT24] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT32F] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH24_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH32F_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\n\nfunction getAttachmentPointForFormat(format, internalFormat) {\n return attachmentsByFormat[format] || attachmentsByFormat[internalFormat];\n}\n\nconst renderbufferFormats = {};\nrenderbufferFormats[RGBA4] = true;\nrenderbufferFormats[RGB5_A1] = true;\nrenderbufferFormats[RGB565] = true;\nrenderbufferFormats[DEPTH_STENCIL] = true;\nrenderbufferFormats[DEPTH_COMPONENT16] = true;\nrenderbufferFormats[STENCIL_INDEX] = true;\nrenderbufferFormats[STENCIL_INDEX8] = true;\n\nfunction isRenderbufferFormat(format) {\n return renderbufferFormats[format];\n}\n\nconst MAX_COLOR_ATTACHMENT_POINTS = 32; // even an 3090 only supports 8 but WebGL/OpenGL ES define constants for 32\n\nfunction isColorAttachmentPoint(attachmentPoint) {\n return attachmentPoint >= COLOR_ATTACHMENT0 && attachmentPoint < COLOR_ATTACHMENT0 + MAX_COLOR_ATTACHMENT_POINTS;\n}\n\n/**\n * @typedef {Object} FramebufferInfo\n * @property {WebGLFramebuffer} framebuffer The WebGLFramebuffer for this framebufferInfo\n * @property {Array.<(WebGLRenderbuffer | WebGLTexture)>} attachments The created attachments in the same order as passed in to {@link module:twgl.createFramebufferInfo}.\n * @property {number} width The width of the framebuffer and its attachments\n * @property {number} height The width of the framebuffer and its attachments\n * @memberOf module:twgl\n */\n\n/**\n * Creates a framebuffer and attachments.\n *\n * This returns a {@link module:twgl.FramebufferInfo} because it needs to return the attachments as well as the framebuffer.\n * It also leaves the framebuffer it just created as the currently bound `FRAMEBUFFER`.\n * Note: If this is WebGL2 or if you called {@link module:twgl.addExtensionsToContext} then it will set the drawBuffers\n * to `[COLOR_ATTACHMENT0, COLOR_ATTACHMENT1, ...]` for how ever many color attachments were created.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * Passing in a specific size\n *\n * const width = 256;\n * const height = 256;\n * const fbi = twgl.createFramebufferInfo(gl, attachments, width, height);\n *\n * **Note!!** It is up to you to check if the framebuffer is renderable by calling `gl.checkFramebufferStatus`.\n * [WebGL1 only guarantees 3 combinations of attachments work](https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.6).\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.AttachmentOptions[]} [attachments] which attachments to create. If not provided the default is a framebuffer with an\n * `RGBA`, `UNSIGNED_BYTE` texture `COLOR_ATTACHMENT0` and a `DEPTH_STENCIL` renderbuffer `DEPTH_STENCIL_ATTACHMENT`.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @return {module:twgl.FramebufferInfo} the framebuffer and attachments.\n * @memberOf module:twgl/framebuffers\n */\nfunction createFramebufferInfo(gl, attachments, width, height) {\n const target = FRAMEBUFFER;\n const fb = gl.createFramebuffer();\n gl.bindFramebuffer(target, fb);\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n attachments = attachments || defaultAttachments;\n const usedColorAttachmentsPoints = [];\n const framebufferInfo = {\n framebuffer: fb,\n attachments: [],\n width: width,\n height: height,\n };\n\n attachments.forEach(function(attachmentOptions, i) {\n let attachment = attachmentOptions.attachment;\n const samples = attachmentOptions.samples;\n const format = attachmentOptions.format;\n let attachmentPoint = attachmentOptions.attachmentPoint || getAttachmentPointForFormat(format, attachmentOptions.internalFormat);\n if (!attachmentPoint) {\n attachmentPoint = COLOR_ATTACHMENT0 + i;\n }\n if (isColorAttachmentPoint(attachmentPoint)) {\n usedColorAttachmentsPoints.push(attachmentPoint);\n }\n if (!attachment) {\n if (samples !== undefined || isRenderbufferFormat(format)) {\n attachment = gl.createRenderbuffer();\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else {\n const textureOptions = Object.assign({}, attachmentOptions);\n textureOptions.width = width;\n textureOptions.height = height;\n if (textureOptions.auto === undefined) {\n textureOptions.auto = false;\n textureOptions.min = textureOptions.min || textureOptions.minMag || LINEAR;\n textureOptions.mag = textureOptions.mag || textureOptions.minMag || LINEAR;\n textureOptions.wrapS = textureOptions.wrapS || textureOptions.wrap || CLAMP_TO_EDGE;\n textureOptions.wrapT = textureOptions.wrapT || textureOptions.wrap || CLAMP_TO_EDGE;\n }\n attachment = createTexture(gl, textureOptions);\n }\n }\n if (isRenderbuffer(gl, attachment)) {\n gl.framebufferRenderbuffer(target, attachmentPoint, RENDERBUFFER, attachment);\n } else if (isTexture(gl, attachment)) {\n if (attachmentOptions.layer !== undefined) {\n gl.framebufferTextureLayer(\n target,\n attachmentPoint,\n attachment,\n attachmentOptions.level || 0,\n attachmentOptions.layer);\n } else {\n gl.framebufferTexture2D(\n target,\n attachmentPoint,\n attachmentOptions.target || TEXTURE_2D,\n attachment,\n attachmentOptions.level || 0);\n }\n } else {\n throw new Error('unknown attachment type');\n }\n framebufferInfo.attachments.push(attachment);\n });\n if (gl.drawBuffers) {\n gl.drawBuffers(usedColorAttachmentsPoints);\n }\n return framebufferInfo;\n}\n\n/**\n * Resizes the attachments of a framebuffer.\n *\n * You need to pass in the same `attachments` as you passed in {@link module:twgl.createFramebufferInfo}\n * because TWGL has no idea the format/type of each attachment.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments\n * twgl.resizeFramebufferInfo(gl, fbi);\n * }\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments to match\n * twgl.resizeFramebufferInfo(gl, fbi, attachments);\n * }\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo} framebufferInfo a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * @param {module:twgl.AttachmentOptions[]} [attachments] the same attachments options as passed to {@link module:twgl.createFramebufferInfo}.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @memberOf module:twgl/framebuffers\n */\nfunction resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) {\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n framebufferInfo.width = width;\n framebufferInfo.height = height;\n attachments = attachments || defaultAttachments;\n attachments.forEach(function(attachmentOptions, ndx) {\n const attachment = framebufferInfo.attachments[ndx];\n const format = attachmentOptions.format;\n const samples = attachmentOptions.samples;\n if (samples !== undefined || isRenderbuffer(gl, attachment)) {\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else if (isTexture(gl, attachment)) {\n resizeTexture(gl, attachment, attachmentOptions, width, height);\n } else {\n throw new Error('unknown attachment type');\n }\n });\n}\n\n/**\n * Binds a framebuffer\n *\n * This function pretty much solely exists because I spent hours\n * trying to figure out why something I wrote wasn't working only\n * to realize I forget to set the viewport dimensions.\n * My hope is this function will fix that.\n *\n * It is effectively the same as\n *\n * gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer);\n * gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height);\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo|null} [framebufferInfo] a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * If falsy will bind the canvas.\n * @param {number} [target] The target. If not passed `gl.FRAMEBUFFER` will be used.\n * @memberOf module:twgl/framebuffers\n */\n\nfunction bindFramebufferInfo(gl, framebufferInfo, target) {\n target = target || FRAMEBUFFER;\n if (framebufferInfo) {\n gl.bindFramebuffer(target, framebufferInfo.framebuffer);\n gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height);\n } else {\n gl.bindFramebuffer(target, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n }\n}\n\nvar framebuffers = /*#__PURE__*/Object.freeze({\n __proto__: null,\n bindFramebufferInfo: bindFramebufferInfo,\n createFramebufferInfo: createFramebufferInfo,\n resizeFramebufferInfo: resizeFramebufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * vertex array object related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.attributes` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/vertexArrays\n */\n\nconst ELEMENT_ARRAY_BUFFER = 0x8893;\n\n/**\n * @typedef {Object} VertexArrayInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLVertexArrayObject} [vertexArrayObject] a vertex array object\n * @memberOf module:twgl\n */\n\n/**\n * Creates a VertexArrayInfo from a BufferInfo and one or more ProgramInfos\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * > **IMPORTANT:** Vertex Array Objects are **not** a direct analog for a BufferInfo. Vertex Array Objects\n * assign buffers to specific attributes at creation time. That means they can only be used with programs\n * who's attributes use the same attribute locations for the same purposes.\n *\n * > Bind your attribute locations by passing an array of attribute names to {@link module:twgl.createProgramInfo}\n * or use WebGL 2's GLSL ES 3's `layout(location = )` to make sure locations match.\n *\n * also\n *\n * > **IMPORTANT:** After calling twgl.setBuffersAndAttribute with a BufferInfo that uses a Vertex Array Object\n * that Vertex Array Object will be bound. That means **ANY MANIPULATION OF ELEMENT_ARRAY_BUFFER or ATTRIBUTES**\n * will affect the Vertex Array Object state.\n *\n * > Call `gl.bindVertexArray(null)` to get back manipulating the global attributes and ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.ProgramInfo|module:twgl.ProgramInfo[]} programInfo a programInfo or array of programInfos\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n *\n * You need to make sure every attribute that will be used is bound. So for example assume shader 1\n * uses attributes A, B, C and shader 2 uses attributes A, B, D. If you only pass in the programInfo\n * for shader 1 then only attributes A, B, and C will have their attributes set because TWGL doesn't\n * now attribute D's location.\n *\n * So, you can pass in both shader 1 and shader 2's programInfo\n *\n * @return {module:twgl.VertexArrayInfo} The created VertexArrayInfo\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVertexArrayInfo(gl, programInfos, bufferInfo) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n if (!programInfos.length) {\n programInfos = [programInfos];\n }\n programInfos.forEach(function(programInfo) {\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n });\n gl.bindVertexArray(null);\n return {\n numElements: bufferInfo.numElements,\n elementType: bufferInfo.elementType,\n vertexArrayObject: vao,\n };\n}\n\n/**\n * Creates a vertex array object and then sets the attributes on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} attribs AttribInfos mapped by attribute name.\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOAndSetAttributes(gl, setters, attribs, indices) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n setAttributes(setters, attribs);\n if (indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER, indices);\n }\n // We unbind this because otherwise any change to ELEMENT_ARRAY_BUFFER\n // like when creating buffers for other stuff will mess up this VAO's binding\n gl.bindVertexArray(null);\n return vao;\n}\n\n/**\n * Creates a vertex array object and then sets the attributes\n * on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {Object.| module:twgl.ProgramInfo} programInfo as returned from createProgramInfo or Attribute setters as returned from createAttributeSetters\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOFromBufferInfo(gl, programInfo, bufferInfo) {\n return createVAOAndSetAttributes(gl, programInfo.attribSetters || programInfo, bufferInfo.attribs, bufferInfo.indices);\n}\n\nvar vertexArrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createVertexArrayInfo: createVertexArrayInfo,\n createVAOAndSetAttributes: createVAOAndSetAttributes,\n createVAOFromBufferInfo: createVAOFromBufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults = {\n addExtensionsToContext: true,\n};\n\n/**\n * Various default settings for twgl.\n *\n * Note: You can call this any number of times. Example:\n *\n * twgl.setDefaults({ textureColor: [1, 0, 0, 1] });\n * twgl.setDefaults({ attribPrefix: 'a_' });\n *\n * is equivalent to\n *\n * twgl.setDefaults({\n * textureColor: [1, 0, 0, 1],\n * attribPrefix: 'a_',\n * });\n *\n * @typedef {Object} Defaults\n * @property {string} [attribPrefix] The prefix to stick on attributes\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * const arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * Default: `\"\"`\n *\n * @property {number[]} [textureColor] Array of 4 values in the range 0 to 1\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * Default: `[0.5, 0.75, 1, 1]`\n *\n * @property {string} [crossOrigin]\n *\n * If not undefined sets the crossOrigin attribute on images\n * that twgl creates when downloading images for textures.\n *\n * Also see {@link module:twgl.TextureOptions}.\n *\n * @property {bool} [addExtensionsToContext]\n *\n * If true, then, when twgl will try to add any supported WebGL extensions\n * directly to the context under their normal GL names. For example\n * if ANGLE_instances_arrays exists then twgl would enable it,\n * add the functions `vertexAttribDivisor`, `drawArraysInstanced`,\n * `drawElementsInstanced`, and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR`\n * to the `WebGLRenderingContext`.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets various defaults for twgl.\n *\n * In the interest of terseness which is kind of the point\n * of twgl I've integrated a few of the older functions here\n *\n * @param {module:twgl.Defaults} newDefaults The default settings.\n * @memberOf module:twgl\n */\nfunction setDefaults(newDefaults) {\n copyExistingProperties(newDefaults, defaults);\n setDefaults$2(newDefaults); // eslint-disable-line\n setDefaults$1(newDefaults); // eslint-disable-line\n}\n\nconst prefixRE = /^(.*?)_/;\nfunction addExtensionToContext(gl, extensionName) {\n glEnumToString(gl, 0);\n const ext = gl.getExtension(extensionName);\n if (ext) {\n const enums = {};\n const fnSuffix = prefixRE.exec(extensionName)[1];\n const enumSuffix = '_' + fnSuffix;\n for (const key in ext) {\n const value = ext[key];\n const isFunc = typeof (value) === 'function';\n const suffix = isFunc ? fnSuffix : enumSuffix;\n let name = key;\n // examples of where this is not true are WEBGL_compressed_texture_s3tc\n // and WEBGL_compressed_texture_pvrtc\n if (key.endsWith(suffix)) {\n name = key.substring(0, key.length - suffix.length);\n }\n if (gl[name] !== undefined) {\n if (!isFunc && gl[name] !== value) {\n warn$1(name, gl[name], value, key);\n }\n } else {\n if (isFunc) {\n gl[name] = function(origFn) {\n return function() {\n return origFn.apply(ext, arguments);\n };\n }(value);\n } else {\n gl[name] = value;\n enums[name] = value;\n }\n }\n }\n // pass the modified enums to glEnumToString\n enums.constructor = {\n name: ext.constructor.name,\n };\n glEnumToString(enums, 0);\n }\n return ext;\n}\n\n/*\n * If you're wondering why the code doesn't just iterate\n * over all extensions using `gl.getExtensions` is that it's possible\n * some future extension is incompatible with this code. Rather than\n * have thing suddenly break it seems better to manually add to this\n * list.\n *\n */\nconst supportedExtensions = [\n 'ANGLE_instanced_arrays',\n 'EXT_blend_minmax',\n 'EXT_color_buffer_float',\n 'EXT_color_buffer_half_float',\n 'EXT_disjoint_timer_query',\n 'EXT_disjoint_timer_query_webgl2',\n 'EXT_frag_depth',\n 'EXT_sRGB',\n 'EXT_shader_texture_lod',\n 'EXT_texture_filter_anisotropic',\n 'OES_element_index_uint',\n 'OES_standard_derivatives',\n 'OES_texture_float',\n 'OES_texture_float_linear',\n 'OES_texture_half_float',\n 'OES_texture_half_float_linear',\n 'OES_vertex_array_object',\n 'WEBGL_color_buffer_float',\n 'WEBGL_compressed_texture_atc',\n 'WEBGL_compressed_texture_etc1',\n 'WEBGL_compressed_texture_pvrtc',\n 'WEBGL_compressed_texture_s3tc',\n 'WEBGL_compressed_texture_s3tc_srgb',\n 'WEBGL_depth_texture',\n 'WEBGL_draw_buffers',\n];\n\n/**\n * Attempts to enable all of the following extensions\n * and add their functions and constants to the\n * `WebGLRenderingContext` using their normal non-extension like names.\n *\n * ANGLE_instanced_arrays\n * EXT_blend_minmax\n * EXT_color_buffer_float\n * EXT_color_buffer_half_float\n * EXT_disjoint_timer_query\n * EXT_disjoint_timer_query_webgl2\n * EXT_frag_depth\n * EXT_sRGB\n * EXT_shader_texture_lod\n * EXT_texture_filter_anisotropic\n * OES_element_index_uint\n * OES_standard_derivatives\n * OES_texture_float\n * OES_texture_float_linear\n * OES_texture_half_float\n * OES_texture_half_float_linear\n * OES_vertex_array_object\n * WEBGL_color_buffer_float\n * WEBGL_compressed_texture_atc\n * WEBGL_compressed_texture_etc1\n * WEBGL_compressed_texture_pvrtc\n * WEBGL_compressed_texture_s3tc\n * WEBGL_compressed_texture_s3tc_srgb\n * WEBGL_depth_texture\n * WEBGL_draw_buffers\n *\n * For example if `ANGLE_instanced_arrays` exists then the functions\n * `drawArraysInstanced`, `drawElementsInstanced`, `vertexAttribDivisor`\n * and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR` are added to the\n * `WebGLRenderingContext`.\n *\n * Note that if you want to know if the extension exists you should\n * probably call `gl.getExtension` for each extension. Alternatively\n * you can check for the existence of the functions or constants that\n * are expected to be added. For example\n *\n * if (gl.drawBuffers) {\n * // Either WEBGL_draw_buffers was enabled OR you're running in WebGL2\n * ....\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @memberOf module:twgl\n */\nfunction addExtensionsToContext(gl) {\n for (let ii = 0; ii < supportedExtensions.length; ++ii) {\n addExtensionToContext(gl, supportedExtensions[ii]);\n }\n}\n\n/**\n * Creates a webgl context.\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n * @private\n */\nfunction create3DContext(canvas, opt_attribs) {\n const names = [\"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL1 context.\n *\n * Note: Will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n * @deprecated\n * @private\n */\nfunction getWebGLContext(canvas, opt_attribs) {\n const gl = create3DContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Creates a webgl context.\n *\n * Will return a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * twgl.isWebGL2(gl);\n *\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n */\nfunction createContext(canvas, opt_attribs) {\n const names = [\"webgl2\", \"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL context. Will create a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * function isWebGL2(gl) {\n * return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0 \") == 0;\n * }\n *\n * Note: For a WebGL1 context will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n */\nfunction getContext(canvas, opt_attribs) {\n const gl = createContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Resize a canvas to match the size it's displayed.\n * @param {HTMLCanvasElement} canvas The canvas to resize.\n * @param {number} [multiplier] So you can pass in `window.devicePixelRatio` or other scale value if you want to.\n * @return {boolean} true if the canvas was resized.\n * @memberOf module:twgl\n */\nfunction resizeCanvasToDisplaySize(canvas, multiplier) {\n multiplier = multiplier || 1;\n multiplier = Math.max(0, multiplier);\n const width = canvas.clientWidth * multiplier | 0;\n const height = canvas.clientHeight * multiplier | 0;\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n return true;\n }\n return false;\n}\n\nexport { addExtensionsToContext, attributes, bindFramebufferInfo, bindTransformFeedbackInfo, bindUniformBlock, canFilter, canGenerateMipmap, createAttribsFromArrays, createAttributeSetters, createBufferFromArray, createBufferFromTypedArray, createBufferInfoFromArrays, createBuffersFromArrays, createFramebufferInfo, createProgram, createProgramAsync, createProgramFromScripts, createProgramFromSources, createProgramInfo, createProgramInfoAsync, createProgramInfoFromProgram, createProgramInfos, createProgramInfosAsync, createPrograms, createProgramsAsync, createSampler, createSamplers, createTexture, createTextures, createTransformFeedback, createTransformFeedbackInfo, createUniformBlockInfo, createUniformBlockInfoFromProgram, createUniformBlockSpecFromProgram, createUniformSetters, createVAOAndSetAttributes, createVAOFromBufferInfo, createVertexArrayInfo, draw, drawBufferInfo, drawObjectList, framebuffers, getArray$1 as getArray_, getBytesPerElementForInternalFormat, getContext, getFormatAndTypeForInternalFormat, getGLTypeForTypedArray, getGLTypeForTypedArrayType, getNumComponentsForFormat, getNumComponents$1 as getNumComponents_, getTypedArrayTypeForGLType, getWebGLContext, glEnumToString, isArrayBuffer$1 as isArrayBuffer, isWebGL1, isWebGL2, loadTextureFromUrl, m4, primitives, programs, resizeCanvasToDisplaySize, resizeFramebufferInfo, resizeTexture, setAttribInfoBufferFromArray, setDefaults$2 as setAttributeDefaults_, setAttributePrefix, setAttributes, setBlockUniforms, setBuffersAndAttributes, setDefaultTextureColor, setDefaults, setEmptyTexture, setSamplerParameters, setDefaults$1 as setTextureDefaults_, setTextureFilteringForSize, setTextureFromArray, setTextureFromElement, setTextureParameters, setUniformBlock, setUniforms, setUniformsAndBindTextures, textures, typedarrays, utils, v3, vertexArrays };\n","/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\n\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};","import * as glMatrix from \"./common.js\";\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a the source 4x4 matrix\n * @returns {mat3} out\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\n\nexport var perspective = perspectiveNO;\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\n\nexport var ortho = orthoNO;\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\n * Quaternion\n * @module quat\n */\n\n/**\n * Creates a new identity quat\n *\n * @returns {quat} a new quaternion\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n out[3] = 1;\n return out;\n}\n/**\n * Set a quat to the identity quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\n * Sets a quat from the given angle and rotation axis,\n * then returns it.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyVec3} axis the axis around which to rotate\n * @param {Number} rad the angle in radians\n * @returns {quat} out\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\n * Gets the rotation axis and angle for a given\n * quaternion. If a quaternion is created with\n * setAxisAngle, this method will return the same\n * values as providied in the original parameter list\n * OR functionally equivalent values.\n * Example: The quaternion formed by axis [0, 0, 1] and\n * angle -90 is the same as the quaternion formed by\n * [0, 0, 1] and 270. This method favors the latter.\n * @param {vec3} out_axis Vector receiving the axis of rotation\n * @param {ReadonlyQuat} q Quaternion to be decomposed\n * @return {Number} Angle, in radians, of the rotation\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\n * Gets the angular distance between two unit quaternions\n *\n * @param {ReadonlyQuat} a Origin unit quaternion\n * @param {ReadonlyQuat} b Destination unit quaternion\n * @return {Number} Angle, in radians, between the two quaternions\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\n * Multiplies two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the X axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Y axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Z axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\n * Calculates the W component of a quat from the X, Y, and Z components.\n * Assumes that quaternion is 1 unit in length.\n * Any existing W component will be ignored.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate W component of\n * @returns {quat} out\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\n * Calculate the exponential of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\n * Calculate the natural logarithm of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\n * Calculate the scalar power of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @param {Number} b amount to scale the quaternion by\n * @returns {quat} out\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\n * Performs a spherical linear interpolation between two quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\n * Generates a random unit quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\n * Calculates the inverse of a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate inverse of\n * @returns {quat} out\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\n * Calculates the conjugate of a quat\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate conjugate of\n * @returns {quat} out\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a quaternion from the given 3x3 rotation matrix.\n *\n * NOTE: The resultant quaternion is not normalized, so you should be sure\n * to renormalize the quaternion yourself where necessary.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyMat3} m rotation matrix\n * @returns {quat} out\n * @function\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\n * Creates a quaternion from the given euler angle x, y, z.\n *\n * @param {quat} out the receiving quaternion\n * @param {x} Angle to rotate around X axis in degrees.\n * @param {y} Angle to rotate around Y axis in degrees.\n * @param {z} Angle to rotate around Z axis in degrees.\n * @returns {quat} out\n * @function\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\n * Returns a string representation of a quatenion\n *\n * @param {ReadonlyQuat} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Creates a new quat initialized with values from an existing quaternion\n *\n * @param {ReadonlyQuat} a quaternion to clone\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var clone = vec4.clone;\n/**\n * Creates a new quat initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var fromValues = vec4.fromValues;\n/**\n * Copy the values from one quat to another\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the source quaternion\n * @returns {quat} out\n * @function\n */\n\nexport var copy = vec4.copy;\n/**\n * Set the components of a quat to the given values\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} out\n * @function\n */\n\nexport var set = vec4.set;\n/**\n * Adds two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n * @function\n */\n\nexport var add = vec4.add;\n/**\n * Alias for {@link quat.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Scales a quat by a scalar number\n *\n * @param {quat} out the receiving vector\n * @param {ReadonlyQuat} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {quat} out\n * @function\n */\n\nexport var scale = vec4.scale;\n/**\n * Calculates the dot product of two quat's\n *\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {Number} dot product of a and b\n * @function\n */\n\nexport var dot = vec4.dot;\n/**\n * Performs a linear interpolation between two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n * @function\n */\n\nexport var lerp = vec4.lerp;\n/**\n * Calculates the length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport var length = vec4.length;\n/**\n * Alias for {@link quat.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Calculates the squared length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate squared length of\n * @returns {Number} squared length of a\n * @function\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\n * Alias for {@link quat.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Normalize a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quaternion to normalize\n * @returns {quat} out\n * @function\n */\n\nexport var normalize = vec4.normalize;\n/**\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyQuat} a The first quaternion.\n * @param {ReadonlyQuat} b The second quaternion.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\n * Returns whether or not the quaternions have approximately the same elements in the same position.\n *\n * @param {ReadonlyQuat} a The first vector.\n * @param {ReadonlyQuat} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var equals = vec4.equals;\n/**\n * Sets a quaternion to represent the shortest rotation from one\n * vector to another.\n *\n * Both vectors are assumed to be unit length.\n *\n * @param {quat} out the receiving quaternion.\n * @param {ReadonlyVec3} a the initial vector\n * @param {ReadonlyVec3} b the destination vector\n * @returns {quat} out\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\n * Performs a spherical linear interpolation with two control points\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {ReadonlyQuat} c the third operand\n * @param {ReadonlyQuat} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\n * Sets the specified quaternion with values corresponding to the given\n * axes. Each axis is a vec3 and is expected to be unit length and\n * perpendicular to all other specified axes.\n *\n * @param {ReadonlyVec3} view the vector representing the viewing direction\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\n * @param {ReadonlyVec3} up the vector representing the local \"up\" direction\n * @returns {quat} out\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\n * Math.round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec3} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec3.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\n * Math.round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec4} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec4.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","{\n \"name\": \"gsots3d\",\n \"version\": \"0.0.5-alpha.9\",\n \"description\": \"Getting S**t On The Screen in 3D. A library for doing 3D graphics in the browser.\",\n \"author\": \"Ben Coleman\",\n \"license\": \"MIT\",\n \"homepage\": \"https://code.benco.io/gsots3d/docs\",\n \"type\": \"module\",\n \"publishConfig\": {\n \"@benc-uk:registry\": \"https://npm.pkg.github.com\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/benc-uk/gsots3d.git\"\n },\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./parsers\": \"./dist/parsers/index.js\"\n },\n \"browser\": {\n \".\": \"./dist-single/gsots3d.js\"\n },\n \"files\": [\n \"dist/\",\n \"readme.md\"\n ],\n \"keywords\": [\n \"webgl\",\n \"graphics\",\n \"3d\",\n \"twgl\",\n \"typescript\"\n ],\n \"scripts\": {\n \"lint\": \"eslint --ext .ts src && prettier --check src && prettier --check shaders\",\n \"lint-fix\": \"eslint --ext .ts src --fix && prettier --write src && prettier --write shaders\",\n \"check\": \"tsc\",\n \"build\": \"tsc && tsup\",\n \"watch\": \"tsc && npm run build && run-when-changed --watch 'src/**' --watch 'shaders/**' --exec 'npm run build'\",\n \"build-single\": \"tsc && tsup --config tsup.config-single.js\",\n \"watch-single\": \"tsc && npm run build-single && run-when-changed --watch 'src/**' --watch 'shaders/**' --exec 'npm run build-single'\",\n \"clean\": \"rm -rf dist docs dist-single\",\n \"docs\": \"typedoc --out docs --gitRevision main ./src/\",\n \"examples\": \"vite --port 3000 --host 0.0.0.0 ./examples/\"\n },\n \"devDependencies\": {\n \"@typescript-eslint/eslint-plugin\": \"^7.0.2\",\n \"@typescript-eslint/parser\": \"^7.0.2\",\n \"esbuild-plugin-glsl\": \"^1.2.2\",\n \"eslint\": \"^8.57.0\",\n \"prettier\": \"^3.2.5\",\n \"prettier-plugin-glsl\": \"^0.1.3\",\n \"run-when-changed\": \"^2.1.0\",\n \"tsup\": \"^8.0.2\",\n \"typedoc\": \"^0.25.8\",\n \"typescript\": \"^5.3.3\",\n \"vite\": \"^5.1.4\"\n },\n \"dependencies\": {\n \"cannon-es\": \"^0.20.0\",\n \"gl-matrix\": \"^3.4.3\",\n \"loglevel\": \"^1.9.1\",\n \"twgl.js\": \"^5.5.3\"\n }\n}\n","/**\n * Records what objects are colliding with each other\n */\nclass ObjectCollisionMatrix {\n /**\n * The matrix storage.\n */\n\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n this.matrix = {};\n }\n /**\n * get\n */\n\n\n get(bi, bj) {\n let {\n id: i\n } = bi;\n let {\n id: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return `${i}-${j}` in this.matrix;\n }\n /**\n * set\n */\n\n\n set(bi, bj, value) {\n let {\n id: i\n } = bi;\n let {\n id: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n if (value) {\n this.matrix[`${i}-${j}`] = true;\n } else {\n delete this.matrix[`${i}-${j}`];\n }\n }\n /**\n * Empty the matrix\n */\n\n\n reset() {\n this.matrix = {};\n }\n /**\n * Set max number of objects\n */\n\n\n setNumObjects(n) {}\n\n}\n\n/**\n * A 3x3 matrix.\n * Authored by {@link http://github.com/schteppe/ schteppe}\n */\nclass Mat3 {\n /**\n * A vector of length 9, containing all matrix elements.\n */\n\n /**\n * @param elements A vector of length 9, containing all matrix elements.\n */\n constructor(elements) {\n if (elements === void 0) {\n elements = [0, 0, 0, 0, 0, 0, 0, 0, 0];\n }\n\n this.elements = elements;\n }\n /**\n * Sets the matrix to identity\n * @todo Should perhaps be renamed to `setIdentity()` to be more clear.\n * @todo Create another function that immediately creates an identity matrix eg. `eye()`\n */\n\n\n identity() {\n const e = this.elements;\n e[0] = 1;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 1;\n e[5] = 0;\n e[6] = 0;\n e[7] = 0;\n e[8] = 1;\n }\n /**\n * Set all elements to zero\n */\n\n\n setZero() {\n const e = this.elements;\n e[0] = 0;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = 0;\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n }\n /**\n * Sets the matrix diagonal elements from a Vec3\n */\n\n\n setTrace(vector) {\n const e = this.elements;\n e[0] = vector.x;\n e[4] = vector.y;\n e[8] = vector.z;\n }\n /**\n * Gets the matrix diagonal elements\n */\n\n\n getTrace(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const e = this.elements;\n target.x = e[0];\n target.y = e[4];\n target.z = e[8];\n return target;\n }\n /**\n * Matrix-Vector multiplication\n * @param v The vector to multiply with\n * @param target Optional, target to save the result in.\n */\n\n\n vmult(v, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const e = this.elements;\n const x = v.x;\n const y = v.y;\n const z = v.z;\n target.x = e[0] * x + e[1] * y + e[2] * z;\n target.y = e[3] * x + e[4] * y + e[5] * z;\n target.z = e[6] * x + e[7] * y + e[8] * z;\n return target;\n }\n /**\n * Matrix-scalar multiplication\n */\n\n\n smult(s) {\n for (let i = 0; i < this.elements.length; i++) {\n this.elements[i] *= s;\n }\n }\n /**\n * Matrix multiplication\n * @param matrix Matrix to multiply with from left side.\n */\n\n\n mmult(matrix, target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const A = this.elements;\n const B = matrix.elements;\n const T = target.elements;\n const a11 = A[0],\n a12 = A[1],\n a13 = A[2],\n a21 = A[3],\n a22 = A[4],\n a23 = A[5],\n a31 = A[6],\n a32 = A[7],\n a33 = A[8];\n const b11 = B[0],\n b12 = B[1],\n b13 = B[2],\n b21 = B[3],\n b22 = B[4],\n b23 = B[5],\n b31 = B[6],\n b32 = B[7],\n b33 = B[8];\n T[0] = a11 * b11 + a12 * b21 + a13 * b31;\n T[1] = a11 * b12 + a12 * b22 + a13 * b32;\n T[2] = a11 * b13 + a12 * b23 + a13 * b33;\n T[3] = a21 * b11 + a22 * b21 + a23 * b31;\n T[4] = a21 * b12 + a22 * b22 + a23 * b32;\n T[5] = a21 * b13 + a22 * b23 + a23 * b33;\n T[6] = a31 * b11 + a32 * b21 + a33 * b31;\n T[7] = a31 * b12 + a32 * b22 + a33 * b32;\n T[8] = a31 * b13 + a32 * b23 + a33 * b33;\n return target;\n }\n /**\n * Scale each column of the matrix\n */\n\n\n scale(vector, target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const e = this.elements;\n const t = target.elements;\n\n for (let i = 0; i !== 3; i++) {\n t[3 * i + 0] = vector.x * e[3 * i + 0];\n t[3 * i + 1] = vector.y * e[3 * i + 1];\n t[3 * i + 2] = vector.z * e[3 * i + 2];\n }\n\n return target;\n }\n /**\n * Solve Ax=b\n * @param b The right hand side\n * @param target Optional. Target vector to save in.\n * @return The solution x\n * @todo should reuse arrays\n */\n\n\n solve(b, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n // Construct equations\n const nr = 3; // num rows\n\n const nc = 4; // num cols\n\n const eqns = [];\n let i;\n let j;\n\n for (i = 0; i < nr * nc; i++) {\n eqns.push(0);\n }\n\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n eqns[i + nc * j] = this.elements[i + 3 * j];\n }\n }\n\n eqns[3 + 4 * 0] = b.x;\n eqns[3 + 4 * 1] = b.y;\n eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination\n\n let n = 3;\n const k = n;\n let np;\n const kp = 4; // num rows\n\n let p;\n\n do {\n i = k - n;\n\n if (eqns[i + nc * i] === 0) {\n // the pivot is null, swap lines\n for (j = i + 1; j < k; j++) {\n if (eqns[i + nc * j] !== 0) {\n np = kp;\n\n do {\n // do ligne( i ) = ligne( i ) + ligne( k )\n p = kp - np;\n eqns[p + nc * i] += eqns[p + nc * j];\n } while (--np);\n\n break;\n }\n }\n }\n\n if (eqns[i + nc * i] !== 0) {\n for (j = i + 1; j < k; j++) {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = kp;\n\n do {\n // do ligne( k ) = ligne( k ) - multiplier * ligne( i )\n p = kp - np;\n eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n }\n }\n } while (--n); // Get the solution\n\n\n target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];\n target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];\n target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];\n\n if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {\n throw `Could not solve equation! Got x=[${target.toString()}], b=[${b.toString()}], A=[${this.toString()}]`;\n }\n\n return target;\n }\n /**\n * Get an element in the matrix by index. Index starts at 0, not 1!!!\n * @param value If provided, the matrix element will be set to this value.\n */\n\n\n e(row, column, value) {\n if (value === undefined) {\n return this.elements[column + 3 * row];\n } else {\n // Set value\n this.elements[column + 3 * row] = value;\n }\n }\n /**\n * Copy another matrix into this matrix object.\n */\n\n\n copy(matrix) {\n for (let i = 0; i < matrix.elements.length; i++) {\n this.elements[i] = matrix.elements[i];\n }\n\n return this;\n }\n /**\n * Returns a string representation of the matrix.\n */\n\n\n toString() {\n let r = '';\n const sep = ',';\n\n for (let i = 0; i < 9; i++) {\n r += this.elements[i] + sep;\n }\n\n return r;\n }\n /**\n * reverse the matrix\n * @param target Target matrix to save in.\n * @return The solution x\n */\n\n\n reverse(target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n // Construct equations\n const nr = 3; // num rows\n\n const nc = 6; // num cols\n\n const eqns = reverse_eqns;\n let i;\n let j;\n\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n eqns[i + nc * j] = this.elements[i + 3 * j];\n }\n }\n\n eqns[3 + 6 * 0] = 1;\n eqns[3 + 6 * 1] = 0;\n eqns[3 + 6 * 2] = 0;\n eqns[4 + 6 * 0] = 0;\n eqns[4 + 6 * 1] = 1;\n eqns[4 + 6 * 2] = 0;\n eqns[5 + 6 * 0] = 0;\n eqns[5 + 6 * 1] = 0;\n eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination\n\n let n = 3;\n const k = n;\n let np;\n const kp = nc; // num rows\n\n let p;\n\n do {\n i = k - n;\n\n if (eqns[i + nc * i] === 0) {\n // the pivot is null, swap lines\n for (j = i + 1; j < k; j++) {\n if (eqns[i + nc * j] !== 0) {\n np = kp;\n\n do {\n // do line( i ) = line( i ) + line( k )\n p = kp - np;\n eqns[p + nc * i] += eqns[p + nc * j];\n } while (--np);\n\n break;\n }\n }\n }\n\n if (eqns[i + nc * i] !== 0) {\n for (j = i + 1; j < k; j++) {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = kp;\n\n do {\n // do line( k ) = line( k ) - multiplier * line( i )\n p = kp - np;\n eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n }\n }\n } while (--n); // eliminate the upper left triangle of the matrix\n\n\n i = 2;\n\n do {\n j = i - 1;\n\n do {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = nc;\n\n do {\n p = nc - np;\n eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n } while (j--);\n } while (--i); // operations on the diagonal\n\n\n i = 2;\n\n do {\n const multiplier = 1 / eqns[i + nc * i];\n np = nc;\n\n do {\n p = nc - np;\n eqns[p + nc * i] = eqns[p + nc * i] * multiplier;\n } while (--np);\n } while (i--);\n\n i = 2;\n\n do {\n j = 2;\n\n do {\n p = eqns[nr + j + nc * i];\n\n if (isNaN(p) || p === Infinity) {\n throw `Could not reverse! A=[${this.toString()}]`;\n }\n\n target.e(i, j, p);\n } while (j--);\n } while (i--);\n\n return target;\n }\n /**\n * Set the matrix from a quaterion\n */\n\n\n setRotationFromQuaternion(q) {\n const x = q.x;\n const y = q.y;\n const z = q.z;\n const w = q.w;\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const e = this.elements;\n e[3 * 0 + 0] = 1 - (yy + zz);\n e[3 * 0 + 1] = xy - wz;\n e[3 * 0 + 2] = xz + wy;\n e[3 * 1 + 0] = xy + wz;\n e[3 * 1 + 1] = 1 - (xx + zz);\n e[3 * 1 + 2] = yz - wx;\n e[3 * 2 + 0] = xz - wy;\n e[3 * 2 + 1] = yz + wx;\n e[3 * 2 + 2] = 1 - (xx + yy);\n return this;\n }\n /**\n * Transpose the matrix\n * @param target Optional. Where to store the result.\n * @return The target Mat3, or a new Mat3 if target was omitted.\n */\n\n\n transpose(target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const M = this.elements;\n const T = target.elements;\n let tmp; //Set diagonals\n\n T[0] = M[0];\n T[4] = M[4];\n T[8] = M[8];\n tmp = M[1];\n T[1] = M[3];\n T[3] = tmp;\n tmp = M[2];\n T[2] = M[6];\n T[6] = tmp;\n tmp = M[5];\n T[5] = M[7];\n T[7] = tmp;\n return target;\n }\n\n}\nconst reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n/**\n * 3-dimensional vector\n * @example\n * const v = new Vec3(1, 2, 3)\n * console.log('x=' + v.x) // x=1\n */\n\nclass Vec3 {\n constructor(x, y, z) {\n if (x === void 0) {\n x = 0.0;\n }\n\n if (y === void 0) {\n y = 0.0;\n }\n\n if (z === void 0) {\n z = 0.0;\n }\n\n this.x = x;\n this.y = y;\n this.z = z;\n }\n /**\n * Vector cross product\n * @param target Optional target to save in.\n */\n\n\n cross(vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const vx = vector.x;\n const vy = vector.y;\n const vz = vector.z;\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = y * vz - z * vy;\n target.y = z * vx - x * vz;\n target.z = x * vy - y * vx;\n return target;\n }\n /**\n * Set the vectors' 3 elements\n */\n\n\n set(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n /**\n * Set all components of the vector to zero.\n */\n\n\n setZero() {\n this.x = this.y = this.z = 0;\n }\n /**\n * Vector addition\n */\n\n\n vadd(vector, target) {\n if (target) {\n target.x = vector.x + this.x;\n target.y = vector.y + this.y;\n target.z = vector.z + this.z;\n } else {\n return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);\n }\n }\n /**\n * Vector subtraction\n * @param target Optional target to save in.\n */\n\n\n vsub(vector, target) {\n if (target) {\n target.x = this.x - vector.x;\n target.y = this.y - vector.y;\n target.z = this.z - vector.z;\n } else {\n return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);\n }\n }\n /**\n * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c\n *\n * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}\n */\n\n\n crossmat() {\n return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);\n }\n /**\n * Normalize the vector. Note that this changes the values in the vector.\n * @return Returns the norm of the vector\n */\n\n\n normalize() {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const n = Math.sqrt(x * x + y * y + z * z);\n\n if (n > 0.0) {\n const invN = 1 / n;\n this.x *= invN;\n this.y *= invN;\n this.z *= invN;\n } else {\n // Make something up\n this.x = 0;\n this.y = 0;\n this.z = 0;\n }\n\n return n;\n }\n /**\n * Get the version of this vector that is of length 1.\n * @param target Optional target to save in\n * @return Returns the unit vector\n */\n\n\n unit(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n let ninv = Math.sqrt(x * x + y * y + z * z);\n\n if (ninv > 0.0) {\n ninv = 1.0 / ninv;\n target.x = x * ninv;\n target.y = y * ninv;\n target.z = z * ninv;\n } else {\n target.x = 1;\n target.y = 0;\n target.z = 0;\n }\n\n return target;\n }\n /**\n * Get the length of the vector\n */\n\n\n length() {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n return Math.sqrt(x * x + y * y + z * z);\n }\n /**\n * Get the squared length of the vector.\n */\n\n\n lengthSquared() {\n return this.dot(this);\n }\n /**\n * Get distance from this point to another point\n */\n\n\n distanceTo(p) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const px = p.x;\n const py = p.y;\n const pz = p.z;\n return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));\n }\n /**\n * Get squared distance from this point to another point\n */\n\n\n distanceSquared(p) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const px = p.x;\n const py = p.y;\n const pz = p.z;\n return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);\n }\n /**\n * Multiply all the components of the vector with a scalar.\n * @param target The vector to save the result in.\n */\n\n\n scale(scalar, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = scalar * x;\n target.y = scalar * y;\n target.z = scalar * z;\n return target;\n }\n /**\n * Multiply the vector with an other vector, component-wise.\n * @param target The vector to save the result in.\n */\n\n\n vmul(vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = vector.x * this.x;\n target.y = vector.y * this.y;\n target.z = vector.z * this.z;\n return target;\n }\n /**\n * Scale a vector and add it to this vector. Save the result in \"target\". (target = this + vector * scalar)\n * @param target The vector to save the result in.\n */\n\n\n addScaledVector(scalar, vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = this.x + scalar * vector.x;\n target.y = this.y + scalar * vector.y;\n target.z = this.z + scalar * vector.z;\n return target;\n }\n /**\n * Calculate dot product\n * @param vector\n */\n\n\n dot(vector) {\n return this.x * vector.x + this.y * vector.y + this.z * vector.z;\n }\n\n isZero() {\n return this.x === 0 && this.y === 0 && this.z === 0;\n }\n /**\n * Make the vector point in the opposite direction.\n * @param target Optional target to save in\n */\n\n\n negate(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = -this.x;\n target.y = -this.y;\n target.z = -this.z;\n return target;\n }\n /**\n * Compute two artificial tangents to the vector\n * @param t1 Vector object to save the first tangent in\n * @param t2 Vector object to save the second tangent in\n */\n\n\n tangents(t1, t2) {\n const norm = this.length();\n\n if (norm > 0.0) {\n const n = Vec3_tangents_n;\n const inorm = 1 / norm;\n n.set(this.x * inorm, this.y * inorm, this.z * inorm);\n const randVec = Vec3_tangents_randVec;\n\n if (Math.abs(n.x) < 0.9) {\n randVec.set(1, 0, 0);\n n.cross(randVec, t1);\n } else {\n randVec.set(0, 1, 0);\n n.cross(randVec, t1);\n }\n\n n.cross(t1, t2);\n } else {\n // The normal length is zero, make something up\n t1.set(1, 0, 0);\n t2.set(0, 1, 0);\n }\n }\n /**\n * Converts to a more readable format\n */\n\n\n toString() {\n return `${this.x},${this.y},${this.z}`;\n }\n /**\n * Converts to an array\n */\n\n\n toArray() {\n return [this.x, this.y, this.z];\n }\n /**\n * Copies value of source to this vector.\n */\n\n\n copy(vector) {\n this.x = vector.x;\n this.y = vector.y;\n this.z = vector.z;\n return this;\n }\n /**\n * Do a linear interpolation between two vectors\n * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.\n */\n\n\n lerp(vector, t, target) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = x + (vector.x - x) * t;\n target.y = y + (vector.y - y) * t;\n target.z = z + (vector.z - z) * t;\n }\n /**\n * Check if a vector equals is almost equal to another one.\n */\n\n\n almostEquals(vector, precision) {\n if (precision === void 0) {\n precision = 1e-6;\n }\n\n if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {\n return false;\n }\n\n return true;\n }\n /**\n * Check if a vector is almost zero\n */\n\n\n almostZero(precision) {\n if (precision === void 0) {\n precision = 1e-6;\n }\n\n if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {\n return false;\n }\n\n return true;\n }\n /**\n * Check if the vector is anti-parallel to another vector.\n * @param precision Set to zero for exact comparisons\n */\n\n\n isAntiparallelTo(vector, precision) {\n this.negate(antip_neg);\n return antip_neg.almostEquals(vector, precision);\n }\n /**\n * Clone the vector\n */\n\n\n clone() {\n return new Vec3(this.x, this.y, this.z);\n }\n\n}\nVec3.ZERO = new Vec3(0, 0, 0);\nVec3.UNIT_X = new Vec3(1, 0, 0);\nVec3.UNIT_Y = new Vec3(0, 1, 0);\nVec3.UNIT_Z = new Vec3(0, 0, 1);\nconst Vec3_tangents_n = new Vec3();\nconst Vec3_tangents_randVec = new Vec3();\nconst antip_neg = new Vec3();\n\n/**\n * Axis aligned bounding box class.\n */\nclass AABB {\n /**\n * The lower bound of the bounding box\n */\n\n /**\n * The upper bound of the bounding box\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.lowerBound = new Vec3();\n this.upperBound = new Vec3();\n\n if (options.lowerBound) {\n this.lowerBound.copy(options.lowerBound);\n }\n\n if (options.upperBound) {\n this.upperBound.copy(options.upperBound);\n }\n }\n /**\n * Set the AABB bounds from a set of points.\n * @param points An array of Vec3's.\n * @return The self object\n */\n\n\n setFromPoints(points, position, quaternion, skinSize) {\n const l = this.lowerBound;\n const u = this.upperBound;\n const q = quaternion; // Set to the first point\n\n l.copy(points[0]);\n\n if (q) {\n q.vmult(l, l);\n }\n\n u.copy(l);\n\n for (let i = 1; i < points.length; i++) {\n let p = points[i];\n\n if (q) {\n q.vmult(p, tmp$1);\n p = tmp$1;\n }\n\n if (p.x > u.x) {\n u.x = p.x;\n }\n\n if (p.x < l.x) {\n l.x = p.x;\n }\n\n if (p.y > u.y) {\n u.y = p.y;\n }\n\n if (p.y < l.y) {\n l.y = p.y;\n }\n\n if (p.z > u.z) {\n u.z = p.z;\n }\n\n if (p.z < l.z) {\n l.z = p.z;\n }\n } // Add offset\n\n\n if (position) {\n position.vadd(l, l);\n position.vadd(u, u);\n }\n\n if (skinSize) {\n l.x -= skinSize;\n l.y -= skinSize;\n l.z -= skinSize;\n u.x += skinSize;\n u.y += skinSize;\n u.z += skinSize;\n }\n\n return this;\n }\n /**\n * Copy bounds from an AABB to this AABB\n * @param aabb Source to copy from\n * @return The this object, for chainability\n */\n\n\n copy(aabb) {\n this.lowerBound.copy(aabb.lowerBound);\n this.upperBound.copy(aabb.upperBound);\n return this;\n }\n /**\n * Clone an AABB\n */\n\n\n clone() {\n return new AABB().copy(this);\n }\n /**\n * Extend this AABB so that it covers the given AABB too.\n */\n\n\n extend(aabb) {\n this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);\n this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);\n this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);\n this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);\n this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);\n this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);\n }\n /**\n * Returns true if the given AABB overlaps this AABB.\n */\n\n\n overlaps(aabb) {\n const l1 = this.lowerBound;\n const u1 = this.upperBound;\n const l2 = aabb.lowerBound;\n const u2 = aabb.upperBound; // l2 u2\n // |---------|\n // |--------|\n // l1 u1\n\n const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;\n const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;\n const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;\n return overlapsX && overlapsY && overlapsZ;\n } // Mostly for debugging\n\n\n volume() {\n const l = this.lowerBound;\n const u = this.upperBound;\n return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);\n }\n /**\n * Returns true if the given AABB is fully contained in this AABB.\n */\n\n\n contains(aabb) {\n const l1 = this.lowerBound;\n const u1 = this.upperBound;\n const l2 = aabb.lowerBound;\n const u2 = aabb.upperBound; // l2 u2\n // |---------|\n // |---------------|\n // l1 u1\n\n return l1.x <= l2.x && u1.x >= u2.x && l1.y <= l2.y && u1.y >= u2.y && l1.z <= l2.z && u1.z >= u2.z;\n }\n\n getCorners(a, b, c, d, e, f, g, h) {\n const l = this.lowerBound;\n const u = this.upperBound;\n a.copy(l);\n b.set(u.x, l.y, l.z);\n c.set(u.x, u.y, l.z);\n d.set(l.x, u.y, u.z);\n e.set(u.x, l.y, u.z);\n f.set(l.x, u.y, l.z);\n g.set(l.x, l.y, u.z);\n h.copy(u);\n }\n /**\n * Get the representation of an AABB in another frame.\n * @return The \"target\" AABB object.\n */\n\n\n toLocalFrame(frame, target) {\n const corners = transformIntoFrame_corners;\n const a = corners[0];\n const b = corners[1];\n const c = corners[2];\n const d = corners[3];\n const e = corners[4];\n const f = corners[5];\n const g = corners[6];\n const h = corners[7]; // Get corners in current frame\n\n this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame\n\n for (let i = 0; i !== 8; i++) {\n const corner = corners[i];\n frame.pointToLocal(corner, corner);\n }\n\n return target.setFromPoints(corners);\n }\n /**\n * Get the representation of an AABB in the global frame.\n * @return The \"target\" AABB object.\n */\n\n\n toWorldFrame(frame, target) {\n const corners = transformIntoFrame_corners;\n const a = corners[0];\n const b = corners[1];\n const c = corners[2];\n const d = corners[3];\n const e = corners[4];\n const f = corners[5];\n const g = corners[6];\n const h = corners[7]; // Get corners in current frame\n\n this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame\n\n for (let i = 0; i !== 8; i++) {\n const corner = corners[i];\n frame.pointToWorld(corner, corner);\n }\n\n return target.setFromPoints(corners);\n }\n /**\n * Check if the AABB is hit by a ray.\n */\n\n\n overlapsRay(ray) {\n const {\n direction,\n from\n } = ray; // const t = 0\n // ray.direction is unit direction vector of ray\n\n const dirFracX = 1 / direction.x;\n const dirFracY = 1 / direction.y;\n const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner\n\n const t1 = (this.lowerBound.x - from.x) * dirFracX;\n const t2 = (this.upperBound.x - from.x) * dirFracX;\n const t3 = (this.lowerBound.y - from.y) * dirFracY;\n const t4 = (this.upperBound.y - from.y) * dirFracY;\n const t5 = (this.lowerBound.z - from.z) * dirFracZ;\n const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));\n // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));\n\n const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));\n const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us\n\n if (tmax < 0) {\n //t = tmax;\n return false;\n } // if tmin > tmax, ray doesn't intersect AABB\n\n\n if (tmin > tmax) {\n //t = tmax;\n return false;\n }\n\n return true;\n }\n\n}\nconst tmp$1 = new Vec3();\nconst transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\n\n/**\n * Collision \"matrix\".\n * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step\n */\nclass ArrayCollisionMatrix {\n /**\n * The matrix storage.\n */\n constructor() {\n this.matrix = [];\n }\n /**\n * Get an element\n */\n\n\n get(bi, bj) {\n let {\n index: i\n } = bi;\n let {\n index: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return this.matrix[(i * (i + 1) >> 1) + j - 1];\n }\n /**\n * Set an element\n */\n\n\n set(bi, bj, value) {\n let {\n index: i\n } = bi;\n let {\n index: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;\n }\n /**\n * Sets all elements to zero\n */\n\n\n reset() {\n for (let i = 0, l = this.matrix.length; i !== l; i++) {\n this.matrix[i] = 0;\n }\n }\n /**\n * Sets the max number of objects\n */\n\n\n setNumObjects(n) {\n this.matrix.length = n * (n - 1) >> 1;\n }\n\n}\n\n/**\n * Base class for objects that dispatches events.\n */\nclass EventTarget {\n /**\n * Add an event listener\n * @return The self object, for chainability.\n */\n addEventListener(type, listener) {\n if (this._listeners === undefined) {\n this._listeners = {};\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] === undefined) {\n listeners[type] = [];\n }\n\n if (!listeners[type].includes(listener)) {\n listeners[type].push(listener);\n }\n\n return this;\n }\n /**\n * Check if an event listener is added\n */\n\n\n hasEventListener(type, listener) {\n if (this._listeners === undefined) {\n return false;\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] !== undefined && listeners[type].includes(listener)) {\n return true;\n }\n\n return false;\n }\n /**\n * Check if any event listener of the given type is added\n */\n\n\n hasAnyEventListener(type) {\n if (this._listeners === undefined) {\n return false;\n }\n\n const listeners = this._listeners;\n return listeners[type] !== undefined;\n }\n /**\n * Remove an event listener\n * @return The self object, for chainability.\n */\n\n\n removeEventListener(type, listener) {\n if (this._listeners === undefined) {\n return this;\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] === undefined) {\n return this;\n }\n\n const index = listeners[type].indexOf(listener);\n\n if (index !== -1) {\n listeners[type].splice(index, 1);\n }\n\n return this;\n }\n /**\n * Emit an event.\n * @return The self object, for chainability.\n */\n\n\n dispatchEvent(event) {\n if (this._listeners === undefined) {\n return this;\n }\n\n const listeners = this._listeners;\n const listenerArray = listeners[event.type];\n\n if (listenerArray !== undefined) {\n event.target = this;\n\n for (let i = 0, l = listenerArray.length; i < l; i++) {\n listenerArray[i].call(this, event);\n }\n }\n\n return this;\n }\n\n}\n\n/**\n * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.\n * @param x Multiplier of the imaginary basis vector i.\n * @param y Multiplier of the imaginary basis vector j.\n * @param z Multiplier of the imaginary basis vector k.\n * @param w Multiplier of the real part.\n * @see http://en.wikipedia.org/wiki/Quaternion\n */\n\nclass Quaternion {\n constructor(x, y, z, w) {\n if (x === void 0) {\n x = 0;\n }\n\n if (y === void 0) {\n y = 0;\n }\n\n if (z === void 0) {\n z = 0;\n }\n\n if (w === void 0) {\n w = 1;\n }\n\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Set the value of the quaternion.\n */\n\n\n set(x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n }\n /**\n * Convert to a readable format\n * @return \"x,y,z,w\"\n */\n\n\n toString() {\n return `${this.x},${this.y},${this.z},${this.w}`;\n }\n /**\n * Convert to an Array\n * @return [x, y, z, w]\n */\n\n\n toArray() {\n return [this.x, this.y, this.z, this.w];\n }\n /**\n * Set the quaternion components given an axis and an angle in radians.\n */\n\n\n setFromAxisAngle(vector, angle) {\n const s = Math.sin(angle * 0.5);\n this.x = vector.x * s;\n this.y = vector.y * s;\n this.z = vector.z * s;\n this.w = Math.cos(angle * 0.5);\n return this;\n }\n /**\n * Converts the quaternion to [ axis, angle ] representation.\n * @param targetAxis A vector object to reuse for storing the axis.\n * @return An array, first element is the axis and the second is the angle in radians.\n */\n\n\n toAxisAngle(targetAxis) {\n if (targetAxis === void 0) {\n targetAxis = new Vec3();\n }\n\n this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised\n\n const angle = 2 * Math.acos(this.w);\n const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.\n\n if (s < 0.001) {\n // test to avoid divide by zero, s is always positive due to sqrt\n // if s close to zero then direction of axis not important\n targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;\n\n targetAxis.y = this.y;\n targetAxis.z = this.z;\n } else {\n targetAxis.x = this.x / s; // normalise axis\n\n targetAxis.y = this.y / s;\n targetAxis.z = this.z / s;\n }\n\n return [targetAxis, angle];\n }\n /**\n * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.\n */\n\n\n setFromVectors(u, v) {\n if (u.isAntiparallelTo(v)) {\n const t1 = sfv_t1;\n const t2 = sfv_t2;\n u.tangents(t1, t2);\n this.setFromAxisAngle(t1, Math.PI);\n } else {\n const a = u.cross(v);\n this.x = a.x;\n this.y = a.y;\n this.z = a.z;\n this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);\n this.normalize();\n }\n\n return this;\n }\n /**\n * Multiply the quaternion with an other quaternion.\n */\n\n\n mult(quat, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = this.x;\n const ay = this.y;\n const az = this.z;\n const aw = this.w;\n const bx = quat.x;\n const by = quat.y;\n const bz = quat.z;\n const bw = quat.w;\n target.x = ax * bw + aw * bx + ay * bz - az * by;\n target.y = ay * bw + aw * by + az * bx - ax * bz;\n target.z = az * bw + aw * bz + ax * by - ay * bx;\n target.w = aw * bw - ax * bx - ay * by - az * bz;\n return target;\n }\n /**\n * Get the inverse quaternion rotation.\n */\n\n\n inverse(target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const w = this.w;\n this.conjugate(target);\n const inorm2 = 1 / (x * x + y * y + z * z + w * w);\n target.x *= inorm2;\n target.y *= inorm2;\n target.z *= inorm2;\n target.w *= inorm2;\n return target;\n }\n /**\n * Get the quaternion conjugate\n */\n\n\n conjugate(target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n target.x = -this.x;\n target.y = -this.y;\n target.z = -this.z;\n target.w = this.w;\n return target;\n }\n /**\n * Normalize the quaternion. Note that this changes the values of the quaternion.\n */\n\n\n normalize() {\n let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n\n if (l === 0) {\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n } else {\n l = 1 / l;\n this.x *= l;\n this.y *= l;\n this.z *= l;\n this.w *= l;\n }\n\n return this;\n }\n /**\n * Approximation of quaternion normalization. Works best when quat is already almost-normalized.\n * @author unphased, https://github.com/unphased\n */\n\n\n normalizeFast() {\n const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;\n\n if (f === 0) {\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n } else {\n this.x *= f;\n this.y *= f;\n this.z *= f;\n this.w *= f;\n }\n\n return this;\n }\n /**\n * Multiply the quaternion by a vector\n */\n\n\n vmult(v, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = v.x;\n const y = v.y;\n const z = v.z;\n const qx = this.x;\n const qy = this.y;\n const qz = this.z;\n const qw = this.w; // q*v\n\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = -qx * x - qy * y - qz * z;\n target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n return target;\n }\n /**\n * Copies value of source to this quaternion.\n * @return this\n */\n\n\n copy(quat) {\n this.x = quat.x;\n this.y = quat.y;\n this.z = quat.z;\n this.w = quat.w;\n return this;\n }\n /**\n * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm\n * @param order Three-character string, defaults to \"YZX\"\n */\n\n\n toEuler(target, order) {\n if (order === void 0) {\n order = 'YZX';\n }\n\n let heading;\n let attitude;\n let bank;\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const w = this.w;\n\n switch (order) {\n case 'YZX':\n const test = x * y + z * w;\n\n if (test > 0.499) {\n // singularity at north pole\n heading = 2 * Math.atan2(x, w);\n attitude = Math.PI / 2;\n bank = 0;\n }\n\n if (test < -0.499) {\n // singularity at south pole\n heading = -2 * Math.atan2(x, w);\n attitude = -Math.PI / 2;\n bank = 0;\n }\n\n if (heading === undefined) {\n const sqx = x * x;\n const sqy = y * y;\n const sqz = z * z;\n heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading\n\n attitude = Math.asin(2 * test); // attitude\n\n bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank\n }\n\n break;\n\n default:\n throw new Error(`Euler order ${order} not supported yet.`);\n }\n\n target.y = heading;\n target.z = attitude;\n target.x = bank;\n }\n /**\n * Set the quaternion components given Euler angle representation.\n *\n * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.\n *\n * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference\n */\n\n\n setFromEuler(x, y, z, order) {\n if (order === void 0) {\n order = 'XYZ';\n }\n\n const c1 = Math.cos(x / 2);\n const c2 = Math.cos(y / 2);\n const c3 = Math.cos(z / 2);\n const s1 = Math.sin(x / 2);\n const s2 = Math.sin(y / 2);\n const s3 = Math.sin(z / 2);\n\n if (order === 'XYZ') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'YXZ') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n } else if (order === 'ZXY') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'ZYX') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n } else if (order === 'YZX') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'XZY') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n }\n\n return this;\n }\n\n clone() {\n return new Quaternion(this.x, this.y, this.z, this.w);\n }\n /**\n * Performs a spherical linear interpolation between two quat\n *\n * @param toQuat second operand\n * @param t interpolation amount between the self quaternion and toQuat\n * @param target A quaternion to store the result in. If not provided, a new one will be created.\n * @returns {Quaternion} The \"target\" object\n */\n\n\n slerp(toQuat, t, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = this.x;\n const ay = this.y;\n const az = this.z;\n const aw = this.w;\n let bx = toQuat.x;\n let by = toQuat.y;\n let bz = toQuat.z;\n let bw = toQuat.w;\n let omega;\n let cosom;\n let sinom;\n let scale0;\n let scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > 0.000001) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n target.x = scale0 * ax + scale1 * bx;\n target.y = scale0 * ay + scale1 * by;\n target.z = scale0 * az + scale1 * bz;\n target.w = scale0 * aw + scale1 * bw;\n return target;\n }\n /**\n * Rotate an absolute orientation quaternion given an angular velocity and a time step.\n */\n\n\n integrate(angularVelocity, dt, angularFactor, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = angularVelocity.x * angularFactor.x,\n ay = angularVelocity.y * angularFactor.y,\n az = angularVelocity.z * angularFactor.z,\n bx = this.x,\n by = this.y,\n bz = this.z,\n bw = this.w;\n const half_dt = dt * 0.5;\n target.x += half_dt * (ax * bw + ay * bz - az * by);\n target.y += half_dt * (ay * bw + az * bx - ax * bz);\n target.z += half_dt * (az * bw + ax * by - ay * bx);\n target.w += half_dt * (-ax * bx - ay * by - az * bz);\n return target;\n }\n\n}\nconst sfv_t1 = new Vec3();\nconst sfv_t2 = new Vec3();\n\n/**\n * The available shape types.\n */\nconst SHAPE_TYPES = {\n /** SPHERE */\n SPHERE: 1,\n\n /** PLANE */\n PLANE: 2,\n\n /** BOX */\n BOX: 4,\n\n /** COMPOUND */\n COMPOUND: 8,\n\n /** CONVEXPOLYHEDRON */\n CONVEXPOLYHEDRON: 16,\n\n /** HEIGHTFIELD */\n HEIGHTFIELD: 32,\n\n /** PARTICLE */\n PARTICLE: 64,\n\n /** CYLINDER */\n CYLINDER: 128,\n\n /** TRIMESH */\n TRIMESH: 256\n};\n/**\n * ShapeType\n */\n\n/**\n * Base class for shapes\n */\nclass Shape {\n /**\n * Identifier of the Shape.\n */\n\n /**\n * The type of this shape. Must be set to an int > 0 by subclasses.\n */\n\n /**\n * The local bounding sphere radius of this shape.\n */\n\n /**\n * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.\n * @default true\n */\n\n /**\n * @default 1\n */\n\n /**\n * @default -1\n */\n\n /**\n * Optional material of the shape that regulates contact properties.\n */\n\n /**\n * The body to which the shape is added to.\n */\n\n /**\n * All the Shape types.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.id = Shape.idCounter++;\n this.type = options.type || 0;\n this.boundingSphereRadius = 0;\n this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;\n this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;\n this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;\n this.material = options.material ? options.material : null;\n this.body = null;\n }\n /**\n * Computes the bounding sphere radius.\n * The result is stored in the property `.boundingSphereRadius`\n */\n\n\n updateBoundingSphereRadius() {\n throw `computeBoundingSphereRadius() not implemented for shape type ${this.type}`;\n }\n /**\n * Get the volume of this shape\n */\n\n\n volume() {\n throw `volume() not implemented for shape type ${this.type}`;\n }\n /**\n * Calculates the inertia in the local frame for this shape.\n * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia\n */\n\n\n calculateLocalInertia(mass, target) {\n throw `calculateLocalInertia() not implemented for shape type ${this.type}`;\n }\n /**\n * @todo use abstract for these kind of methods\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n throw `calculateWorldAABB() not implemented for shape type ${this.type}`;\n }\n\n}\nShape.idCounter = 0;\nShape.types = SHAPE_TYPES;\n\n/**\n * Transformation utilities.\n */\nclass Transform {\n /**\n * position\n */\n\n /**\n * quaternion\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.position = new Vec3();\n this.quaternion = new Quaternion();\n\n if (options.position) {\n this.position.copy(options.position);\n }\n\n if (options.quaternion) {\n this.quaternion.copy(options.quaternion);\n }\n }\n /**\n * Get a global point in local transform coordinates.\n */\n\n\n pointToLocal(worldPoint, result) {\n return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);\n }\n /**\n * Get a local point in global transform coordinates.\n */\n\n\n pointToWorld(localPoint, result) {\n return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);\n }\n /**\n * vectorToWorldFrame\n */\n\n\n vectorToWorldFrame(localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * pointToLocalFrame\n */\n\n\n static pointToLocalFrame(position, quaternion, worldPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n worldPoint.vsub(position, result);\n quaternion.conjugate(tmpQuat$1);\n tmpQuat$1.vmult(result, result);\n return result;\n }\n /**\n * pointToWorldFrame\n */\n\n\n static pointToWorldFrame(position, quaternion, localPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.vmult(localPoint, result);\n result.vadd(position, result);\n return result;\n }\n /**\n * vectorToWorldFrame\n */\n\n\n static vectorToWorldFrame(quaternion, localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * vectorToLocalFrame\n */\n\n\n static vectorToLocalFrame(position, quaternion, worldVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.w *= -1;\n quaternion.vmult(worldVector, result);\n quaternion.w *= -1;\n return result;\n }\n\n}\nconst tmpQuat$1 = new Quaternion();\n\n/**\n * A set of polygons describing a convex shape.\n *\n * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained\n * in the same 3D plane), instead these should be merged into one polygon.\n *\n * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)\n * @author schteppe / https://github.com/schteppe\n * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/\n *\n * @todo Move the clipping functions to ContactGenerator?\n * @todo Automatically merge coplanar polygons in constructor.\n * @example\n * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })\n * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })\n * world.addBody(convexBody)\n */\nclass ConvexPolyhedron extends Shape {\n /** vertices */\n\n /**\n * Array of integer arrays, indicating which vertices each face consists of\n */\n\n /** faceNormals */\n\n /** worldVertices */\n\n /** worldVerticesNeedsUpdate */\n\n /** worldFaceNormals */\n\n /** worldFaceNormalsNeedsUpdate */\n\n /**\n * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.\n */\n\n /** uniqueEdges */\n\n /**\n * @param vertices An array of Vec3's\n * @param faces Array of integer arrays, describing which vertices that is included in each face.\n */\n constructor(props) {\n if (props === void 0) {\n props = {};\n }\n\n const {\n vertices = [],\n faces = [],\n normals = [],\n axes,\n boundingSphereRadius\n } = props;\n super({\n type: Shape.types.CONVEXPOLYHEDRON\n });\n this.vertices = vertices;\n this.faces = faces;\n this.faceNormals = normals;\n\n if (this.faceNormals.length === 0) {\n this.computeNormals();\n }\n\n if (!boundingSphereRadius) {\n this.updateBoundingSphereRadius();\n } else {\n this.boundingSphereRadius = boundingSphereRadius;\n }\n\n this.worldVertices = []; // World transformed version of .vertices\n\n this.worldVerticesNeedsUpdate = true;\n this.worldFaceNormals = []; // World transformed version of .faceNormals\n\n this.worldFaceNormalsNeedsUpdate = true;\n this.uniqueAxes = axes ? axes.slice() : null;\n this.uniqueEdges = [];\n this.computeEdges();\n }\n /**\n * Computes uniqueEdges\n */\n\n\n computeEdges() {\n const faces = this.faces;\n const vertices = this.vertices;\n const edges = this.uniqueEdges;\n edges.length = 0;\n const edge = new Vec3();\n\n for (let i = 0; i !== faces.length; i++) {\n const face = faces[i];\n const numVertices = face.length;\n\n for (let j = 0; j !== numVertices; j++) {\n const k = (j + 1) % numVertices;\n vertices[face[j]].vsub(vertices[face[k]], edge);\n edge.normalize();\n let found = false;\n\n for (let p = 0; p !== edges.length; p++) {\n if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n edges.push(edge.clone());\n }\n }\n }\n }\n /**\n * Compute the normals of the faces.\n * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.\n */\n\n\n computeNormals() {\n this.faceNormals.length = this.faces.length; // Generate normals\n\n for (let i = 0; i < this.faces.length; i++) {\n // Check so all vertices exists for this face\n for (let j = 0; j < this.faces[i].length; j++) {\n if (!this.vertices[this.faces[i][j]]) {\n throw new Error(`Vertex ${this.faces[i][j]} not found!`);\n }\n }\n\n const n = this.faceNormals[i] || new Vec3();\n this.getFaceNormal(i, n);\n n.negate(n);\n this.faceNormals[i] = n;\n const vertex = this.vertices[this.faces[i][0]];\n\n if (n.dot(vertex) < 0) {\n console.error(`.faceNormals[${i}] = Vec3(${n.toString()}) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.`);\n\n for (let j = 0; j < this.faces[i].length; j++) {\n console.warn(`.vertices[${this.faces[i][j]}] = Vec3(${this.vertices[this.faces[i][j]].toString()})`);\n }\n }\n }\n }\n /**\n * Compute the normal of a face from its vertices\n */\n\n\n getFaceNormal(i, target) {\n const f = this.faces[i];\n const va = this.vertices[f[0]];\n const vb = this.vertices[f[1]];\n const vc = this.vertices[f[2]];\n ConvexPolyhedron.computeNormal(va, vb, vc, target);\n }\n /**\n * Get face normal given 3 vertices\n */\n\n\n static computeNormal(va, vb, vc, target) {\n const cb = new Vec3();\n const ab = new Vec3();\n vb.vsub(va, ab);\n vc.vsub(vb, cb);\n cb.cross(ab, target);\n\n if (!target.isZero()) {\n target.normalize();\n }\n }\n /**\n * @param minDist Clamp distance\n * @param result The an array of contact point objects, see clipFaceAgainstHull\n */\n\n\n clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {\n const WorldNormal = new Vec3();\n let closestFaceB = -1;\n let dmax = -Number.MAX_VALUE;\n\n for (let face = 0; face < hullB.faces.length; face++) {\n WorldNormal.copy(hullB.faceNormals[face]);\n quatB.vmult(WorldNormal, WorldNormal);\n const d = WorldNormal.dot(separatingNormal);\n\n if (d > dmax) {\n dmax = d;\n closestFaceB = face;\n }\n }\n\n const worldVertsB1 = [];\n\n for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {\n const b = hullB.vertices[hullB.faces[closestFaceB][i]];\n const worldb = new Vec3();\n worldb.copy(b);\n quatB.vmult(worldb, worldb);\n posB.vadd(worldb, worldb);\n worldVertsB1.push(worldb);\n }\n\n if (closestFaceB >= 0) {\n this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);\n }\n }\n /**\n * Find the separating axis between this hull and another\n * @param target The target vector to save the axis in\n * @return Returns false if a separation is found, else true\n */\n\n\n findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {\n const faceANormalWS3 = new Vec3();\n const Worldnormal1 = new Vec3();\n const deltaC = new Vec3();\n const worldEdge0 = new Vec3();\n const worldEdge1 = new Vec3();\n const Cross = new Vec3();\n let dmin = Number.MAX_VALUE;\n const hullA = this;\n\n if (!hullA.uniqueAxes) {\n const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA\n\n for (let i = 0; i < numFacesA; i++) {\n const fi = faceListA ? faceListA[i] : i; // Get world face normal\n\n faceANormalWS3.copy(hullA.faceNormals[fi]);\n quatA.vmult(faceANormalWS3, faceANormalWS3);\n const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(faceANormalWS3);\n }\n }\n } else {\n // Test unique axes\n for (let i = 0; i !== hullA.uniqueAxes.length; i++) {\n // Get world axis\n quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);\n const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(faceANormalWS3);\n }\n }\n }\n\n if (!hullB.uniqueAxes) {\n // Test face normals from hullB\n const numFacesB = faceListB ? faceListB.length : hullB.faces.length;\n\n for (let i = 0; i < numFacesB; i++) {\n const fi = faceListB ? faceListB[i] : i;\n Worldnormal1.copy(hullB.faceNormals[fi]);\n quatB.vmult(Worldnormal1, Worldnormal1);\n const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(Worldnormal1);\n }\n }\n } else {\n // Test unique axes in B\n for (let i = 0; i !== hullB.uniqueAxes.length; i++) {\n quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);\n const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(Worldnormal1);\n }\n }\n } // Test edges\n\n\n for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {\n // Get world edge\n quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);\n\n for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {\n // Get world edge 2\n quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);\n worldEdge0.cross(worldEdge1, Cross);\n\n if (!Cross.almostZero()) {\n Cross.normalize();\n const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);\n\n if (dist === false) {\n return false;\n }\n\n if (dist < dmin) {\n dmin = dist;\n target.copy(Cross);\n }\n }\n }\n }\n\n posB.vsub(posA, deltaC);\n\n if (deltaC.dot(target) > 0.0) {\n target.negate(target);\n }\n\n return true;\n }\n /**\n * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.\n * @return The overlap depth, or FALSE if no penetration.\n */\n\n\n testSepAxis(axis, hullB, posA, quatA, posB, quatB) {\n const hullA = this;\n ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);\n ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);\n const maxA = maxminA[0];\n const minA = maxminA[1];\n const maxB = maxminB[0];\n const minB = maxminB[1];\n\n if (maxA < minB || maxB < minA) {\n return false; // Separated\n }\n\n const d0 = maxA - minB;\n const d1 = maxB - minA;\n const depth = d0 < d1 ? d0 : d1;\n return depth;\n }\n /**\n * calculateLocalInertia\n */\n\n\n calculateLocalInertia(mass, target) {\n // Approximate with box inertia\n // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it\n const aabbmax = new Vec3();\n const aabbmin = new Vec3();\n this.computeLocalAABB(aabbmin, aabbmax);\n const x = aabbmax.x - aabbmin.x;\n const y = aabbmax.y - aabbmin.y;\n const z = aabbmax.z - aabbmin.z;\n target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);\n target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);\n target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);\n }\n /**\n * @param face_i Index of the face\n */\n\n\n getPlaneConstantOfFace(face_i) {\n const f = this.faces[face_i];\n const n = this.faceNormals[face_i];\n const v = this.vertices[f[0]];\n const c = -n.dot(v);\n return c;\n }\n /**\n * Clip a face against a hull.\n * @param worldVertsB1 An array of Vec3 with vertices in the world frame.\n * @param minDist Distance clamping\n * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.\n */\n\n\n clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {\n const faceANormalWS = new Vec3();\n const edge0 = new Vec3();\n const WorldEdge0 = new Vec3();\n const worldPlaneAnormal1 = new Vec3();\n const planeNormalWS1 = new Vec3();\n const worldA1 = new Vec3();\n const localPlaneNormal = new Vec3();\n const planeNormalWS = new Vec3();\n const hullA = this;\n const worldVertsB2 = [];\n const pVtxIn = worldVertsB1;\n const pVtxOut = worldVertsB2;\n let closestFaceA = -1;\n let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis\n\n for (let face = 0; face < hullA.faces.length; face++) {\n faceANormalWS.copy(hullA.faceNormals[face]);\n quatA.vmult(faceANormalWS, faceANormalWS);\n const d = faceANormalWS.dot(separatingNormal);\n\n if (d < dmin) {\n dmin = d;\n closestFaceA = face;\n }\n }\n\n if (closestFaceA < 0) {\n return;\n } // Get the face and construct connected faces\n\n\n const polyA = hullA.faces[closestFaceA];\n polyA.connectedFaces = [];\n\n for (let i = 0; i < hullA.faces.length; i++) {\n for (let j = 0; j < hullA.faces[i].length; j++) {\n if (\n /* Sharing a vertex*/\n polyA.indexOf(hullA.faces[i][j]) !== -1 &&\n /* Not the one we are looking for connections from */\n i !== closestFaceA &&\n /* Not already added */\n polyA.connectedFaces.indexOf(i) === -1) {\n polyA.connectedFaces.push(i);\n }\n }\n } // Clip the polygon to the back of the planes of all faces of hull A,\n // that are adjacent to the witness face\n\n\n const numVerticesA = polyA.length;\n\n for (let i = 0; i < numVerticesA; i++) {\n const a = hullA.vertices[polyA[i]];\n const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];\n a.vsub(b, edge0);\n WorldEdge0.copy(edge0);\n quatA.vmult(WorldEdge0, WorldEdge0);\n posA.vadd(WorldEdge0, WorldEdge0);\n worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);\n quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);\n posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);\n WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);\n planeNormalWS1.negate(planeNormalWS1);\n worldA1.copy(a);\n quatA.vmult(worldA1, worldA1);\n posA.vadd(worldA1, worldA1);\n const otherFace = polyA.connectedFaces[i];\n localPlaneNormal.copy(this.faceNormals[otherFace]);\n const localPlaneEq = this.getPlaneConstantOfFace(otherFace);\n planeNormalWS.copy(localPlaneNormal);\n quatA.vmult(planeNormalWS, planeNormalWS);\n const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane\n\n this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip\n\n while (pVtxIn.length) {\n pVtxIn.shift();\n }\n\n while (pVtxOut.length) {\n pVtxIn.push(pVtxOut.shift());\n }\n } // only keep contact points that are behind the witness face\n\n\n localPlaneNormal.copy(this.faceNormals[closestFaceA]);\n const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);\n planeNormalWS.copy(localPlaneNormal);\n quatA.vmult(planeNormalWS, planeNormalWS);\n const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);\n\n for (let i = 0; i < pVtxIn.length; i++) {\n let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???\n\n if (depth <= minDist) {\n console.log(`clamped: depth=${depth} to minDist=${minDist}`);\n depth = minDist;\n }\n\n if (depth <= maxDist) {\n const point = pVtxIn[i];\n\n if (depth <= 1e-6) {\n const p = {\n point,\n normal: planeNormalWS,\n depth\n };\n result.push(p);\n }\n }\n }\n }\n /**\n * Clip a face in a hull against the back of a plane.\n * @param planeConstant The constant in the mathematical plane equation\n */\n\n\n clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {\n let n_dot_first;\n let n_dot_last;\n const numVerts = inVertices.length;\n\n if (numVerts < 2) {\n return outVertices;\n }\n\n let firstVertex = inVertices[inVertices.length - 1];\n let lastVertex = inVertices[0];\n n_dot_first = planeNormal.dot(firstVertex) + planeConstant;\n\n for (let vi = 0; vi < numVerts; vi++) {\n lastVertex = inVertices[vi];\n n_dot_last = planeNormal.dot(lastVertex) + planeConstant;\n\n if (n_dot_first < 0) {\n if (n_dot_last < 0) {\n // Start < 0, end < 0, so output lastVertex\n const newv = new Vec3();\n newv.copy(lastVertex);\n outVertices.push(newv);\n } else {\n // Start < 0, end >= 0, so output intersection\n const newv = new Vec3();\n firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);\n outVertices.push(newv);\n }\n } else {\n if (n_dot_last < 0) {\n // Start >= 0, end < 0 so output intersection and end\n const newv = new Vec3();\n firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);\n outVertices.push(newv);\n outVertices.push(lastVertex);\n }\n }\n\n firstVertex = lastVertex;\n n_dot_first = n_dot_last;\n }\n\n return outVertices;\n }\n /**\n * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.\n */\n\n\n computeWorldVertices(position, quat) {\n while (this.worldVertices.length < this.vertices.length) {\n this.worldVertices.push(new Vec3());\n }\n\n const verts = this.vertices;\n const worldVerts = this.worldVertices;\n\n for (let i = 0; i !== this.vertices.length; i++) {\n quat.vmult(verts[i], worldVerts[i]);\n position.vadd(worldVerts[i], worldVerts[i]);\n }\n\n this.worldVerticesNeedsUpdate = false;\n }\n\n computeLocalAABB(aabbmin, aabbmax) {\n const vertices = this.vertices;\n aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n\n for (let i = 0; i < this.vertices.length; i++) {\n const v = vertices[i];\n\n if (v.x < aabbmin.x) {\n aabbmin.x = v.x;\n } else if (v.x > aabbmax.x) {\n aabbmax.x = v.x;\n }\n\n if (v.y < aabbmin.y) {\n aabbmin.y = v.y;\n } else if (v.y > aabbmax.y) {\n aabbmax.y = v.y;\n }\n\n if (v.z < aabbmin.z) {\n aabbmin.z = v.z;\n } else if (v.z > aabbmax.z) {\n aabbmax.z = v.z;\n }\n }\n }\n /**\n * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.\n */\n\n\n computeWorldFaceNormals(quat) {\n const N = this.faceNormals.length;\n\n while (this.worldFaceNormals.length < N) {\n this.worldFaceNormals.push(new Vec3());\n }\n\n const normals = this.faceNormals;\n const worldNormals = this.worldFaceNormals;\n\n for (let i = 0; i !== N; i++) {\n quat.vmult(normals[i], worldNormals[i]);\n }\n\n this.worldFaceNormalsNeedsUpdate = false;\n }\n /**\n * updateBoundingSphereRadius\n */\n\n\n updateBoundingSphereRadius() {\n // Assume points are distributed with local (0,0,0) as center\n let max2 = 0;\n const verts = this.vertices;\n\n for (let i = 0; i !== verts.length; i++) {\n const norm2 = verts[i].lengthSquared();\n\n if (norm2 > max2) {\n max2 = norm2;\n }\n }\n\n this.boundingSphereRadius = Math.sqrt(max2);\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n const verts = this.vertices;\n let minx;\n let miny;\n let minz;\n let maxx;\n let maxy;\n let maxz;\n let tempWorldVertex = new Vec3();\n\n for (let i = 0; i < verts.length; i++) {\n tempWorldVertex.copy(verts[i]);\n quat.vmult(tempWorldVertex, tempWorldVertex);\n pos.vadd(tempWorldVertex, tempWorldVertex);\n const v = tempWorldVertex;\n\n if (minx === undefined || v.x < minx) {\n minx = v.x;\n }\n\n if (maxx === undefined || v.x > maxx) {\n maxx = v.x;\n }\n\n if (miny === undefined || v.y < miny) {\n miny = v.y;\n }\n\n if (maxy === undefined || v.y > maxy) {\n maxy = v.y;\n }\n\n if (minz === undefined || v.z < minz) {\n minz = v.z;\n }\n\n if (maxz === undefined || v.z > maxz) {\n maxz = v.z;\n }\n }\n\n min.set(minx, miny, minz);\n max.set(maxx, maxy, maxz);\n }\n /**\n * Get approximate convex volume\n */\n\n\n volume() {\n return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;\n }\n /**\n * Get an average of all the vertices positions\n */\n\n\n getAveragePointLocal(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const verts = this.vertices;\n\n for (let i = 0; i < verts.length; i++) {\n target.vadd(verts[i], target);\n }\n\n target.scale(1 / verts.length, target);\n return target;\n }\n /**\n * Transform all local points. Will change the .vertices\n */\n\n\n transformAllPoints(offset, quat) {\n const n = this.vertices.length;\n const verts = this.vertices; // Apply rotation\n\n if (quat) {\n // Rotate vertices\n for (let i = 0; i < n; i++) {\n const v = verts[i];\n quat.vmult(v, v);\n } // Rotate face normals\n\n\n for (let i = 0; i < this.faceNormals.length; i++) {\n const v = this.faceNormals[i];\n quat.vmult(v, v);\n }\n /*\n // Rotate edges\n for(let i=0; i 0 || r1 > 0 && r2 < 0) {\n return false; // Encountered some other sign. Exit.\n }\n } // If we got here, all dot products were of the same sign.\n\n\n return positiveResult ? 1 : -1;\n }\n /**\n * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.\n * Results are saved in the array maxmin.\n * @param result result[0] and result[1] will be set to maximum and minimum, respectively.\n */\n\n\n static project(shape, axis, pos, quat, result) {\n const n = shape.vertices.length;\n project_worldVertex;\n const localAxis = project_localAxis;\n let max = 0;\n let min = 0;\n const localOrigin = project_localOrigin;\n const vs = shape.vertices;\n localOrigin.setZero(); // Transform the axis to local\n\n Transform.vectorToLocalFrame(pos, quat, axis, localAxis);\n Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);\n const add = localOrigin.dot(localAxis);\n min = max = vs[0].dot(localAxis);\n\n for (let i = 1; i < n; i++) {\n const val = vs[i].dot(localAxis);\n\n if (val > max) {\n max = val;\n }\n\n if (val < min) {\n min = val;\n }\n }\n\n min -= add;\n max -= add;\n\n if (min > max) {\n // Inconsistent - swap\n const temp = min;\n min = max;\n max = temp;\n } // Output\n\n\n result[0] = max;\n result[1] = min;\n }\n\n}\nconst maxminA = [];\nconst maxminB = [];\nconst project_worldVertex = new Vec3();\nconst project_localAxis = new Vec3();\nconst project_localOrigin = new Vec3();\n\n/**\n * A 3d box shape.\n * @example\n * const size = 1\n * const halfExtents = new CANNON.Vec3(size, size, size)\n * const boxShape = new CANNON.Box(halfExtents)\n * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })\n * world.addBody(boxBody)\n */\nclass Box extends Shape {\n /**\n * The half extents of the box.\n */\n\n /**\n * Used by the contact generator to make contacts with other convex polyhedra for example.\n */\n constructor(halfExtents) {\n super({\n type: Shape.types.BOX\n });\n this.halfExtents = halfExtents;\n this.convexPolyhedronRepresentation = null;\n this.updateConvexPolyhedronRepresentation();\n this.updateBoundingSphereRadius();\n }\n /**\n * Updates the local convex polyhedron representation used for some collisions.\n */\n\n\n updateConvexPolyhedronRepresentation() {\n const sx = this.halfExtents.x;\n const sy = this.halfExtents.y;\n const sz = this.halfExtents.z;\n const V = Vec3;\n const vertices = [new V(-sx, -sy, -sz), new V(sx, -sy, -sz), new V(sx, sy, -sz), new V(-sx, sy, -sz), new V(-sx, -sy, sz), new V(sx, -sy, sz), new V(sx, sy, sz), new V(-sx, sy, sz)];\n const faces = [[3, 2, 1, 0], // -z\n [4, 5, 6, 7], // +z\n [5, 4, 0, 1], // -y\n [2, 3, 7, 6], // +y\n [0, 4, 7, 3], // -x\n [1, 2, 6, 5] // +x\n ];\n const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];\n const h = new ConvexPolyhedron({\n vertices,\n faces,\n axes\n });\n this.convexPolyhedronRepresentation = h;\n h.material = this.material;\n }\n /**\n * Calculate the inertia of the box.\n */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n Box.calculateInertia(this.halfExtents, mass, target);\n return target;\n }\n\n static calculateInertia(halfExtents, mass, target) {\n const e = halfExtents;\n target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);\n target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);\n target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);\n }\n /**\n * Get the box 6 side normals\n * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.\n * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.\n */\n\n\n getSideNormals(sixTargetVectors, quat) {\n const sides = sixTargetVectors;\n const ex = this.halfExtents;\n sides[0].set(ex.x, 0, 0);\n sides[1].set(0, ex.y, 0);\n sides[2].set(0, 0, ex.z);\n sides[3].set(-ex.x, 0, 0);\n sides[4].set(0, -ex.y, 0);\n sides[5].set(0, 0, -ex.z);\n\n if (quat !== undefined) {\n for (let i = 0; i !== sides.length; i++) {\n quat.vmult(sides[i], sides[i]);\n }\n }\n\n return sides;\n }\n /**\n * Returns the volume of the box.\n */\n\n\n volume() {\n return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;\n }\n /**\n * updateBoundingSphereRadius\n */\n\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = this.halfExtents.length();\n }\n /**\n * forEachWorldCorner\n */\n\n\n forEachWorldCorner(pos, quat, callback) {\n const e = this.halfExtents;\n const corners = [[e.x, e.y, e.z], [-e.x, e.y, e.z], [-e.x, -e.y, e.z], [-e.x, -e.y, -e.z], [e.x, -e.y, -e.z], [e.x, e.y, -e.z], [-e.x, e.y, -e.z], [e.x, -e.y, e.z]];\n\n for (let i = 0; i < corners.length; i++) {\n worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);\n quat.vmult(worldCornerTempPos, worldCornerTempPos);\n pos.vadd(worldCornerTempPos, worldCornerTempPos);\n callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);\n }\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n const e = this.halfExtents;\n worldCornersTemp[0].set(e.x, e.y, e.z);\n worldCornersTemp[1].set(-e.x, e.y, e.z);\n worldCornersTemp[2].set(-e.x, -e.y, e.z);\n worldCornersTemp[3].set(-e.x, -e.y, -e.z);\n worldCornersTemp[4].set(e.x, -e.y, -e.z);\n worldCornersTemp[5].set(e.x, e.y, -e.z);\n worldCornersTemp[6].set(-e.x, e.y, -e.z);\n worldCornersTemp[7].set(e.x, -e.y, e.z);\n const wc = worldCornersTemp[0];\n quat.vmult(wc, wc);\n pos.vadd(wc, wc);\n max.copy(wc);\n min.copy(wc);\n\n for (let i = 1; i < 8; i++) {\n const wc = worldCornersTemp[i];\n quat.vmult(wc, wc);\n pos.vadd(wc, wc);\n const x = wc.x;\n const y = wc.y;\n const z = wc.z;\n\n if (x > max.x) {\n max.x = x;\n }\n\n if (y > max.y) {\n max.y = y;\n }\n\n if (z > max.z) {\n max.z = z;\n }\n\n if (x < min.x) {\n min.x = x;\n }\n\n if (y < min.y) {\n min.y = y;\n }\n\n if (z < min.z) {\n min.z = z;\n }\n } // Get each axis max\n // min.set(Infinity,Infinity,Infinity);\n // max.set(-Infinity,-Infinity,-Infinity);\n // this.forEachWorldCorner(pos,quat,function(x,y,z){\n // if(x > max.x){\n // max.x = x;\n // }\n // if(y > max.y){\n // max.y = y;\n // }\n // if(z > max.z){\n // max.z = z;\n // }\n // if(x < min.x){\n // min.x = x;\n // }\n // if(y < min.y){\n // min.y = y;\n // }\n // if(z < min.z){\n // min.z = z;\n // }\n // });\n\n }\n\n}\nconst worldCornerTempPos = new Vec3();\nconst worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\n\n/**\n * BODY_TYPES\n */\nconst BODY_TYPES = {\n /** DYNAMIC */\n DYNAMIC: 1,\n\n /** STATIC */\n STATIC: 2,\n\n /** KINEMATIC */\n KINEMATIC: 4\n};\n/**\n * BodyType\n */\n\n/**\n * BODY_SLEEP_STATES\n */\nconst BODY_SLEEP_STATES = {\n /** AWAKE */\n AWAKE: 0,\n\n /** SLEEPY */\n SLEEPY: 1,\n\n /** SLEEPING */\n SLEEPING: 2\n};\n/**\n * BodySleepState\n */\n\n/**\n * Base class for all body types.\n * @example\n * const shape = new CANNON.Sphere(1)\n * const body = new CANNON.Body({\n * mass: 1,\n * shape,\n * })\n * world.addBody(body)\n */\nclass Body extends EventTarget {\n /**\n * Dispatched after two bodies collide. This event is dispatched on each\n * of the two bodies involved in the collision.\n * @event collide\n * @param body The body that was involved in the collision.\n * @param contact The details of the collision.\n */\n\n /**\n * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.\n */\n\n /**\n * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.\n */\n\n /**\n * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.\n */\n\n /**\n * AWAKE\n */\n\n /**\n * SLEEPY\n */\n\n /**\n * SLEEPING\n */\n\n /**\n * Dispatched after a sleeping body has woken up.\n * @event wakeup\n */\n\n /**\n * Dispatched after a body has gone in to the sleepy state.\n * @event sleepy\n */\n\n /**\n * Dispatched after a body has fallen asleep.\n * @event sleep\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n super();\n this.id = Body.idCounter++;\n this.index = -1;\n this.world = null;\n this.vlambda = new Vec3();\n this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;\n this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;\n this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;\n this.position = new Vec3();\n this.previousPosition = new Vec3();\n this.interpolatedPosition = new Vec3();\n this.initPosition = new Vec3();\n\n if (options.position) {\n this.position.copy(options.position);\n this.previousPosition.copy(options.position);\n this.interpolatedPosition.copy(options.position);\n this.initPosition.copy(options.position);\n }\n\n this.velocity = new Vec3();\n\n if (options.velocity) {\n this.velocity.copy(options.velocity);\n }\n\n this.initVelocity = new Vec3();\n this.force = new Vec3();\n const mass = typeof options.mass === 'number' ? options.mass : 0;\n this.mass = mass;\n this.invMass = mass > 0 ? 1.0 / mass : 0;\n this.material = options.material || null;\n this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;\n this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;\n\n if (typeof options.type === typeof Body.STATIC) {\n this.type = options.type;\n }\n\n this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;\n this.sleepState = Body.AWAKE;\n this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;\n this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;\n this.timeLastSleepy = 0;\n this.wakeUpAfterNarrowphase = false;\n this.torque = new Vec3();\n this.quaternion = new Quaternion();\n this.initQuaternion = new Quaternion();\n this.previousQuaternion = new Quaternion();\n this.interpolatedQuaternion = new Quaternion();\n\n if (options.quaternion) {\n this.quaternion.copy(options.quaternion);\n this.initQuaternion.copy(options.quaternion);\n this.previousQuaternion.copy(options.quaternion);\n this.interpolatedQuaternion.copy(options.quaternion);\n }\n\n this.angularVelocity = new Vec3();\n\n if (options.angularVelocity) {\n this.angularVelocity.copy(options.angularVelocity);\n }\n\n this.initAngularVelocity = new Vec3();\n this.shapes = [];\n this.shapeOffsets = [];\n this.shapeOrientations = [];\n this.inertia = new Vec3();\n this.invInertia = new Vec3();\n this.invInertiaWorld = new Mat3();\n this.invMassSolve = 0;\n this.invInertiaSolve = new Vec3();\n this.invInertiaWorldSolve = new Mat3();\n this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;\n this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;\n this.linearFactor = new Vec3(1, 1, 1);\n\n if (options.linearFactor) {\n this.linearFactor.copy(options.linearFactor);\n }\n\n this.angularFactor = new Vec3(1, 1, 1);\n\n if (options.angularFactor) {\n this.angularFactor.copy(options.angularFactor);\n }\n\n this.aabb = new AABB();\n this.aabbNeedsUpdate = true;\n this.boundingRadius = 0;\n this.wlambda = new Vec3();\n this.isTrigger = Boolean(options.isTrigger);\n\n if (options.shape) {\n this.addShape(options.shape);\n }\n\n this.updateMassProperties();\n }\n /**\n * Wake the body up.\n */\n\n\n wakeUp() {\n const prevState = this.sleepState;\n this.sleepState = Body.AWAKE;\n this.wakeUpAfterNarrowphase = false;\n\n if (prevState === Body.SLEEPING) {\n this.dispatchEvent(Body.wakeupEvent);\n }\n }\n /**\n * Force body sleep\n */\n\n\n sleep() {\n this.sleepState = Body.SLEEPING;\n this.velocity.set(0, 0, 0);\n this.angularVelocity.set(0, 0, 0);\n this.wakeUpAfterNarrowphase = false;\n }\n /**\n * Called every timestep to update internal sleep timer and change sleep state if needed.\n * @param time The world time in seconds\n */\n\n\n sleepTick(time) {\n if (this.allowSleep) {\n const sleepState = this.sleepState;\n const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();\n const speedLimitSquared = this.sleepSpeedLimit ** 2;\n\n if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {\n this.sleepState = Body.SLEEPY; // Sleepy\n\n this.timeLastSleepy = time;\n this.dispatchEvent(Body.sleepyEvent);\n } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {\n this.wakeUp(); // Wake up\n } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {\n this.sleep(); // Sleeping\n\n this.dispatchEvent(Body.sleepEvent);\n }\n }\n }\n /**\n * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate \"solve mass\".\n */\n\n\n updateSolveMassProperties() {\n if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {\n this.invMassSolve = 0;\n this.invInertiaSolve.setZero();\n this.invInertiaWorldSolve.setZero();\n } else {\n this.invMassSolve = this.invMass;\n this.invInertiaSolve.copy(this.invInertia);\n this.invInertiaWorldSolve.copy(this.invInertiaWorld);\n }\n }\n /**\n * Convert a world point to local body frame.\n */\n\n\n pointToLocalFrame(worldPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n worldPoint.vsub(this.position, result);\n this.quaternion.conjugate().vmult(result, result);\n return result;\n }\n /**\n * Convert a world vector to local body frame.\n */\n\n\n vectorToLocalFrame(worldVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.conjugate().vmult(worldVector, result);\n return result;\n }\n /**\n * Convert a local body point to world frame.\n */\n\n\n pointToWorldFrame(localPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localPoint, result);\n result.vadd(this.position, result);\n return result;\n }\n /**\n * Convert a local body point to world frame.\n */\n\n\n vectorToWorldFrame(localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * Add a shape to the body with a local offset and orientation.\n * @return The body object, for chainability.\n */\n\n\n addShape(shape, _offset, _orientation) {\n const offset = new Vec3();\n const orientation = new Quaternion();\n\n if (_offset) {\n offset.copy(_offset);\n }\n\n if (_orientation) {\n orientation.copy(_orientation);\n }\n\n this.shapes.push(shape);\n this.shapeOffsets.push(offset);\n this.shapeOrientations.push(orientation);\n this.updateMassProperties();\n this.updateBoundingRadius();\n this.aabbNeedsUpdate = true;\n shape.body = this;\n return this;\n }\n /**\n * Remove a shape from the body.\n * @return The body object, for chainability.\n */\n\n\n removeShape(shape) {\n const index = this.shapes.indexOf(shape);\n\n if (index === -1) {\n console.warn('Shape does not belong to the body');\n return this;\n }\n\n this.shapes.splice(index, 1);\n this.shapeOffsets.splice(index, 1);\n this.shapeOrientations.splice(index, 1);\n this.updateMassProperties();\n this.updateBoundingRadius();\n this.aabbNeedsUpdate = true;\n shape.body = null;\n return this;\n }\n /**\n * Update the bounding radius of the body. Should be done if any of the shapes are changed.\n */\n\n\n updateBoundingRadius() {\n const shapes = this.shapes;\n const shapeOffsets = this.shapeOffsets;\n const N = shapes.length;\n let radius = 0;\n\n for (let i = 0; i !== N; i++) {\n const shape = shapes[i];\n shape.updateBoundingSphereRadius();\n const offset = shapeOffsets[i].length();\n const r = shape.boundingSphereRadius;\n\n if (offset + r > radius) {\n radius = offset + r;\n }\n }\n\n this.boundingRadius = radius;\n }\n /**\n * Updates the .aabb\n */\n\n\n updateAABB() {\n const shapes = this.shapes;\n const shapeOffsets = this.shapeOffsets;\n const shapeOrientations = this.shapeOrientations;\n const N = shapes.length;\n const offset = tmpVec;\n const orientation = tmpQuat;\n const bodyQuat = this.quaternion;\n const aabb = this.aabb;\n const shapeAABB = updateAABB_shapeAABB;\n\n for (let i = 0; i !== N; i++) {\n const shape = shapes[i]; // Get shape world position\n\n bodyQuat.vmult(shapeOffsets[i], offset);\n offset.vadd(this.position, offset); // Get shape world quaternion\n\n bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB\n\n shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);\n\n if (i === 0) {\n aabb.copy(shapeAABB);\n } else {\n aabb.extend(shapeAABB);\n }\n }\n\n this.aabbNeedsUpdate = false;\n }\n /**\n * Update `.inertiaWorld` and `.invInertiaWorld`\n */\n\n\n updateInertiaWorld(force) {\n const I = this.invInertia;\n\n if (I.x === I.y && I.y === I.z && !force) ; else {\n const m1 = uiw_m1;\n const m2 = uiw_m2;\n uiw_m3;\n m1.setRotationFromQuaternion(this.quaternion);\n m1.transpose(m2);\n m1.scale(I, m1);\n m1.mmult(m2, this.invInertiaWorld);\n }\n }\n /**\n * Apply force to a point of the body. This could for example be a point on the Body surface.\n * Applying force this way will add to Body.force and Body.torque.\n * @param force The amount of force to add.\n * @param relativePoint A point relative to the center of mass to apply the force on.\n */\n\n\n applyForce(force, relativePoint) {\n if (relativePoint === void 0) {\n relativePoint = new Vec3();\n }\n\n // Needed?\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Compute produced rotational force\n\n\n const rotForce = Body_applyForce_rotForce;\n relativePoint.cross(force, rotForce); // Add linear force\n\n this.force.vadd(force, this.force); // Add rotational force\n\n this.torque.vadd(rotForce, this.torque);\n }\n /**\n * Apply force to a local point in the body.\n * @param force The force vector to apply, defined locally in the body frame.\n * @param localPoint A local point in the body to apply the force on.\n */\n\n\n applyLocalForce(localForce, localPoint) {\n if (localPoint === void 0) {\n localPoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n const worldForce = Body_applyLocalForce_worldForce;\n const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space\n\n this.vectorToWorldFrame(localForce, worldForce);\n this.vectorToWorldFrame(localPoint, relativePointWorld);\n this.applyForce(worldForce, relativePointWorld);\n }\n /**\n * Apply torque to the body.\n * @param torque The amount of torque to add.\n */\n\n\n applyTorque(torque) {\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Add rotational force\n\n\n this.torque.vadd(torque, this.torque);\n }\n /**\n * Apply impulse to a point of the body. This could for example be a point on the Body surface.\n * An impulse is a force added to a body during a short period of time (impulse = force * time).\n * Impulses will be added to Body.velocity and Body.angularVelocity.\n * @param impulse The amount of impulse to add.\n * @param relativePoint A point relative to the center of mass to apply the force on.\n */\n\n\n applyImpulse(impulse, relativePoint) {\n if (relativePoint === void 0) {\n relativePoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Compute point position relative to the body center\n\n\n const r = relativePoint; // Compute produced central impulse velocity\n\n const velo = Body_applyImpulse_velo;\n velo.copy(impulse);\n velo.scale(this.invMass, velo); // Add linear impulse\n\n this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity\n\n const rotVelo = Body_applyImpulse_rotVelo;\n r.cross(impulse, rotVelo);\n /*\n rotVelo.x *= this.invInertia.x;\n rotVelo.y *= this.invInertia.y;\n rotVelo.z *= this.invInertia.z;\n */\n\n this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse\n\n this.angularVelocity.vadd(rotVelo, this.angularVelocity);\n }\n /**\n * Apply locally-defined impulse to a local point in the body.\n * @param force The force vector to apply, defined locally in the body frame.\n * @param localPoint A local point in the body to apply the force on.\n */\n\n\n applyLocalImpulse(localImpulse, localPoint) {\n if (localPoint === void 0) {\n localPoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n const worldImpulse = Body_applyLocalImpulse_worldImpulse;\n const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space\n\n this.vectorToWorldFrame(localImpulse, worldImpulse);\n this.vectorToWorldFrame(localPoint, relativePointWorld);\n this.applyImpulse(worldImpulse, relativePointWorld);\n }\n /**\n * Should be called whenever you change the body shape or mass.\n */\n\n\n updateMassProperties() {\n const halfExtents = Body_updateMassProperties_halfExtents;\n this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;\n const I = this.inertia;\n const fixed = this.fixedRotation; // Approximate with AABB box\n\n this.updateAABB();\n halfExtents.set((this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2, (this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2, (this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2);\n Box.calculateInertia(halfExtents, this.mass, I);\n this.invInertia.set(I.x > 0 && !fixed ? 1.0 / I.x : 0, I.y > 0 && !fixed ? 1.0 / I.y : 0, I.z > 0 && !fixed ? 1.0 / I.z : 0);\n this.updateInertiaWorld(true);\n }\n /**\n * Get world velocity of a point in the body.\n * @param worldPoint\n * @param result\n * @return The result vector.\n */\n\n\n getVelocityAtWorldPoint(worldPoint, result) {\n const r = new Vec3();\n worldPoint.vsub(this.position, r);\n this.angularVelocity.cross(r, result);\n this.velocity.vadd(result, result);\n return result;\n }\n /**\n * Move the body forward in time.\n * @param dt Time step\n * @param quatNormalize Set to true to normalize the body quaternion\n * @param quatNormalizeFast If the quaternion should be normalized using \"fast\" quaternion normalization\n */\n\n\n integrate(dt, quatNormalize, quatNormalizeFast) {\n // Save previous position\n this.previousPosition.copy(this.position);\n this.previousQuaternion.copy(this.quaternion);\n\n if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {\n // Only for dynamic\n return;\n }\n\n const velo = this.velocity;\n const angularVelo = this.angularVelocity;\n const pos = this.position;\n const force = this.force;\n const torque = this.torque;\n const quat = this.quaternion;\n const invMass = this.invMass;\n const invInertia = this.invInertiaWorld;\n const linearFactor = this.linearFactor;\n const iMdt = invMass * dt;\n velo.x += force.x * iMdt * linearFactor.x;\n velo.y += force.y * iMdt * linearFactor.y;\n velo.z += force.z * iMdt * linearFactor.z;\n const e = invInertia.elements;\n const angularFactor = this.angularFactor;\n const tx = torque.x * angularFactor.x;\n const ty = torque.y * angularFactor.y;\n const tz = torque.z * angularFactor.z;\n angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);\n angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);\n angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog\n\n pos.x += velo.x * dt;\n pos.y += velo.y * dt;\n pos.z += velo.z * dt;\n quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);\n\n if (quatNormalize) {\n if (quatNormalizeFast) {\n quat.normalizeFast();\n } else {\n quat.normalize();\n }\n }\n\n this.aabbNeedsUpdate = true; // Update world inertia\n\n this.updateInertiaWorld();\n }\n\n}\nBody.idCounter = 0;\nBody.COLLIDE_EVENT_NAME = 'collide';\nBody.DYNAMIC = BODY_TYPES.DYNAMIC;\nBody.STATIC = BODY_TYPES.STATIC;\nBody.KINEMATIC = BODY_TYPES.KINEMATIC;\nBody.AWAKE = BODY_SLEEP_STATES.AWAKE;\nBody.SLEEPY = BODY_SLEEP_STATES.SLEEPY;\nBody.SLEEPING = BODY_SLEEP_STATES.SLEEPING;\nBody.wakeupEvent = {\n type: 'wakeup'\n};\nBody.sleepyEvent = {\n type: 'sleepy'\n};\nBody.sleepEvent = {\n type: 'sleep'\n};\nconst tmpVec = new Vec3();\nconst tmpQuat = new Quaternion();\nconst updateAABB_shapeAABB = new AABB();\nconst uiw_m1 = new Mat3();\nconst uiw_m2 = new Mat3();\nconst uiw_m3 = new Mat3();\nconst Body_applyForce_rotForce = new Vec3();\nconst Body_applyLocalForce_worldForce = new Vec3();\nconst Body_applyLocalForce_relativePointWorld = new Vec3();\nconst Body_applyImpulse_velo = new Vec3();\nconst Body_applyImpulse_rotVelo = new Vec3();\nconst Body_applyLocalImpulse_worldImpulse = new Vec3();\nconst Body_applyLocalImpulse_relativePoint = new Vec3();\nconst Body_updateMassProperties_halfExtents = new Vec3();\n\n/**\n * Base class for broadphase implementations\n * @author schteppe\n */\nclass Broadphase {\n /**\n * The world to search for collisions in.\n */\n\n /**\n * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.\n */\n\n /**\n * Set to true if the objects in the world moved.\n */\n constructor() {\n this.world = null;\n this.useBoundingBoxes = false;\n this.dirty = true;\n }\n /**\n * Get the collision pairs from the world\n * @param world The world to search in\n * @param p1 Empty array to be filled with body objects\n * @param p2 Empty array to be filled with body objects\n */\n\n\n collisionPairs(world, p1, p2) {\n throw new Error('collisionPairs not implemented for this BroadPhase class!');\n }\n /**\n * Check if a body pair needs to be intersection tested at all.\n */\n\n\n needBroadphaseCollision(bodyA, bodyB) {\n // Check collision filter masks\n if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {\n return false;\n } // Check types\n\n\n if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {\n // Both bodies are static or sleeping. Skip.\n return false;\n }\n\n return true;\n }\n /**\n * Check if the bounding volumes of two bodies intersect.\n */\n\n\n intersectionTest(bodyA, bodyB, pairs1, pairs2) {\n if (this.useBoundingBoxes) {\n this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);\n } else {\n this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);\n }\n }\n /**\n * Check if the bounding spheres of two bodies are intersecting.\n * @param pairs1 bodyA is appended to this array if intersection\n * @param pairs2 bodyB is appended to this array if intersection\n */\n\n\n doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {\n const r = Broadphase_collisionPairs_r;\n bodyB.position.vsub(bodyA.position, r);\n const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;\n const norm2 = r.lengthSquared();\n\n if (norm2 < boundingRadiusSum2) {\n pairs1.push(bodyA);\n pairs2.push(bodyB);\n }\n }\n /**\n * Check if the bounding boxes of two bodies are intersecting.\n */\n\n\n doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {\n if (bodyA.aabbNeedsUpdate) {\n bodyA.updateAABB();\n }\n\n if (bodyB.aabbNeedsUpdate) {\n bodyB.updateAABB();\n } // Check AABB / AABB\n\n\n if (bodyA.aabb.overlaps(bodyB.aabb)) {\n pairs1.push(bodyA);\n pairs2.push(bodyB);\n }\n }\n /**\n * Removes duplicate pairs from the pair arrays.\n */\n\n\n makePairsUnique(pairs1, pairs2) {\n const t = Broadphase_makePairsUnique_temp;\n const p1 = Broadphase_makePairsUnique_p1;\n const p2 = Broadphase_makePairsUnique_p2;\n const N = pairs1.length;\n\n for (let i = 0; i !== N; i++) {\n p1[i] = pairs1[i];\n p2[i] = pairs2[i];\n }\n\n pairs1.length = 0;\n pairs2.length = 0;\n\n for (let i = 0; i !== N; i++) {\n const id1 = p1[i].id;\n const id2 = p2[i].id;\n const key = id1 < id2 ? `${id1},${id2}` : `${id2},${id1}`;\n t[key] = i;\n t.keys.push(key);\n }\n\n for (let i = 0; i !== t.keys.length; i++) {\n const key = t.keys.pop();\n const pairIndex = t[key];\n pairs1.push(p1[pairIndex]);\n pairs2.push(p2[pairIndex]);\n delete t[key];\n }\n }\n /**\n * To be implemented by subcasses\n */\n\n\n setWorld(world) {}\n /**\n * Check if the bounding spheres of two bodies overlap.\n */\n\n\n static boundingSphereCheck(bodyA, bodyB) {\n const dist = new Vec3(); // bsc_dist;\n\n bodyA.position.vsub(bodyB.position, dist);\n const sa = bodyA.shapes[0];\n const sb = bodyB.shapes[0];\n return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();\n }\n /**\n * Returns all the bodies within the AABB.\n */\n\n\n aabbQuery(world, aabb, result) {\n console.warn('.aabbQuery is not implemented in this Broadphase subclass.');\n return [];\n }\n\n} // Temp objects\n\nconst Broadphase_collisionPairs_r = new Vec3();\nnew Vec3();\nnew Quaternion();\nnew Vec3();\nconst Broadphase_makePairsUnique_temp = {\n keys: []\n};\nconst Broadphase_makePairsUnique_p1 = [];\nconst Broadphase_makePairsUnique_p2 = [];\nnew Vec3();\n\n/**\n * Axis aligned uniform grid broadphase.\n * @todo Needs support for more than just planes and spheres.\n */\nclass GridBroadphase extends Broadphase {\n /**\n * Number of boxes along x\n */\n\n /**\n * Number of boxes along y\n */\n\n /**\n * Number of boxes along z\n */\n\n /**\n * aabbMin\n */\n\n /**\n * aabbMax\n */\n\n /**\n * bins\n */\n\n /**\n * binLengths\n */\n\n /**\n * @param nx Number of boxes along x.\n * @param ny Number of boxes along y.\n * @param nz Number of boxes along z.\n */\n constructor(aabbMin, aabbMax, nx, ny, nz) {\n if (aabbMin === void 0) {\n aabbMin = new Vec3(100, 100, 100);\n }\n\n if (aabbMax === void 0) {\n aabbMax = new Vec3(-100, -100, -100);\n }\n\n if (nx === void 0) {\n nx = 10;\n }\n\n if (ny === void 0) {\n ny = 10;\n }\n\n if (nz === void 0) {\n nz = 10;\n }\n\n super();\n this.nx = nx;\n this.ny = ny;\n this.nz = nz;\n this.aabbMin = aabbMin;\n this.aabbMax = aabbMax;\n const nbins = this.nx * this.ny * this.nz;\n\n if (nbins <= 0) {\n throw \"GridBroadphase: Each dimension's n must be >0\";\n }\n\n this.bins = [];\n this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow\n\n this.bins.length = nbins;\n this.binLengths.length = nbins;\n\n for (let i = 0; i < nbins; i++) {\n this.bins[i] = [];\n this.binLengths[i] = 0;\n }\n }\n /**\n * Get all the collision pairs in the physics world\n */\n\n\n collisionPairs(world, pairs1, pairs2) {\n const N = world.bodies.length;\n const bodies = world.bodies;\n const max = this.aabbMax;\n const min = this.aabbMin;\n const nx = this.nx;\n const ny = this.ny;\n const nz = this.nz;\n const xstep = ny * nz;\n const ystep = nz;\n const zstep = 1;\n const xmax = max.x;\n const ymax = max.y;\n const zmax = max.z;\n const xmin = min.x;\n const ymin = min.y;\n const zmin = min.z;\n const xmult = nx / (xmax - xmin);\n const ymult = ny / (ymax - ymin);\n const zmult = nz / (zmax - zmin);\n const binsizeX = (xmax - xmin) / nx;\n const binsizeY = (ymax - ymin) / ny;\n const binsizeZ = (zmax - zmin) / nz;\n const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;\n const types = Shape.types;\n const SPHERE = types.SPHERE;\n const PLANE = types.PLANE;\n types.BOX;\n types.COMPOUND;\n types.CONVEXPOLYHEDRON;\n const bins = this.bins;\n const binLengths = this.binLengths;\n const Nbins = this.bins.length; // Reset bins\n\n for (let i = 0; i !== Nbins; i++) {\n binLengths[i] = 0;\n }\n\n const ceil = Math.ceil;\n\n function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {\n let xoff0 = (x0 - xmin) * xmult | 0;\n let yoff0 = (y0 - ymin) * ymult | 0;\n let zoff0 = (z0 - zmin) * zmult | 0;\n let xoff1 = ceil((x1 - xmin) * xmult);\n let yoff1 = ceil((y1 - ymin) * ymult);\n let zoff1 = ceil((z1 - zmin) * zmult);\n\n if (xoff0 < 0) {\n xoff0 = 0;\n } else if (xoff0 >= nx) {\n xoff0 = nx - 1;\n }\n\n if (yoff0 < 0) {\n yoff0 = 0;\n } else if (yoff0 >= ny) {\n yoff0 = ny - 1;\n }\n\n if (zoff0 < 0) {\n zoff0 = 0;\n } else if (zoff0 >= nz) {\n zoff0 = nz - 1;\n }\n\n if (xoff1 < 0) {\n xoff1 = 0;\n } else if (xoff1 >= nx) {\n xoff1 = nx - 1;\n }\n\n if (yoff1 < 0) {\n yoff1 = 0;\n } else if (yoff1 >= ny) {\n yoff1 = ny - 1;\n }\n\n if (zoff1 < 0) {\n zoff1 = 0;\n } else if (zoff1 >= nz) {\n zoff1 = nz - 1;\n }\n\n xoff0 *= xstep;\n yoff0 *= ystep;\n zoff0 *= zstep;\n xoff1 *= xstep;\n yoff1 *= ystep;\n zoff1 *= zstep;\n\n for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) {\n for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) {\n for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) {\n const idx = xoff + yoff + zoff;\n bins[idx][binLengths[idx]++] = bi;\n }\n }\n }\n } // Put all bodies into the bins\n\n\n for (let i = 0; i !== N; i++) {\n const bi = bodies[i];\n const si = bi.shapes[0];\n\n switch (si.type) {\n case SPHERE:\n {\n const shape = si; // Put in bin\n // check if overlap with other bins\n\n const x = bi.position.x;\n const y = bi.position.y;\n const z = bi.position.z;\n const r = shape.radius;\n addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);\n break;\n }\n\n case PLANE:\n {\n const shape = si;\n\n if (shape.worldNormalNeedsUpdate) {\n shape.computeWorldNormal(bi.quaternion);\n }\n\n const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin\n //Incremented as we iterate through the bins\n\n const xreset = xmin + binsizeX * 0.5 - bi.position.x;\n const yreset = ymin + binsizeY * 0.5 - bi.position.y;\n const zreset = zmin + binsizeZ * 0.5 - bi.position.z;\n const d = GridBroadphase_collisionPairs_d;\n d.set(xreset, yreset, zreset);\n\n for (let xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {\n for (let yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {\n for (let zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {\n if (d.dot(planeNormal) < binRadius) {\n const idx = xoff + yoff + zoff;\n bins[idx][binLengths[idx]++] = bi;\n }\n }\n }\n }\n\n break;\n }\n\n default:\n {\n if (bi.aabbNeedsUpdate) {\n bi.updateAABB();\n }\n\n addBoxToBins(bi.aabb.lowerBound.x, bi.aabb.lowerBound.y, bi.aabb.lowerBound.z, bi.aabb.upperBound.x, bi.aabb.upperBound.y, bi.aabb.upperBound.z, bi);\n break;\n }\n }\n } // Check each bin\n\n\n for (let i = 0; i !== Nbins; i++) {\n const binLength = binLengths[i]; //Skip bins with no potential collisions\n\n if (binLength > 1) {\n const bin = bins[i]; // Do N^2 broadphase inside\n\n for (let xi = 0; xi !== binLength; xi++) {\n const bi = bin[xi];\n\n for (let yi = 0; yi !== xi; yi++) {\n const bj = bin[yi];\n\n if (this.needBroadphaseCollision(bi, bj)) {\n this.intersectionTest(bi, bj, pairs1, pairs2);\n }\n }\n }\n }\n } //\tfor (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {\n //\t\tconsole.log(\"layer \"+zi);\n //\t\tfor (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {\n //\t\t\tconst row = '';\n //\t\t\tfor (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {\n //\t\t\t\tconst idx = xoff + yoff + zoff;\n //\t\t\t\trow += ' ' + binLengths[idx];\n //\t\t\t}\n //\t\t\tconsole.log(row);\n //\t\t}\n //\t}\n\n\n this.makePairsUnique(pairs1, pairs2);\n }\n\n}\nconst GridBroadphase_collisionPairs_d = new Vec3();\nnew Vec3();\n\n/**\n * Naive broadphase implementation, used in lack of better ones.\n *\n * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_\n */\nclass NaiveBroadphase extends Broadphase {\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n super();\n }\n /**\n * Get all the collision pairs in the physics world\n */\n\n\n collisionPairs(world, pairs1, pairs2) {\n const bodies = world.bodies;\n const n = bodies.length;\n let bi;\n let bj; // Naive N^2 ftw!\n\n for (let i = 0; i !== n; i++) {\n for (let j = 0; j !== i; j++) {\n bi = bodies[i];\n bj = bodies[j];\n\n if (!this.needBroadphaseCollision(bi, bj)) {\n continue;\n }\n\n this.intersectionTest(bi, bj, pairs1, pairs2);\n }\n }\n }\n /**\n * Returns all the bodies within an AABB.\n * @param result An array to store resulting bodies in.\n */\n\n\n aabbQuery(world, aabb, result) {\n if (result === void 0) {\n result = [];\n }\n\n for (let i = 0; i < world.bodies.length; i++) {\n const b = world.bodies[i];\n\n if (b.aabbNeedsUpdate) {\n b.updateAABB();\n } // Ugly hack until Body gets aabb\n\n\n if (b.aabb.overlaps(aabb)) {\n result.push(b);\n }\n }\n\n return result;\n }\n\n}\n\n/**\n * Storage for Ray casting data\n */\nclass RaycastResult {\n /**\n * rayFromWorld\n */\n\n /**\n * rayToWorld\n */\n\n /**\n * hitNormalWorld\n */\n\n /**\n * hitPointWorld\n */\n\n /**\n * hasHit\n */\n\n /**\n * shape\n */\n\n /**\n * body\n */\n\n /**\n * The index of the hit triangle, if the hit shape was a trimesh\n */\n\n /**\n * Distance to the hit. Will be set to -1 if there was no hit\n */\n\n /**\n * If the ray should stop traversing the bodies\n */\n constructor() {\n this.rayFromWorld = new Vec3();\n this.rayToWorld = new Vec3();\n this.hitNormalWorld = new Vec3();\n this.hitPointWorld = new Vec3();\n this.hasHit = false;\n this.shape = null;\n this.body = null;\n this.hitFaceIndex = -1;\n this.distance = -1;\n this.shouldStop = false;\n }\n /**\n * Reset all result data.\n */\n\n\n reset() {\n this.rayFromWorld.setZero();\n this.rayToWorld.setZero();\n this.hitNormalWorld.setZero();\n this.hitPointWorld.setZero();\n this.hasHit = false;\n this.shape = null;\n this.body = null;\n this.hitFaceIndex = -1;\n this.distance = -1;\n this.shouldStop = false;\n }\n /**\n * abort\n */\n\n\n abort() {\n this.shouldStop = true;\n }\n /**\n * Set result data.\n */\n\n\n set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {\n this.rayFromWorld.copy(rayFromWorld);\n this.rayToWorld.copy(rayToWorld);\n this.hitNormalWorld.copy(hitNormalWorld);\n this.hitPointWorld.copy(hitPointWorld);\n this.shape = shape;\n this.body = body;\n this.distance = distance;\n }\n\n}\n\nlet _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;\n\n/**\n * RAY_MODES\n */\nconst RAY_MODES = {\n /** CLOSEST */\n CLOSEST: 1,\n\n /** ANY */\n ANY: 2,\n\n /** ALL */\n ALL: 4\n};\n/**\n * RayMode\n */\n\n_Shape$types$SPHERE = Shape.types.SPHERE;\n_Shape$types$PLANE = Shape.types.PLANE;\n_Shape$types$BOX = Shape.types.BOX;\n_Shape$types$CYLINDER = Shape.types.CYLINDER;\n_Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;\n_Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;\n_Shape$types$TRIMESH = Shape.types.TRIMESH;\n\n/**\n * A line in 3D space that intersects bodies and return points.\n */\nclass Ray {\n /**\n * from\n */\n\n /**\n * to\n */\n\n /**\n * direction\n */\n\n /**\n * The precision of the ray. Used when checking parallelity etc.\n * @default 0.0001\n */\n\n /**\n * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.\n * @default true\n */\n\n /**\n * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.\n * @default false\n */\n\n /**\n * collisionFilterMask\n * @default -1\n */\n\n /**\n * collisionFilterGroup\n * @default -1\n */\n\n /**\n * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.\n * @default RAY.ANY\n */\n\n /**\n * Current result object.\n */\n\n /**\n * Will be set to `true` during intersectWorld() if the ray hit anything.\n */\n\n /**\n * User-provided result callback. Will be used if mode is Ray.ALL.\n */\n\n /**\n * CLOSEST\n */\n\n /**\n * ANY\n */\n\n /**\n * ALL\n */\n get [_Shape$types$SPHERE]() {\n return this._intersectSphere;\n }\n\n get [_Shape$types$PLANE]() {\n return this._intersectPlane;\n }\n\n get [_Shape$types$BOX]() {\n return this._intersectBox;\n }\n\n get [_Shape$types$CYLINDER]() {\n return this._intersectConvex;\n }\n\n get [_Shape$types$CONVEXPO]() {\n return this._intersectConvex;\n }\n\n get [_Shape$types$HEIGHTFI]() {\n return this._intersectHeightfield;\n }\n\n get [_Shape$types$TRIMESH]() {\n return this._intersectTrimesh;\n }\n\n constructor(from, to) {\n if (from === void 0) {\n from = new Vec3();\n }\n\n if (to === void 0) {\n to = new Vec3();\n }\n\n this.from = from.clone();\n this.to = to.clone();\n this.direction = new Vec3();\n this.precision = 0.0001;\n this.checkCollisionResponse = true;\n this.skipBackfaces = false;\n this.collisionFilterMask = -1;\n this.collisionFilterGroup = -1;\n this.mode = Ray.ANY;\n this.result = new RaycastResult();\n this.hasHit = false;\n\n this.callback = result => {};\n }\n /**\n * Do itersection against all bodies in the given World.\n * @return True if the ray hit anything, otherwise false.\n */\n\n\n intersectWorld(world, options) {\n this.mode = options.mode || Ray.ANY;\n this.result = options.result || new RaycastResult();\n this.skipBackfaces = !!options.skipBackfaces;\n this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;\n this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;\n this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;\n\n if (options.from) {\n this.from.copy(options.from);\n }\n\n if (options.to) {\n this.to.copy(options.to);\n }\n\n this.callback = options.callback || (() => {});\n\n this.hasHit = false;\n this.result.reset();\n this.updateDirection();\n this.getAABB(tmpAABB$1);\n tmpArray.length = 0;\n world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);\n this.intersectBodies(tmpArray);\n return this.hasHit;\n }\n /**\n * Shoot a ray at a body, get back information about the hit.\n * @deprecated @param result set the result property of the Ray instead.\n */\n\n\n intersectBody(body, result) {\n if (result) {\n this.result = result;\n this.updateDirection();\n }\n\n const checkCollisionResponse = this.checkCollisionResponse;\n\n if (checkCollisionResponse && !body.collisionResponse) {\n return;\n }\n\n if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {\n return;\n }\n\n const xi = intersectBody_xi;\n const qi = intersectBody_qi;\n\n for (let i = 0, N = body.shapes.length; i < N; i++) {\n const shape = body.shapes[i];\n\n if (checkCollisionResponse && !shape.collisionResponse) {\n continue; // Skip\n }\n\n body.quaternion.mult(body.shapeOrientations[i], qi);\n body.quaternion.vmult(body.shapeOffsets[i], xi);\n xi.vadd(body.position, xi);\n this.intersectShape(shape, qi, xi, body);\n\n if (this.result.shouldStop) {\n break;\n }\n }\n }\n /**\n * Shoot a ray at an array bodies, get back information about the hit.\n * @param bodies An array of Body objects.\n * @deprecated @param result set the result property of the Ray instead.\n *\n */\n\n\n intersectBodies(bodies, result) {\n if (result) {\n this.result = result;\n this.updateDirection();\n }\n\n for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {\n this.intersectBody(bodies[i]);\n }\n }\n /**\n * Updates the direction vector.\n */\n\n\n updateDirection() {\n this.to.vsub(this.from, this.direction);\n this.direction.normalize();\n }\n\n intersectShape(shape, quat, position, body) {\n const from = this.from; // Checking boundingSphere\n\n const distance = distanceFromIntersection(from, this.direction, position);\n\n if (distance > shape.boundingSphereRadius) {\n return;\n }\n\n const intersectMethod = this[shape.type];\n\n if (intersectMethod) {\n intersectMethod.call(this, shape, quat, position, body, shape);\n }\n }\n\n _intersectBox(box, quat, position, body, reportedShape) {\n return this._intersectConvex(box.convexPolyhedronRepresentation, quat, position, body, reportedShape);\n }\n\n _intersectPlane(shape, quat, position, body, reportedShape) {\n const from = this.from;\n const to = this.to;\n const direction = this.direction; // Get plane normal\n\n const worldNormal = new Vec3(0, 0, 1);\n quat.vmult(worldNormal, worldNormal);\n const len = new Vec3();\n from.vsub(position, len);\n const planeToFrom = len.dot(worldNormal);\n to.vsub(position, len);\n const planeToTo = len.dot(worldNormal);\n\n if (planeToFrom * planeToTo > 0) {\n // \"from\" and \"to\" are on the same side of the plane... bail out\n return;\n }\n\n if (from.distanceTo(to) < planeToFrom) {\n return;\n }\n\n const n_dot_dir = worldNormal.dot(direction);\n\n if (Math.abs(n_dot_dir) < this.precision) {\n // No intersection\n return;\n }\n\n const planePointToFrom = new Vec3();\n const dir_scaled_with_t = new Vec3();\n const hitPointWorld = new Vec3();\n from.vsub(position, planePointToFrom);\n const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;\n direction.scale(t, dir_scaled_with_t);\n from.vadd(dir_scaled_with_t, hitPointWorld);\n this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);\n }\n /**\n * Get the world AABB of the ray.\n */\n\n\n getAABB(aabb) {\n const {\n lowerBound,\n upperBound\n } = aabb;\n const to = this.to;\n const from = this.from;\n lowerBound.x = Math.min(to.x, from.x);\n lowerBound.y = Math.min(to.y, from.y);\n lowerBound.z = Math.min(to.z, from.z);\n upperBound.x = Math.max(to.x, from.x);\n upperBound.y = Math.max(to.y, from.y);\n upperBound.z = Math.max(to.z, from.z);\n }\n\n _intersectHeightfield(shape, quat, position, body, reportedShape) {\n shape.data;\n shape.elementSize; // Convert the ray to local heightfield coordinates\n\n const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);\n\n localRay.from.copy(this.from);\n localRay.to.copy(this.to);\n Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);\n Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);\n localRay.updateDirection(); // Get the index of the data points to test against\n\n const index = intersectHeightfield_index;\n let iMinX;\n let iMinY;\n let iMaxX;\n let iMaxY; // Set to max\n\n iMinX = iMinY = 0;\n iMaxX = iMaxY = shape.data.length - 1;\n const aabb = new AABB();\n localRay.getAABB(aabb);\n shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);\n iMinX = Math.max(iMinX, index[0]);\n iMinY = Math.max(iMinY, index[1]);\n shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);\n iMaxX = Math.min(iMaxX, index[0] + 1);\n iMaxY = Math.min(iMaxY, index[1] + 1);\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n if (this.result.shouldStop) {\n return;\n }\n\n shape.getAabbAtIndex(i, j, aabb);\n\n if (!aabb.overlapsRay(localRay)) {\n continue;\n } // Lower triangle\n\n\n shape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);\n\n this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);\n\n if (this.result.shouldStop) {\n return;\n } // Upper triangle\n\n\n shape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);\n\n this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);\n }\n }\n }\n\n _intersectSphere(sphere, quat, position, body, reportedShape) {\n const from = this.from;\n const to = this.to;\n const r = sphere.radius;\n const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;\n const b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));\n const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;\n const delta = b ** 2 - 4 * a * c;\n const intersectionPoint = Ray_intersectSphere_intersectionPoint;\n const normal = Ray_intersectSphere_normal;\n\n if (delta < 0) {\n // No intersection\n return;\n } else if (delta === 0) {\n // single intersection point\n from.lerp(to, delta, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n } else {\n const d1 = (-b - Math.sqrt(delta)) / (2 * a);\n const d2 = (-b + Math.sqrt(delta)) / (2 * a);\n\n if (d1 >= 0 && d1 <= 1) {\n from.lerp(to, d1, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n }\n\n if (this.result.shouldStop) {\n return;\n }\n\n if (d2 >= 0 && d2 <= 1) {\n from.lerp(to, d2, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n }\n }\n }\n\n _intersectConvex(shape, quat, position, body, reportedShape, options) {\n intersectConvex_minDistNormal;\n const normal = intersectConvex_normal;\n const vector = intersectConvex_vector;\n intersectConvex_minDistIntersect;\n const faceList = options && options.faceList || null; // Checking faces\n\n const faces = shape.faces;\n const vertices = shape.vertices;\n const normals = shape.faceNormals;\n const direction = this.direction;\n const from = this.from;\n const to = this.to;\n const fromToDistance = from.distanceTo(to);\n const Nfaces = faceList ? faceList.length : faces.length;\n const result = this.result;\n\n for (let j = 0; !result.shouldStop && j < Nfaces; j++) {\n const fi = faceList ? faceList[j] : j;\n const face = faces[fi];\n const faceNormal = normals[fi];\n const q = quat;\n const x = position; // determine if ray intersects the plane of the face\n // note: this works regardless of the direction of the face normal\n // Get plane point in world coordinates...\n\n vector.copy(vertices[face[0]]);\n q.vmult(vector, vector);\n vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.\n\n vector.vsub(from, vector); // Get plane normal\n\n q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting\n\n const dot = direction.dot(normal); // Bail out if ray and plane are parallel\n\n if (Math.abs(dot) < this.precision) {\n continue;\n } // calc distance to plane\n\n\n const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray\n\n if (scalar < 0) {\n continue;\n } // if (dot < 0) {\n // Intersection point is from + direction * scalar\n\n\n direction.scale(scalar, intersectPoint);\n intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.\n\n a.copy(vertices[face[0]]);\n q.vmult(a, a);\n x.vadd(a, a);\n\n for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {\n // Transform 3 vertices to world coords\n b.copy(vertices[face[i]]);\n c.copy(vertices[face[i + 1]]);\n q.vmult(b, b);\n q.vmult(c, c);\n x.vadd(b, b);\n x.vadd(c, c);\n const distance = intersectPoint.distanceTo(from);\n\n if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {\n continue;\n }\n\n this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);\n } // }\n\n }\n }\n /**\n * @todo Optimize by transforming the world to local space first.\n * @todo Use Octree lookup\n */\n\n\n _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {\n const normal = intersectTrimesh_normal;\n const triangles = intersectTrimesh_triangles;\n const treeTransform = intersectTrimesh_treeTransform;\n const vector = intersectConvex_vector;\n const localDirection = intersectTrimesh_localDirection;\n const localFrom = intersectTrimesh_localFrom;\n const localTo = intersectTrimesh_localTo;\n const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;\n const worldNormal = intersectTrimesh_worldNormal; // Checking faces\n\n const indices = mesh.indices;\n mesh.vertices; // const normals = mesh.faceNormals\n\n const from = this.from;\n const to = this.to;\n const direction = this.direction;\n treeTransform.position.copy(position);\n treeTransform.quaternion.copy(quat); // Transform ray to local space!\n\n Transform.vectorToLocalFrame(position, quat, direction, localDirection);\n Transform.pointToLocalFrame(position, quat, from, localFrom);\n Transform.pointToLocalFrame(position, quat, to, localTo);\n localTo.x *= mesh.scale.x;\n localTo.y *= mesh.scale.y;\n localTo.z *= mesh.scale.z;\n localFrom.x *= mesh.scale.x;\n localFrom.y *= mesh.scale.y;\n localFrom.z *= mesh.scale.z;\n localTo.vsub(localFrom, localDirection);\n localDirection.normalize();\n const fromToDistanceSquared = localFrom.distanceSquared(localTo);\n mesh.tree.rayQuery(this, treeTransform, triangles);\n\n for (let i = 0, N = triangles.length; !this.result.shouldStop && i !== N; i++) {\n const trianglesIndex = triangles[i];\n mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face\n // note: this works regardless of the direction of the face normal\n // Get plane point in world coordinates...\n\n mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.\n\n a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting\n\n const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel\n // if (Math.abs( dot ) < this.precision){\n // continue;\n // }\n // calc distance to plane\n\n const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray\n\n if (scalar < 0) {\n continue;\n } // Intersection point is from + direction * scalar\n\n\n localDirection.scale(scalar, intersectPoint);\n intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices\n\n mesh.getVertex(indices[trianglesIndex * 3 + 1], b);\n mesh.getVertex(indices[trianglesIndex * 3 + 2], c);\n const squaredDistance = intersectPoint.distanceSquared(localFrom);\n\n if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {\n continue;\n } // transform intersectpoint and normal to world\n\n\n Transform.vectorToWorldFrame(quat, normal, worldNormal);\n Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);\n this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);\n }\n\n triangles.length = 0;\n }\n /**\n * @return True if the intersections should continue\n */\n\n\n reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {\n const from = this.from;\n const to = this.to;\n const distance = from.distanceTo(hitPointWorld);\n const result = this.result; // Skip back faces?\n\n if (this.skipBackfaces && normal.dot(this.direction) > 0) {\n return;\n }\n\n result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;\n\n switch (this.mode) {\n case Ray.ALL:\n this.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n result.hasHit = true;\n this.callback(result);\n break;\n\n case Ray.CLOSEST:\n // Store if closer than current closest\n if (distance < result.distance || !result.hasHit) {\n this.hasHit = true;\n result.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n }\n\n break;\n\n case Ray.ANY:\n // Report and stop.\n this.hasHit = true;\n result.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n result.shouldStop = true;\n break;\n }\n }\n /**\n * As per \"Barycentric Technique\" as named\n * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division\n */\n\n\n static pointInTriangle(p, a, b, c) {\n c.vsub(a, v0);\n b.vsub(a, v1);\n p.vsub(a, v2);\n const dot00 = v0.dot(v0);\n const dot01 = v0.dot(v1);\n const dot02 = v0.dot(v2);\n const dot11 = v1.dot(v1);\n const dot12 = v1.dot(v2);\n let u;\n let v;\n return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;\n }\n\n}\nRay.CLOSEST = RAY_MODES.CLOSEST;\nRay.ANY = RAY_MODES.ANY;\nRay.ALL = RAY_MODES.ALL;\nconst tmpAABB$1 = new AABB();\nconst tmpArray = [];\nconst v1 = new Vec3();\nconst v2 = new Vec3();\nconst intersectBody_xi = new Vec3();\nconst intersectBody_qi = new Quaternion();\nconst intersectPoint = new Vec3();\nconst a = new Vec3();\nconst b = new Vec3();\nconst c = new Vec3();\nnew Vec3();\nnew RaycastResult();\nconst intersectConvexOptions = {\n faceList: [0]\n};\nconst worldPillarOffset = new Vec3();\nconst intersectHeightfield_localRay = new Ray();\nconst intersectHeightfield_index = [];\nconst Ray_intersectSphere_intersectionPoint = new Vec3();\nconst Ray_intersectSphere_normal = new Vec3();\nconst intersectConvex_normal = new Vec3();\nconst intersectConvex_minDistNormal = new Vec3();\nconst intersectConvex_minDistIntersect = new Vec3();\nconst intersectConvex_vector = new Vec3();\nconst intersectTrimesh_normal = new Vec3();\nconst intersectTrimesh_localDirection = new Vec3();\nconst intersectTrimesh_localFrom = new Vec3();\nconst intersectTrimesh_localTo = new Vec3();\nconst intersectTrimesh_worldNormal = new Vec3();\nconst intersectTrimesh_worldIntersectPoint = new Vec3();\nnew AABB();\nconst intersectTrimesh_triangles = [];\nconst intersectTrimesh_treeTransform = new Transform();\nconst v0 = new Vec3();\nconst intersect = new Vec3();\n\nfunction distanceFromIntersection(from, direction, position) {\n // v0 is vector from from to position\n position.vsub(from, v0);\n const dot = v0.dot(direction); // intersect = direction*dot + from\n\n direction.scale(dot, intersect);\n intersect.vadd(from, intersect);\n const distance = position.distanceTo(intersect);\n return distance;\n}\n\n/**\n * Sweep and prune broadphase along one axis.\n */\nclass SAPBroadphase extends Broadphase {\n /**\n * List of bodies currently in the broadphase.\n */\n\n /**\n * The world to search in.\n */\n\n /**\n * Axis to sort the bodies along.\n * Set to 0 for x axis, and 1 for y axis.\n * For best performance, pick the axis where bodies are most distributed.\n */\n\n /**\n * Check if the bounds of two bodies overlap, along the given SAP axis.\n */\n static checkBounds(bi, bj, axisIndex) {\n let biPos;\n let bjPos;\n\n if (axisIndex === 0) {\n biPos = bi.position.x;\n bjPos = bj.position.x;\n } else if (axisIndex === 1) {\n biPos = bi.position.y;\n bjPos = bj.position.y;\n } else if (axisIndex === 2) {\n biPos = bi.position.z;\n bjPos = bj.position.z;\n }\n\n const ri = bi.boundingRadius,\n rj = bj.boundingRadius,\n boundA2 = biPos + ri,\n boundB1 = bjPos - rj;\n return boundB1 < boundA2;\n } // Note: these are identical, save for x/y/z lowerbound\n\n /**\n * insertionSortX\n */\n\n\n static insertionSortX(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n /**\n * insertionSortY\n */\n\n\n static insertionSortY(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n /**\n * insertionSortZ\n */\n\n\n static insertionSortZ(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n\n constructor(world) {\n super();\n this.axisList = [];\n this.world = null;\n this.axisIndex = 0;\n const axisList = this.axisList;\n\n this._addBodyHandler = event => {\n axisList.push(event.body);\n };\n\n this._removeBodyHandler = event => {\n const idx = axisList.indexOf(event.body);\n\n if (idx !== -1) {\n axisList.splice(idx, 1);\n }\n };\n\n if (world) {\n this.setWorld(world);\n }\n }\n /**\n * Change the world\n */\n\n\n setWorld(world) {\n // Clear the old axis array\n this.axisList.length = 0; // Add all bodies from the new world\n\n for (let i = 0; i < world.bodies.length; i++) {\n this.axisList.push(world.bodies[i]);\n } // Remove old handlers, if any\n\n\n world.removeEventListener('addBody', this._addBodyHandler);\n world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.\n\n world.addEventListener('addBody', this._addBodyHandler);\n world.addEventListener('removeBody', this._removeBodyHandler);\n this.world = world;\n this.dirty = true;\n }\n /**\n * Collect all collision pairs\n */\n\n\n collisionPairs(world, p1, p2) {\n const bodies = this.axisList;\n const N = bodies.length;\n const axisIndex = this.axisIndex;\n let i;\n let j;\n\n if (this.dirty) {\n this.sortList();\n this.dirty = false;\n } // Look through the list\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n for (j = i + 1; j < N; j++) {\n const bj = bodies[j];\n\n if (!this.needBroadphaseCollision(bi, bj)) {\n continue;\n }\n\n if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {\n break;\n }\n\n this.intersectionTest(bi, bj, p1, p2);\n }\n }\n }\n\n sortList() {\n const axisList = this.axisList;\n const axisIndex = this.axisIndex;\n const N = axisList.length; // Update AABBs\n\n for (let i = 0; i !== N; i++) {\n const bi = axisList[i];\n\n if (bi.aabbNeedsUpdate) {\n bi.updateAABB();\n }\n } // Sort the list\n\n\n if (axisIndex === 0) {\n SAPBroadphase.insertionSortX(axisList);\n } else if (axisIndex === 1) {\n SAPBroadphase.insertionSortY(axisList);\n } else if (axisIndex === 2) {\n SAPBroadphase.insertionSortZ(axisList);\n }\n }\n /**\n * Computes the variance of the body positions and estimates the best axis to use.\n * Will automatically set property `axisIndex`.\n */\n\n\n autoDetectAxis() {\n let sumX = 0;\n let sumX2 = 0;\n let sumY = 0;\n let sumY2 = 0;\n let sumZ = 0;\n let sumZ2 = 0;\n const bodies = this.axisList;\n const N = bodies.length;\n const invN = 1 / N;\n\n for (let i = 0; i !== N; i++) {\n const b = bodies[i];\n const centerX = b.position.x;\n sumX += centerX;\n sumX2 += centerX * centerX;\n const centerY = b.position.y;\n sumY += centerY;\n sumY2 += centerY * centerY;\n const centerZ = b.position.z;\n sumZ += centerZ;\n sumZ2 += centerZ * centerZ;\n }\n\n const varianceX = sumX2 - sumX * sumX * invN;\n const varianceY = sumY2 - sumY * sumY * invN;\n const varianceZ = sumZ2 - sumZ * sumZ * invN;\n\n if (varianceX > varianceY) {\n if (varianceX > varianceZ) {\n this.axisIndex = 0;\n } else {\n this.axisIndex = 2;\n }\n } else if (varianceY > varianceZ) {\n this.axisIndex = 1;\n } else {\n this.axisIndex = 2;\n }\n }\n /**\n * Returns all the bodies within an AABB.\n * @param result An array to store resulting bodies in.\n */\n\n\n aabbQuery(world, aabb, result) {\n if (result === void 0) {\n result = [];\n }\n\n if (this.dirty) {\n this.sortList();\n this.dirty = false;\n }\n\n const axisIndex = this.axisIndex;\n let axis = 'x';\n\n if (axisIndex === 1) {\n axis = 'y';\n }\n\n if (axisIndex === 2) {\n axis = 'z';\n }\n\n const axisList = this.axisList;\n aabb.lowerBound[axis];\n aabb.upperBound[axis];\n\n for (let i = 0; i < axisList.length; i++) {\n const b = axisList[i];\n\n if (b.aabbNeedsUpdate) {\n b.updateAABB();\n }\n\n if (b.aabb.overlaps(aabb)) {\n result.push(b);\n }\n }\n\n return result;\n }\n\n}\n\nclass Utils {\n /**\n * Extend an options object with default values.\n * @param options The options object. May be falsy: in this case, a new object is created and returned.\n * @param defaults An object containing default values.\n * @return The modified options object.\n */\n static defaults(options, defaults) {\n if (options === void 0) {\n options = {};\n }\n\n for (let key in defaults) {\n if (!(key in options)) {\n options[key] = defaults[key];\n }\n }\n\n return options;\n }\n\n}\n\n/**\n * Constraint base class\n */\nclass Constraint {\n /**\n * Equations to be solved in this constraint.\n */\n\n /**\n * Body A.\n */\n\n /**\n * Body B.\n */\n\n /**\n * Set to false if you don't want the bodies to collide when they are connected.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n collideConnected: true,\n wakeUpBodies: true\n });\n this.equations = [];\n this.bodyA = bodyA;\n this.bodyB = bodyB;\n this.id = Constraint.idCounter++;\n this.collideConnected = options.collideConnected;\n\n if (options.wakeUpBodies) {\n if (bodyA) {\n bodyA.wakeUp();\n }\n\n if (bodyB) {\n bodyB.wakeUp();\n }\n }\n }\n /**\n * Update all the equations with data.\n */\n\n\n update() {\n throw new Error('method update() not implmemented in this Constraint subclass!');\n }\n /**\n * Enables all equations in the constraint.\n */\n\n\n enable() {\n const eqs = this.equations;\n\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = true;\n }\n }\n /**\n * Disables all equations in the constraint.\n */\n\n\n disable() {\n const eqs = this.equations;\n\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = false;\n }\n }\n\n}\nConstraint.idCounter = 0;\n\n/**\n * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.\n */\n\nclass JacobianElement {\n /**\n * spatial\n */\n\n /**\n * rotational\n */\n constructor() {\n this.spatial = new Vec3();\n this.rotational = new Vec3();\n }\n /**\n * Multiply with other JacobianElement\n */\n\n\n multiplyElement(element) {\n return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);\n }\n /**\n * Multiply with two vectors\n */\n\n\n multiplyVectors(spatial, rotational) {\n return spatial.dot(this.spatial) + rotational.dot(this.rotational);\n }\n\n}\n\n/**\n * Equation base class.\n *\n * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation.\n */\nclass Equation {\n /**\n * Minimum (read: negative max) force to be applied by the constraint.\n */\n\n /**\n * Maximum (read: positive max) force to be applied by the constraint.\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * A number, proportional to the force added to the bodies.\n */\n constructor(bi, bj, minForce, maxForce) {\n if (minForce === void 0) {\n minForce = -1e6;\n }\n\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n this.id = Equation.idCounter++;\n this.minForce = minForce;\n this.maxForce = maxForce;\n this.bi = bi;\n this.bj = bj;\n this.a = 0.0; // SPOOK parameter\n\n this.b = 0.0; // SPOOK parameter\n\n this.eps = 0.0; // SPOOK parameter\n\n this.jacobianElementA = new JacobianElement();\n this.jacobianElementB = new JacobianElement();\n this.enabled = true;\n this.multiplier = 0;\n this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params\n }\n /**\n * Recalculates a, b, and eps.\n *\n * The Equation constructor sets typical SPOOK parameters as such:\n * * `stiffness` = 1e7\n * * `relaxation` = 4\n * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._\n */\n\n\n setSpookParams(stiffness, relaxation, timeStep) {\n const d = relaxation;\n const k = stiffness;\n const h = timeStep;\n this.a = 4.0 / (h * (1 + 4 * d));\n this.b = 4.0 * d / (1 + 4 * d);\n this.eps = 4.0 / (h * h * k * (1 + 4 * d));\n }\n /**\n * Computes the right hand side of the SPOOK equation\n */\n\n\n computeB(a, b, h) {\n const GW = this.computeGW();\n const Gq = this.computeGq();\n const GiMf = this.computeGiMf();\n return -Gq * a - GW * b - GiMf * h;\n }\n /**\n * Computes G*q, where q are the generalized body coordinates\n */\n\n\n computeGq() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const xi = bi.position;\n const xj = bj.position;\n return GA.spatial.dot(xi) + GB.spatial.dot(xj);\n }\n /**\n * Computes G*W, where W are the body velocities\n */\n\n\n computeGW() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const vi = bi.velocity;\n const vj = bj.velocity;\n const wi = bi.angularVelocity;\n const wj = bj.angularVelocity;\n return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);\n }\n /**\n * Computes G*Wlambda, where W are the body velocities\n */\n\n\n computeGWlambda() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const vi = bi.vlambda;\n const vj = bj.vlambda;\n const wi = bi.wlambda;\n const wj = bj.wlambda;\n return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);\n }\n /**\n * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.\n */\n\n\n computeGiMf() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const fi = bi.force;\n const ti = bi.torque;\n const fj = bj.force;\n const tj = bj.torque;\n const invMassi = bi.invMassSolve;\n const invMassj = bj.invMassSolve;\n fi.scale(invMassi, iMfi);\n fj.scale(invMassj, iMfj);\n bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);\n bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);\n return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);\n }\n /**\n * Computes G*inv(M)*G'\n */\n\n\n computeGiMGt() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const invMassi = bi.invMassSolve;\n const invMassj = bj.invMassSolve;\n const invIi = bi.invInertiaWorldSolve;\n const invIj = bj.invInertiaWorldSolve;\n let result = invMassi + invMassj;\n invIi.vmult(GA.rotational, tmp);\n result += tmp.dot(GA.rotational);\n invIj.vmult(GB.rotational, tmp);\n result += tmp.dot(GB.rotational);\n return result;\n }\n /**\n * Add constraint velocity to the bodies.\n */\n\n\n addToWlambda(deltalambda) {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const temp = addToWlambda_temp; // Add to linear velocity\n // v_lambda += inv(M) * delta_lamba * G\n\n bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);\n bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity\n\n bi.invInertiaWorldSolve.vmult(GA.rotational, temp);\n bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);\n bj.invInertiaWorldSolve.vmult(GB.rotational, temp);\n bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);\n }\n /**\n * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps\n */\n\n\n computeC() {\n return this.computeGiMGt() + this.eps;\n }\n\n}\nEquation.idCounter = 0;\nconst iMfi = new Vec3();\nconst iMfj = new Vec3();\nconst invIi_vmult_taui = new Vec3();\nconst invIj_vmult_tauj = new Vec3();\nconst tmp = new Vec3();\nconst addToWlambda_temp = new Vec3();\n\n/**\n * Contact/non-penetration constraint equation\n */\nclass ContactEquation extends Equation {\n /**\n * \"bounciness\": u1 = -e*u0\n */\n\n /**\n * World-oriented vector that goes from the center of bi to the contact point.\n */\n\n /**\n * World-oriented vector that starts in body j position and goes to the contact point.\n */\n\n /**\n * Contact normal, pointing out of body i.\n */\n constructor(bodyA, bodyB, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB, 0, maxForce);\n this.restitution = 0.0;\n this.ri = new Vec3();\n this.rj = new Vec3();\n this.ni = new Vec3();\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const bi = this.bi;\n const bj = this.bj;\n const ri = this.ri;\n const rj = this.rj;\n const rixn = ContactEquation_computeB_temp1;\n const rjxn = ContactEquation_computeB_temp2;\n const vi = bi.velocity;\n const wi = bi.angularVelocity;\n bi.force;\n bi.torque;\n const vj = bj.velocity;\n const wj = bj.angularVelocity;\n bj.force;\n bj.torque;\n const penetrationVec = ContactEquation_computeB_temp3;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const n = this.ni; // Caluclate cross products\n\n ri.cross(n, rixn);\n rj.cross(n, rjxn); // g = xj+rj -(xi+ri)\n // G = [ -ni -rixn ni rjxn ]\n\n n.negate(GA.spatial);\n rixn.negate(GA.rotational);\n GB.spatial.copy(n);\n GB.rotational.copy(rjxn); // Calculate the penetration vector\n\n penetrationVec.copy(bj.position);\n penetrationVec.vadd(rj, penetrationVec);\n penetrationVec.vsub(bi.position, penetrationVec);\n penetrationVec.vsub(ri, penetrationVec);\n const g = n.dot(penetrationVec); // Compute iteration\n\n const ePlusOne = this.restitution + 1;\n const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n /**\n * Get the current relative velocity in the contact point.\n */\n\n\n getImpactVelocityAlongNormal() {\n const vi = ContactEquation_getImpactVelocityAlongNormal_vi;\n const vj = ContactEquation_getImpactVelocityAlongNormal_vj;\n const xi = ContactEquation_getImpactVelocityAlongNormal_xi;\n const xj = ContactEquation_getImpactVelocityAlongNormal_xj;\n const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;\n this.bi.position.vadd(this.ri, xi);\n this.bj.position.vadd(this.rj, xj);\n this.bi.getVelocityAtWorldPoint(xi, vi);\n this.bj.getVelocityAtWorldPoint(xj, vj);\n vi.vsub(vj, relVel);\n return this.ni.dot(relVel);\n }\n\n}\nconst ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors\n\nconst ContactEquation_computeB_temp2 = new Vec3();\nconst ContactEquation_computeB_temp3 = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();\n\n/**\n * Connects two bodies at given offset points.\n * @example\n * const bodyA = new Body({ mass: 1 })\n * const bodyB = new Body({ mass: 1 })\n * bodyA.position.set(-1, 0, 0)\n * bodyB.position.set(1, 0, 0)\n * bodyA.addShape(shapeA)\n * bodyB.addShape(shapeB)\n * world.addBody(bodyA)\n * world.addBody(bodyB)\n * const localPivotA = new Vec3(1, 0, 0)\n * const localPivotB = new Vec3(-1, 0, 0)\n * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)\n * world.addConstraint(constraint)\n */\nclass PointToPointConstraint extends Constraint {\n /**\n * Pivot, defined locally in bodyA.\n */\n\n /**\n * Pivot, defined locally in bodyB.\n */\n\n /**\n * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.\n * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.\n * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.\n * @param maxForce The maximum force that should be applied to constrain the bodies.\n */\n constructor(bodyA, pivotA, bodyB, pivotB, maxForce) {\n if (pivotA === void 0) {\n pivotA = new Vec3();\n }\n\n if (pivotB === void 0) {\n pivotB = new Vec3();\n }\n\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB);\n this.pivotA = pivotA.clone();\n this.pivotB = pivotB.clone();\n const x = this.equationX = new ContactEquation(bodyA, bodyB);\n const y = this.equationY = new ContactEquation(bodyA, bodyB);\n const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver\n\n this.equations.push(x, y, z); // Make the equations bidirectional\n\n x.minForce = y.minForce = z.minForce = -maxForce;\n x.maxForce = y.maxForce = z.maxForce = maxForce;\n x.ni.set(1, 0, 0);\n y.ni.set(0, 1, 0);\n z.ni.set(0, 0, 1);\n }\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const x = this.equationX;\n const y = this.equationY;\n const z = this.equationZ; // Rotate the pivots to world space\n\n bodyA.quaternion.vmult(this.pivotA, x.ri);\n bodyB.quaternion.vmult(this.pivotB, x.rj);\n y.ri.copy(x.ri);\n y.rj.copy(x.rj);\n z.ri.copy(x.ri);\n z.rj.copy(x.rj);\n }\n\n}\n\n/**\n * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.\n */\nclass ConeEquation extends Equation {\n /**\n * Local axis in A\n */\n\n /**\n * Local axis in B\n */\n\n /**\n * The \"cone angle\" to keep\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);\n this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const ni = this.axisA;\n const nj = this.axisB;\n const nixnj = tmpVec1$2;\n const njxni = tmpVec2$2;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // Caluclate cross products\n\n ni.cross(nj, nixnj);\n nj.cross(ni, njxni); // The angle between two vector is:\n // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b\n // g = a * b\n // gdot = (b x a) * wi + (a x b) * wj\n // G = [0 bxa 0 axb]\n // W = [vi wi vj wj]\n\n GA.rotational.copy(njxni);\n GB.rotational.copy(nixnj);\n const g = Math.cos(this.angle) - ni.dot(nj);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n\n}\nconst tmpVec1$2 = new Vec3();\nconst tmpVec2$2 = new Vec3();\n\n/**\n * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.\n */\nclass RotationalEquation extends Equation {\n /**\n * World oriented rotational axis.\n */\n\n /**\n * World oriented rotational axis.\n */\n\n /**\n * maxAngle\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);\n this.maxAngle = Math.PI / 2;\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const ni = this.axisA;\n const nj = this.axisB;\n const nixnj = tmpVec1$1;\n const njxni = tmpVec2$1;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // Caluclate cross products\n\n ni.cross(nj, nixnj);\n nj.cross(ni, njxni); // g = ni * nj\n // gdot = (nj x ni) * wi + (ni x nj) * wj\n // G = [0 njxni 0 nixnj]\n // W = [vi wi vj wj]\n\n GA.rotational.copy(njxni);\n GB.rotational.copy(nixnj);\n const g = Math.cos(this.maxAngle) - ni.dot(nj);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n\n}\nconst tmpVec1$1 = new Vec3();\nconst tmpVec2$1 = new Vec3();\n\n/**\n * A Cone Twist constraint, useful for ragdolls.\n */\nclass ConeTwistConstraint extends PointToPointConstraint {\n /**\n * The axis direction for the constraint of the body A.\n */\n\n /**\n * The axis direction for the constraint of the body B.\n */\n\n /**\n * The aperture angle of the cone.\n */\n\n /**\n * The twist angle of the joint.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between\n\n const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();\n const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();\n super(bodyA, pivotA, bodyB, pivotB, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3();\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3();\n this.collideConnected = !!options.collideConnected;\n this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;\n const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);\n const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);\n this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward\n\n c.maxForce = 0;\n c.minForce = -maxForce; // Make the twist equation add torque toward the initial position\n\n t.maxForce = 0;\n t.minForce = -maxForce;\n this.equations.push(c, t);\n }\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const cone = this.coneEquation;\n const twist = this.twistEquation;\n super.update(); // Update the axes to the cone constraint\n\n bodyA.vectorToWorldFrame(this.axisA, cone.axisA);\n bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint\n\n this.axisA.tangents(twist.axisA, twist.axisA);\n bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);\n this.axisB.tangents(twist.axisB, twist.axisB);\n bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);\n cone.angle = this.angle;\n twist.maxAngle = this.twistAngle;\n }\n\n}\nnew Vec3();\nnew Vec3();\n\n/**\n * Constrains two bodies to be at a constant distance from each others center of mass.\n */\nclass DistanceConstraint extends Constraint {\n /**\n * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB\n */\n\n /**\n * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.\n * @param maxForce The maximum force that should be applied to constrain the bodies.\n */\n constructor(bodyA, bodyB, distance, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB);\n\n if (typeof distance === 'undefined') {\n distance = bodyA.position.distanceTo(bodyB.position);\n }\n\n this.distance = distance;\n const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);\n this.equations.push(eq); // Make it bidirectional\n\n eq.minForce = -maxForce;\n eq.maxForce = maxForce;\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const eq = this.distanceEquation;\n const halfDist = this.distance * 0.5;\n const normal = eq.ni;\n bodyB.position.vsub(bodyA.position, normal);\n normal.normalize();\n normal.scale(halfDist, eq.ri);\n normal.scale(-halfDist, eq.rj);\n }\n\n}\n\n/**\n * Lock constraint. Will remove all degrees of freedom between the bodies.\n */\nclass LockConstraint extends PointToPointConstraint {\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between\n\n const pivotA = new Vec3();\n const pivotB = new Vec3();\n const halfWay = new Vec3();\n bodyA.position.vadd(bodyB.position, halfWay);\n halfWay.scale(0.5, halfWay);\n bodyB.pointToLocalFrame(halfWay, pivotB);\n bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies\n\n super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces\n\n this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);\n this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);\n this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);\n this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);\n this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);\n this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place\n\n const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);\n const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);\n const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);\n this.equations.push(r1, r2, r3);\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n this.motorEquation;\n const r1 = this.rotationalEquation1;\n const r2 = this.rotationalEquation2;\n const r3 = this.rotationalEquation3;\n LockConstraint_update_tmpVec1;\n LockConstraint_update_tmpVec2;\n super.update(); // These vector pairs must be orthogonal\n\n bodyA.vectorToWorldFrame(this.xA, r1.axisA);\n bodyB.vectorToWorldFrame(this.yB, r1.axisB);\n bodyA.vectorToWorldFrame(this.yA, r2.axisA);\n bodyB.vectorToWorldFrame(this.zB, r2.axisB);\n bodyA.vectorToWorldFrame(this.zA, r3.axisA);\n bodyB.vectorToWorldFrame(this.xB, r3.axisB);\n }\n\n}\nconst LockConstraint_update_tmpVec1 = new Vec3();\nconst LockConstraint_update_tmpVec2 = new Vec3();\n\n/**\n * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.\n */\nclass RotationalMotorEquation extends Equation {\n /**\n * World oriented rotational axis.\n */\n\n /**\n * World oriented rotational axis.\n */\n\n /**\n * Motor velocity.\n */\n constructor(bodyA, bodyB, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = new Vec3();\n this.axisB = new Vec3();\n this.targetVelocity = 0;\n }\n\n computeB(h) {\n this.a;\n const b = this.b;\n this.bi;\n this.bj;\n const axisA = this.axisA;\n const axisB = this.axisB;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // g = 0\n // gdot = axisA * wi - axisB * wj\n // gdot = G * W = G * [vi wi vj wj]\n // =>\n // G = [0 axisA 0 -axisB]\n\n GA.rotational.copy(axisA);\n axisB.negate(GB.rotational);\n const GW = this.computeGW() - this.targetVelocity;\n const GiMf = this.computeGiMf();\n const B = -GW * b - h * GiMf;\n return B;\n }\n\n}\n\n/**\n * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.\n */\nclass HingeConstraint extends PointToPointConstraint {\n /**\n * Rotation axis, defined locally in bodyA.\n */\n\n /**\n * Rotation axis, defined locally in bodyB.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();\n const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();\n super(bodyA, pivotA, bodyB, pivotB, maxForce);\n const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n axisA.normalize();\n const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);\n axisB.normalize();\n this.collideConnected = !!options.collideConnected;\n const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);\n const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);\n const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);\n motor.enabled = false; // Not enabled by default\n // Equations to be fed to the solver\n\n this.equations.push(rotational1, rotational2, motor);\n }\n /**\n * enableMotor\n */\n\n\n enableMotor() {\n this.motorEquation.enabled = true;\n }\n /**\n * disableMotor\n */\n\n\n disableMotor() {\n this.motorEquation.enabled = false;\n }\n /**\n * setMotorSpeed\n */\n\n\n setMotorSpeed(speed) {\n this.motorEquation.targetVelocity = speed;\n }\n /**\n * setMotorMaxForce\n */\n\n\n setMotorMaxForce(maxForce) {\n this.motorEquation.maxForce = maxForce;\n this.motorEquation.minForce = -maxForce;\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const motor = this.motorEquation;\n const r1 = this.rotationalEquation1;\n const r2 = this.rotationalEquation2;\n const worldAxisA = HingeConstraint_update_tmpVec1;\n const worldAxisB = HingeConstraint_update_tmpVec2;\n const axisA = this.axisA;\n const axisB = this.axisB;\n super.update(); // Get world axes\n\n bodyA.quaternion.vmult(axisA, worldAxisA);\n bodyB.quaternion.vmult(axisB, worldAxisB);\n worldAxisA.tangents(r1.axisA, r2.axisA);\n r1.axisB.copy(worldAxisB);\n r2.axisB.copy(worldAxisB);\n\n if (this.motorEquation.enabled) {\n bodyA.quaternion.vmult(this.axisA, motor.axisA);\n bodyB.quaternion.vmult(this.axisB, motor.axisB);\n }\n }\n\n}\nconst HingeConstraint_update_tmpVec1 = new Vec3();\nconst HingeConstraint_update_tmpVec2 = new Vec3();\n\n/**\n * Constrains the slipping in a contact along a tangent\n */\nclass FrictionEquation extends Equation {\n // Tangent\n\n /**\n * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g\n */\n constructor(bodyA, bodyB, slipForce) {\n super(bodyA, bodyB, -slipForce, slipForce);\n this.ri = new Vec3();\n this.rj = new Vec3();\n this.t = new Vec3();\n }\n\n computeB(h) {\n this.a;\n const b = this.b;\n this.bi;\n this.bj;\n const ri = this.ri;\n const rj = this.rj;\n const rixt = FrictionEquation_computeB_temp1;\n const rjxt = FrictionEquation_computeB_temp2;\n const t = this.t; // Caluclate cross products\n\n ri.cross(t, rixt);\n rj.cross(t, rjxt); // G = [-t -rixt t rjxt]\n // And remember, this is a pure velocity constraint, g is always zero!\n\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n t.negate(GA.spatial);\n rixt.negate(GA.rotational);\n GB.spatial.copy(t);\n GB.rotational.copy(rjxt);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -GW * b - h * GiMf;\n return B;\n }\n\n}\nconst FrictionEquation_computeB_temp1 = new Vec3();\nconst FrictionEquation_computeB_temp2 = new Vec3();\n\n/**\n * Defines what happens when two materials meet.\n * @todo Refactor materials to materialA and materialB\n */\nclass ContactMaterial {\n /**\n * Identifier of this material.\n */\n\n /**\n * Participating materials.\n */\n\n /**\n * Friction coefficient.\n * @default 0.3\n */\n\n /**\n * Restitution coefficient.\n * @default 0.3\n */\n\n /**\n * Stiffness of the produced contact equations.\n * @default 1e7\n */\n\n /**\n * Relaxation time of the produced contact equations.\n * @default 3\n */\n\n /**\n * Stiffness of the produced friction equations.\n * @default 1e7\n */\n\n /**\n * Relaxation time of the produced friction equations\n * @default 3\n */\n constructor(m1, m2, options) {\n options = Utils.defaults(options, {\n friction: 0.3,\n restitution: 0.3,\n contactEquationStiffness: 1e7,\n contactEquationRelaxation: 3,\n frictionEquationStiffness: 1e7,\n frictionEquationRelaxation: 3\n });\n this.id = ContactMaterial.idCounter++;\n this.materials = [m1, m2];\n this.friction = options.friction;\n this.restitution = options.restitution;\n this.contactEquationStiffness = options.contactEquationStiffness;\n this.contactEquationRelaxation = options.contactEquationRelaxation;\n this.frictionEquationStiffness = options.frictionEquationStiffness;\n this.frictionEquationRelaxation = options.frictionEquationRelaxation;\n }\n\n}\nContactMaterial.idCounter = 0;\n\n/**\n * Defines a physics material.\n */\nclass Material {\n /**\n * Material name.\n * If options is a string, name will be set to that string.\n * @todo Deprecate this\n */\n\n /** Material id. */\n\n /**\n * Friction for this material.\n * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.\n */\n\n /**\n * Restitution for this material.\n * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n let name = ''; // Backwards compatibility fix\n\n if (typeof options === 'string') {\n //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)\n name = options;\n options = {};\n }\n\n this.name = name;\n this.id = Material.idCounter++;\n this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;\n this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;\n }\n\n}\nMaterial.idCounter = 0;\n\n/**\n * A spring, connecting two bodies.\n * @example\n * const spring = new Spring(boxBody, sphereBody, {\n * restLength: 0,\n * stiffness: 50,\n * damping: 1,\n * })\n *\n * // Compute the force after each step\n * world.addEventListener('postStep', (event) => {\n * spring.applyForce()\n * })\n */\nclass Spring {\n /**\n * Rest length of the spring. A number > 0.\n * @default 1\n */\n\n /**\n * Stiffness of the spring. A number >= 0.\n * @default 100\n */\n\n /**\n * Damping of the spring. A number >= 0.\n * @default 1\n */\n\n /**\n * First connected body.\n */\n\n /**\n * Second connected body.\n */\n\n /**\n * Anchor for bodyA in local bodyA coordinates.\n * Where to hook the spring to body A, in local body coordinates.\n * @default new Vec3()\n */\n\n /**\n * Anchor for bodyB in local bodyB coordinates.\n * Where to hook the spring to body B, in local body coordinates.\n * @default new Vec3()\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;\n this.stiffness = options.stiffness || 100;\n this.damping = options.damping || 1;\n this.bodyA = bodyA;\n this.bodyB = bodyB;\n this.localAnchorA = new Vec3();\n this.localAnchorB = new Vec3();\n\n if (options.localAnchorA) {\n this.localAnchorA.copy(options.localAnchorA);\n }\n\n if (options.localAnchorB) {\n this.localAnchorB.copy(options.localAnchorB);\n }\n\n if (options.worldAnchorA) {\n this.setWorldAnchorA(options.worldAnchorA);\n }\n\n if (options.worldAnchorB) {\n this.setWorldAnchorB(options.worldAnchorB);\n }\n }\n /**\n * Set the anchor point on body A, using world coordinates.\n */\n\n\n setWorldAnchorA(worldAnchorA) {\n this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);\n }\n /**\n * Set the anchor point on body B, using world coordinates.\n */\n\n\n setWorldAnchorB(worldAnchorB) {\n this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);\n }\n /**\n * Get the anchor point on body A, in world coordinates.\n * @param result The vector to store the result in.\n */\n\n\n getWorldAnchorA(result) {\n this.bodyA.pointToWorldFrame(this.localAnchorA, result);\n }\n /**\n * Get the anchor point on body B, in world coordinates.\n * @param result The vector to store the result in.\n */\n\n\n getWorldAnchorB(result) {\n this.bodyB.pointToWorldFrame(this.localAnchorB, result);\n }\n /**\n * Apply the spring force to the connected bodies.\n */\n\n\n applyForce() {\n const k = this.stiffness;\n const d = this.damping;\n const l = this.restLength;\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const r = applyForce_r;\n const r_unit = applyForce_r_unit;\n const u = applyForce_u;\n const f = applyForce_f;\n const tmp = applyForce_tmp;\n const worldAnchorA = applyForce_worldAnchorA;\n const worldAnchorB = applyForce_worldAnchorB;\n const ri = applyForce_ri;\n const rj = applyForce_rj;\n const ri_x_f = applyForce_ri_x_f;\n const rj_x_f = applyForce_rj_x_f; // Get world anchors\n\n this.getWorldAnchorA(worldAnchorA);\n this.getWorldAnchorB(worldAnchorB); // Get offset points\n\n worldAnchorA.vsub(bodyA.position, ri);\n worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points\n\n worldAnchorB.vsub(worldAnchorA, r);\n const rlen = r.length();\n r_unit.copy(r);\n r_unit.normalize(); // Compute relative velocity of the anchor points, u\n\n bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity\n\n bodyB.angularVelocity.cross(rj, tmp);\n u.vadd(tmp, u);\n bodyA.angularVelocity.cross(ri, tmp);\n u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )\n\n r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies\n\n bodyA.force.vsub(f, bodyA.force);\n bodyB.force.vadd(f, bodyB.force); // Angular force\n\n ri.cross(f, ri_x_f);\n rj.cross(f, rj_x_f);\n bodyA.torque.vsub(ri_x_f, bodyA.torque);\n bodyB.torque.vadd(rj_x_f, bodyB.torque);\n }\n\n}\nconst applyForce_r = new Vec3();\nconst applyForce_r_unit = new Vec3();\nconst applyForce_u = new Vec3();\nconst applyForce_f = new Vec3();\nconst applyForce_worldAnchorA = new Vec3();\nconst applyForce_worldAnchorB = new Vec3();\nconst applyForce_ri = new Vec3();\nconst applyForce_rj = new Vec3();\nconst applyForce_ri_x_f = new Vec3();\nconst applyForce_rj_x_f = new Vec3();\nconst applyForce_tmp = new Vec3();\n\n/**\n * WheelInfo\n */\nclass WheelInfo {\n /**\n * Max travel distance of the suspension, in meters.\n * @default 1\n */\n\n /**\n * Speed to apply to the wheel rotation when the wheel is sliding.\n * @default -0.1\n */\n\n /**\n * If the customSlidingRotationalSpeed should be used.\n * @default false\n */\n\n /**\n * sliding\n */\n\n /**\n * Connection point, defined locally in the chassis body frame.\n */\n\n /**\n * chassisConnectionPointWorld\n */\n\n /**\n * directionLocal\n */\n\n /**\n * directionWorld\n */\n\n /**\n * axleLocal\n */\n\n /**\n * axleWorld\n */\n\n /**\n * suspensionRestLength\n * @default 1\n */\n\n /**\n * suspensionMaxLength\n * @default 2\n */\n\n /**\n * radius\n * @default 1\n */\n\n /**\n * suspensionStiffness\n * @default 100\n */\n\n /**\n * dampingCompression\n * @default 10\n */\n\n /**\n * dampingRelaxation\n * @default 10\n */\n\n /**\n * frictionSlip\n * @default 10.5\n */\n\n /** forwardAcceleration */\n\n /** sideAcceleration */\n\n /**\n * steering\n * @default 0\n */\n\n /**\n * Rotation value, in radians.\n * @default 0\n */\n\n /**\n * deltaRotation\n * @default 0\n */\n\n /**\n * rollInfluence\n * @default 0.01\n */\n\n /**\n * maxSuspensionForce\n */\n\n /**\n * engineForce\n */\n\n /**\n * brake\n */\n\n /**\n * isFrontWheel\n * @default true\n */\n\n /**\n * clippedInvContactDotSuspension\n * @default 1\n */\n\n /**\n * suspensionRelativeVelocity\n * @default 0\n */\n\n /**\n * suspensionForce\n * @default 0\n */\n\n /**\n * slipInfo\n */\n\n /**\n * skidInfo\n * @default 0\n */\n\n /**\n * suspensionLength\n * @default 0\n */\n\n /**\n * sideImpulse\n */\n\n /**\n * forwardImpulse\n */\n\n /**\n * The result from raycasting.\n */\n\n /**\n * Wheel world transform.\n */\n\n /**\n * isInContact\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n chassisConnectionPointLocal: new Vec3(),\n chassisConnectionPointWorld: new Vec3(),\n directionLocal: new Vec3(),\n directionWorld: new Vec3(),\n axleLocal: new Vec3(),\n axleWorld: new Vec3(),\n suspensionRestLength: 1,\n suspensionMaxLength: 2,\n radius: 1,\n suspensionStiffness: 100,\n dampingCompression: 10,\n dampingRelaxation: 10,\n frictionSlip: 10.5,\n forwardAcceleration: 1,\n sideAcceleration: 1,\n steering: 0,\n rotation: 0,\n deltaRotation: 0,\n rollInfluence: 0.01,\n maxSuspensionForce: Number.MAX_VALUE,\n isFrontWheel: true,\n clippedInvContactDotSuspension: 1,\n suspensionRelativeVelocity: 0,\n suspensionForce: 0,\n slipInfo: 0,\n skidInfo: 0,\n suspensionLength: 0,\n maxSuspensionTravel: 1,\n useCustomSlidingRotationalSpeed: false,\n customSlidingRotationalSpeed: -0.1\n });\n this.maxSuspensionTravel = options.maxSuspensionTravel;\n this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;\n this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;\n this.sliding = false;\n this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();\n this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();\n this.directionLocal = options.directionLocal.clone();\n this.directionWorld = options.directionWorld.clone();\n this.axleLocal = options.axleLocal.clone();\n this.axleWorld = options.axleWorld.clone();\n this.suspensionRestLength = options.suspensionRestLength;\n this.suspensionMaxLength = options.suspensionMaxLength;\n this.radius = options.radius;\n this.suspensionStiffness = options.suspensionStiffness;\n this.dampingCompression = options.dampingCompression;\n this.dampingRelaxation = options.dampingRelaxation;\n this.frictionSlip = options.frictionSlip;\n this.forwardAcceleration = options.forwardAcceleration;\n this.sideAcceleration = options.sideAcceleration;\n this.steering = 0;\n this.rotation = 0;\n this.deltaRotation = 0;\n this.rollInfluence = options.rollInfluence;\n this.maxSuspensionForce = options.maxSuspensionForce;\n this.engineForce = 0;\n this.brake = 0;\n this.isFrontWheel = options.isFrontWheel;\n this.clippedInvContactDotSuspension = 1;\n this.suspensionRelativeVelocity = 0;\n this.suspensionForce = 0;\n this.slipInfo = 0;\n this.skidInfo = 0;\n this.suspensionLength = 0;\n this.sideImpulse = 0;\n this.forwardImpulse = 0;\n this.raycastResult = new RaycastResult();\n this.worldTransform = new Transform();\n this.isInContact = false;\n }\n\n updateWheel(chassis) {\n const raycastResult = this.raycastResult;\n\n if (this.isInContact) {\n const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);\n raycastResult.hitPointWorld.vsub(chassis.position, relpos);\n chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);\n const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);\n\n if (project >= -0.1) {\n this.suspensionRelativeVelocity = 0.0;\n this.clippedInvContactDotSuspension = 1.0 / 0.1;\n } else {\n const inv = -1 / project;\n this.suspensionRelativeVelocity = projVel * inv;\n this.clippedInvContactDotSuspension = inv;\n }\n } else {\n // Not in contact : position wheel in a nice (rest length) position\n raycastResult.suspensionLength = this.suspensionRestLength;\n this.suspensionRelativeVelocity = 0.0;\n raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);\n this.clippedInvContactDotSuspension = 1.0;\n }\n }\n\n}\nconst chassis_velocity_at_contactPoint = new Vec3();\nconst relpos = new Vec3();\n\n/**\n * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.\n */\nclass RaycastVehicle {\n /** The car chassis body. */\n\n /** The wheels. */\n\n /** Will be set to true if the car is sliding. */\n\n /** Index of the right axis. x=0, y=1, z=2 */\n\n /** Index of the forward axis. x=0, y=1, z=2 */\n\n /** Index of the up axis. x=0, y=1, z=2 */\n\n /** The constraints. */\n\n /** Optional pre-step callback. */\n\n /** Number of wheels on the ground. */\n constructor(options) {\n this.chassisBody = options.chassisBody;\n this.wheelInfos = [];\n this.sliding = false;\n this.world = null;\n this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;\n this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;\n this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;\n this.constraints = [];\n\n this.preStepCallback = () => {};\n\n this.currentVehicleSpeedKmHour = 0;\n this.numWheelsOnGround = 0;\n }\n /**\n * Add a wheel. For information about the options, see `WheelInfo`.\n */\n\n\n addWheel(options) {\n if (options === void 0) {\n options = {};\n }\n\n const info = new WheelInfo(options);\n const index = this.wheelInfos.length;\n this.wheelInfos.push(info);\n return index;\n }\n /**\n * Set the steering value of a wheel.\n */\n\n\n setSteeringValue(value, wheelIndex) {\n const wheel = this.wheelInfos[wheelIndex];\n wheel.steering = value;\n }\n /**\n * Set the wheel force to apply on one of the wheels each time step\n */\n\n\n applyEngineForce(value, wheelIndex) {\n this.wheelInfos[wheelIndex].engineForce = value;\n }\n /**\n * Set the braking force of a wheel\n */\n\n\n setBrake(brake, wheelIndex) {\n this.wheelInfos[wheelIndex].brake = brake;\n }\n /**\n * Add the vehicle including its constraints to the world.\n */\n\n\n addToWorld(world) {\n world.addBody(this.chassisBody);\n const that = this;\n\n this.preStepCallback = () => {\n that.updateVehicle(world.dt);\n };\n\n world.addEventListener('preStep', this.preStepCallback);\n this.world = world;\n }\n /**\n * Get one of the wheel axles, world-oriented.\n */\n\n\n getVehicleAxisWorld(axisIndex, result) {\n result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);\n this.chassisBody.vectorToWorldFrame(result, result);\n }\n\n updateVehicle(timeStep) {\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n const chassisBody = this.chassisBody;\n\n for (let i = 0; i < numWheels; i++) {\n this.updateWheelTransform(i);\n }\n\n this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();\n const forwardWorld = new Vec3();\n this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);\n\n if (forwardWorld.dot(chassisBody.velocity) < 0) {\n this.currentVehicleSpeedKmHour *= -1;\n } // simulate suspension\n\n\n for (let i = 0; i < numWheels; i++) {\n this.castRay(wheelInfos[i]);\n }\n\n this.updateSuspension(timeStep);\n const impulse = new Vec3();\n const relpos = new Vec3();\n\n for (let i = 0; i < numWheels; i++) {\n //apply suspension force\n const wheel = wheelInfos[i];\n let suspensionForce = wheel.suspensionForce;\n\n if (suspensionForce > wheel.maxSuspensionForce) {\n suspensionForce = wheel.maxSuspensionForce;\n }\n\n wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);\n wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);\n chassisBody.applyImpulse(impulse, relpos);\n }\n\n this.updateFriction(timeStep);\n const hitNormalWorldScaledWithProj = new Vec3();\n const fwd = new Vec3();\n const vel = new Vec3();\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i]; //const relpos = new Vec3();\n //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);\n\n chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction\n\n let m = 1;\n\n switch (this.indexUpAxis) {\n case 1:\n m = -1;\n break;\n }\n\n if (wheel.isInContact) {\n this.getVehicleAxisWorld(this.indexForwardAxis, fwd);\n const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);\n wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);\n fwd.vsub(hitNormalWorldScaledWithProj, fwd);\n const proj2 = fwd.dot(vel);\n wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;\n }\n\n if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {\n // Apply custom rotation when accelerating and sliding\n wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;\n } // Lock wheels\n\n\n if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {\n wheel.deltaRotation = 0;\n }\n\n wheel.rotation += wheel.deltaRotation; // Use the old value\n\n wheel.deltaRotation *= 0.99; // damping of rotation when not in contact\n }\n }\n\n updateSuspension(deltaTime) {\n const chassisBody = this.chassisBody;\n const chassisMass = chassisBody.mass;\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n\n for (let w_it = 0; w_it < numWheels; w_it++) {\n const wheel = wheelInfos[w_it];\n\n if (wheel.isInContact) {\n let force; // Spring\n\n const susp_length = wheel.suspensionRestLength;\n const current_length = wheel.suspensionLength;\n const length_diff = susp_length - current_length;\n force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper\n\n const projected_rel_vel = wheel.suspensionRelativeVelocity;\n let susp_damping;\n\n if (projected_rel_vel < 0) {\n susp_damping = wheel.dampingCompression;\n } else {\n susp_damping = wheel.dampingRelaxation;\n }\n\n force -= susp_damping * projected_rel_vel;\n wheel.suspensionForce = force * chassisMass;\n\n if (wheel.suspensionForce < 0) {\n wheel.suspensionForce = 0;\n }\n } else {\n wheel.suspensionForce = 0;\n }\n }\n }\n /**\n * Remove the vehicle including its constraints from the world.\n */\n\n\n removeFromWorld(world) {\n this.constraints;\n world.removeBody(this.chassisBody);\n world.removeEventListener('preStep', this.preStepCallback);\n this.world = null;\n }\n\n castRay(wheel) {\n const rayvector = castRay_rayvector;\n const target = castRay_target;\n this.updateWheelTransformWorld(wheel);\n const chassisBody = this.chassisBody;\n let depth = -1;\n const raylen = wheel.suspensionRestLength + wheel.radius;\n wheel.directionWorld.scale(raylen, rayvector);\n const source = wheel.chassisConnectionPointWorld;\n source.vadd(rayvector, target);\n const raycastResult = wheel.raycastResult;\n raycastResult.reset(); // Turn off ray collision with the chassis temporarily\n\n const oldState = chassisBody.collisionResponse;\n chassisBody.collisionResponse = false; // Cast ray against world\n\n this.world.rayTest(source, target, raycastResult);\n chassisBody.collisionResponse = oldState;\n const object = raycastResult.body;\n wheel.raycastResult.groundObject = 0;\n\n if (object) {\n depth = raycastResult.distance;\n wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;\n wheel.isInContact = true;\n const hitDistance = raycastResult.distance;\n wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel\n\n const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;\n const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;\n\n if (wheel.suspensionLength < minSuspensionLength) {\n wheel.suspensionLength = minSuspensionLength;\n }\n\n if (wheel.suspensionLength > maxSuspensionLength) {\n wheel.suspensionLength = maxSuspensionLength;\n wheel.raycastResult.reset();\n }\n\n const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);\n const chassis_velocity_at_contactPoint = new Vec3();\n chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);\n const projVel = wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);\n\n if (denominator >= -0.1) {\n wheel.suspensionRelativeVelocity = 0;\n wheel.clippedInvContactDotSuspension = 1 / 0.1;\n } else {\n const inv = -1 / denominator;\n wheel.suspensionRelativeVelocity = projVel * inv;\n wheel.clippedInvContactDotSuspension = inv;\n }\n } else {\n //put wheel info as in rest position\n wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;\n wheel.suspensionRelativeVelocity = 0.0;\n wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);\n wheel.clippedInvContactDotSuspension = 1.0;\n }\n\n return depth;\n }\n\n updateWheelTransformWorld(wheel) {\n wheel.isInContact = false;\n const chassisBody = this.chassisBody;\n chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);\n chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);\n chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);\n }\n /**\n * Update one of the wheel transform.\n * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.\n * @param wheelIndex The wheel index to update.\n */\n\n\n updateWheelTransform(wheelIndex) {\n const up = tmpVec4;\n const right = tmpVec5;\n const fwd = tmpVec6;\n const wheel = this.wheelInfos[wheelIndex];\n this.updateWheelTransformWorld(wheel);\n wheel.directionLocal.scale(-1, up);\n right.copy(wheel.axleLocal);\n up.cross(right, fwd);\n fwd.normalize();\n right.normalize(); // Rotate around steering over the wheelAxle\n\n const steering = wheel.steering;\n const steeringOrn = new Quaternion();\n steeringOrn.setFromAxisAngle(up, steering);\n const rotatingOrn = new Quaternion();\n rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel\n\n const q = wheel.worldTransform.quaternion;\n this.chassisBody.quaternion.mult(steeringOrn, q);\n q.mult(rotatingOrn, q);\n q.normalize(); // world position of the wheel\n\n const p = wheel.worldTransform.position;\n p.copy(wheel.directionWorld);\n p.scale(wheel.suspensionLength, p);\n p.vadd(wheel.chassisConnectionPointWorld, p);\n }\n /**\n * Get the world transform of one of the wheels\n */\n\n\n getWheelTransformWorld(wheelIndex) {\n return this.wheelInfos[wheelIndex].worldTransform;\n }\n\n updateFriction(timeStep) {\n const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards\n\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n const chassisBody = this.chassisBody;\n const forwardWS = updateFriction_forwardWS;\n const axle = updateFriction_axle;\n this.numWheelsOnGround = 0;\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n\n if (groundObject) {\n this.numWheelsOnGround++;\n }\n\n wheel.sideImpulse = 0;\n wheel.forwardImpulse = 0;\n\n if (!forwardWS[i]) {\n forwardWS[i] = new Vec3();\n }\n\n if (!axle[i]) {\n axle[i] = new Vec3();\n }\n }\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n\n if (groundObject) {\n const axlei = axle[i];\n const wheelTrans = this.getWheelTransformWorld(i); // Get world axle\n\n wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);\n const surfNormalWS = wheel.raycastResult.hitNormalWorld;\n const proj = axlei.dot(surfNormalWS);\n surfNormalWS.scale(proj, surfNormalWS_scaled_proj);\n axlei.vsub(surfNormalWS_scaled_proj, axlei);\n axlei.normalize();\n surfNormalWS.cross(axlei, forwardWS[i]);\n forwardWS[i].normalize();\n wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);\n wheel.sideImpulse *= sideFrictionStiffness2;\n }\n }\n\n const sideFactor = 1;\n const fwdFactor = 0.5;\n this.sliding = false;\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n let rollingFriction = 0;\n wheel.slipInfo = 1;\n\n if (groundObject) {\n const defaultRollingFrictionImpulse = 0;\n const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);\n // rollingFriction = calcRollingFriction(contactPt);\n\n rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);\n rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;\n\n const factor = maxImpulse / rollingFriction;\n wheel.slipInfo *= factor;\n } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)\n\n\n wheel.forwardImpulse = 0;\n wheel.skidInfo = 1;\n\n if (groundObject) {\n wheel.skidInfo = 1;\n const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;\n const maximpSide = maximp;\n const maximpSquared = maximp * maximpSide;\n wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;\n\n const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;\n const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;\n const impulseSquared = x * x + y * y;\n wheel.sliding = false;\n\n if (impulseSquared > maximpSquared) {\n this.sliding = true;\n wheel.sliding = true;\n const factor = maximp / Math.sqrt(impulseSquared);\n wheel.skidInfo *= factor;\n }\n }\n }\n\n if (this.sliding) {\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n\n if (wheel.sideImpulse !== 0) {\n if (wheel.skidInfo < 1) {\n wheel.forwardImpulse *= wheel.skidInfo;\n wheel.sideImpulse *= wheel.skidInfo;\n }\n }\n }\n } // apply the impulses\n\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const rel_pos = new Vec3();\n wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position\n //rel_pos.copy(wheel.raycastResult.hitPointWorld);\n\n if (wheel.forwardImpulse !== 0) {\n const impulse = new Vec3();\n forwardWS[i].scale(wheel.forwardImpulse, impulse);\n chassisBody.applyImpulse(impulse, rel_pos);\n }\n\n if (wheel.sideImpulse !== 0) {\n const groundObject = wheel.raycastResult.body;\n const rel_pos2 = new Vec3();\n wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);\n\n const sideImp = new Vec3();\n axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.\n // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).\n\n chassisBody.vectorToLocalFrame(rel_pos, rel_pos);\n rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;\n chassisBody.vectorToWorldFrame(rel_pos, rel_pos);\n chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground\n\n sideImp.scale(-1, sideImp);\n groundObject.applyImpulse(sideImp, rel_pos2);\n }\n }\n }\n\n}\nnew Vec3();\nnew Vec3();\nnew Vec3();\nconst tmpVec4 = new Vec3();\nconst tmpVec5 = new Vec3();\nconst tmpVec6 = new Vec3();\nnew Ray();\nnew Vec3();\nconst castRay_rayvector = new Vec3();\nconst castRay_target = new Vec3();\nconst directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];\nconst updateFriction_surfNormalWS_scaled_proj = new Vec3();\nconst updateFriction_axle = [];\nconst updateFriction_forwardWS = [];\nconst sideFrictionStiffness2 = 1;\nconst calcRollingFriction_vel1 = new Vec3();\nconst calcRollingFriction_vel2 = new Vec3();\nconst calcRollingFriction_vel = new Vec3();\n\nfunction calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {\n let j1 = 0;\n const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();\n // const rel_pos2 = new Vec3();\n\n const vel1 = calcRollingFriction_vel1;\n const vel2 = calcRollingFriction_vel2;\n const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);\n // contactPosWorld.vsub(body1.position, rel_pos2);\n\n body0.getVelocityAtWorldPoint(contactPosWorld, vel1);\n body1.getVelocityAtWorldPoint(contactPosWorld, vel2);\n vel1.vsub(vel2, vel);\n const vrel = frictionDirectionWorld.dot(vel);\n const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);\n const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);\n const relaxation = 1;\n const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity\n\n j1 = -vrel * jacDiagABInv;\n\n if (maxImpulse < j1) {\n j1 = maxImpulse;\n }\n\n if (j1 < -maxImpulse) {\n j1 = -maxImpulse;\n }\n\n return j1;\n}\n\nconst computeImpulseDenominator_r0 = new Vec3();\nconst computeImpulseDenominator_c0 = new Vec3();\nconst computeImpulseDenominator_vec = new Vec3();\nconst computeImpulseDenominator_m = new Vec3();\n\nfunction computeImpulseDenominator(body, pos, normal) {\n const r0 = computeImpulseDenominator_r0;\n const c0 = computeImpulseDenominator_c0;\n const vec = computeImpulseDenominator_vec;\n const m = computeImpulseDenominator_m;\n pos.vsub(body.position, r0);\n r0.cross(normal, c0);\n body.invInertiaWorld.vmult(c0, m);\n m.cross(r0, vec);\n return body.invMass + normal.dot(vec);\n}\n\nconst resolveSingleBilateral_vel1 = new Vec3();\nconst resolveSingleBilateral_vel2 = new Vec3();\nconst resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects\n\nfunction resolveSingleBilateral(body1, pos1, body2, pos2, normal) {\n const normalLenSqr = normal.lengthSquared();\n\n if (normalLenSqr > 1.1) {\n return 0; // no impulse\n } // const rel_pos1 = new Vec3();\n // const rel_pos2 = new Vec3();\n // pos1.vsub(body1.position, rel_pos1);\n // pos2.vsub(body2.position, rel_pos2);\n\n\n const vel1 = resolveSingleBilateral_vel1;\n const vel2 = resolveSingleBilateral_vel2;\n const vel = resolveSingleBilateral_vel;\n body1.getVelocityAtWorldPoint(pos1, vel1);\n body2.getVelocityAtWorldPoint(pos2, vel2);\n vel1.vsub(vel2, vel);\n const rel_vel = normal.dot(vel);\n const contactDamping = 0.2;\n const massTerm = 1 / (body1.invMass + body2.invMass);\n const impulse = -contactDamping * rel_vel * massTerm;\n return impulse;\n}\n\n/**\n * Spherical shape\n * @example\n * const radius = 1\n * const sphereShape = new CANNON.Sphere(radius)\n * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })\n * world.addBody(sphereBody)\n */\nclass Sphere extends Shape {\n /**\n * The radius of the sphere.\n */\n\n /**\n *\n * @param radius The radius of the sphere, a non-negative number.\n */\n constructor(radius) {\n super({\n type: Shape.types.SPHERE\n });\n this.radius = radius !== undefined ? radius : 1.0;\n\n if (this.radius < 0) {\n throw new Error('The sphere radius cannot be negative.');\n }\n\n this.updateBoundingSphereRadius();\n }\n /** calculateLocalInertia */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const I = 2.0 * mass * this.radius * this.radius / 5.0;\n target.x = I;\n target.y = I;\n target.z = I;\n return target;\n }\n /** volume */\n\n\n volume() {\n return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = this.radius;\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n const r = this.radius;\n const axes = ['x', 'y', 'z'];\n\n for (let i = 0; i < axes.length; i++) {\n const ax = axes[i];\n min[ax] = pos[ax] - r;\n max[ax] = pos[ax] + r;\n }\n }\n\n}\n\n/**\n * Simple vehicle helper class with spherical rigid body wheels.\n */\nclass RigidVehicle {\n /**\n * The bodies of the wheels.\n */\n\n /**\n * The chassis body.\n */\n\n /**\n * The constraints.\n */\n\n /**\n * The wheel axes.\n */\n\n /**\n * The wheel forces.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.wheelBodies = [];\n this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);\n\n if (options.chassisBody) {\n this.chassisBody = options.chassisBody;\n } else {\n // No chassis body given. Create it!\n this.chassisBody = new Body({\n mass: 1,\n shape: new Box(new Vec3(5, 0.5, 2))\n });\n }\n\n this.constraints = [];\n this.wheelAxes = [];\n this.wheelForces = [];\n }\n /**\n * Add a wheel\n */\n\n\n addWheel(options) {\n if (options === void 0) {\n options = {};\n }\n\n let wheelBody;\n\n if (options.body) {\n wheelBody = options.body;\n } else {\n // No wheel body given. Create it!\n wheelBody = new Body({\n mass: 1,\n shape: new Sphere(1.2)\n });\n }\n\n this.wheelBodies.push(wheelBody);\n this.wheelForces.push(0); // Position constrain wheels\n\n const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis\n\n const worldPosition = new Vec3();\n this.chassisBody.pointToWorldFrame(position, worldPosition);\n wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel\n\n const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);\n this.wheelAxes.push(axis);\n const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {\n pivotA: position,\n axisA: axis,\n pivotB: Vec3.ZERO,\n axisB: axis,\n collideConnected: false\n });\n this.constraints.push(hingeConstraint);\n return this.wheelBodies.length - 1;\n }\n /**\n * Set the steering value of a wheel.\n * @todo check coordinateSystem\n */\n\n\n setSteeringValue(value, wheelIndex) {\n // Set angle of the hinge axis\n const axis = this.wheelAxes[wheelIndex];\n const c = Math.cos(value);\n const s = Math.sin(value);\n const x = axis.x;\n const z = axis.z;\n this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);\n }\n /**\n * Set the target rotational speed of the hinge constraint.\n */\n\n\n setMotorSpeed(value, wheelIndex) {\n const hingeConstraint = this.constraints[wheelIndex];\n hingeConstraint.enableMotor();\n hingeConstraint.motorTargetVelocity = value;\n }\n /**\n * Set the target rotational speed of the hinge constraint.\n */\n\n\n disableMotor(wheelIndex) {\n const hingeConstraint = this.constraints[wheelIndex];\n hingeConstraint.disableMotor();\n }\n /**\n * Set the wheel force to apply on one of the wheels each time step\n */\n\n\n setWheelForce(value, wheelIndex) {\n this.wheelForces[wheelIndex] = value;\n }\n /**\n * Apply a torque on one of the wheels.\n */\n\n\n applyWheelForce(value, wheelIndex) {\n const axis = this.wheelAxes[wheelIndex];\n const wheelBody = this.wheelBodies[wheelIndex];\n const bodyTorque = wheelBody.torque;\n axis.scale(value, torque);\n wheelBody.vectorToWorldFrame(torque, torque);\n bodyTorque.vadd(torque, bodyTorque);\n }\n /**\n * Add the vehicle including its constraints to the world.\n */\n\n\n addToWorld(world) {\n const constraints = this.constraints;\n const bodies = this.wheelBodies.concat([this.chassisBody]);\n\n for (let i = 0; i < bodies.length; i++) {\n world.addBody(bodies[i]);\n }\n\n for (let i = 0; i < constraints.length; i++) {\n world.addConstraint(constraints[i]);\n }\n\n world.addEventListener('preStep', this._update.bind(this));\n }\n\n _update() {\n const wheelForces = this.wheelForces;\n\n for (let i = 0; i < wheelForces.length; i++) {\n this.applyWheelForce(wheelForces[i], i);\n }\n }\n /**\n * Remove the vehicle including its constraints from the world.\n */\n\n\n removeFromWorld(world) {\n const constraints = this.constraints;\n const bodies = this.wheelBodies.concat([this.chassisBody]);\n\n for (let i = 0; i < bodies.length; i++) {\n world.removeBody(bodies[i]);\n }\n\n for (let i = 0; i < constraints.length; i++) {\n world.removeConstraint(constraints[i]);\n }\n }\n /**\n * Get current rotational velocity of a wheel\n */\n\n\n getWheelSpeed(wheelIndex) {\n const axis = this.wheelAxes[wheelIndex];\n const wheelBody = this.wheelBodies[wheelIndex];\n const w = wheelBody.angularVelocity;\n this.chassisBody.vectorToWorldFrame(axis, worldAxis);\n return w.dot(worldAxis);\n }\n\n}\nconst torque = new Vec3();\nconst worldAxis = new Vec3();\n\n/**\n * Smoothed-particle hydrodynamics system\n * @todo Make parameters customizable in the constructor\n */\nclass SPHSystem {\n /**\n * The particles array.\n */\n\n /**\n * Density of the system (kg/m3).\n * @default 1\n */\n\n /**\n * Distance below which two particles are considered to be neighbors.\n * It should be adjusted so there are about 15-20 neighbor particles within this radius.\n * @default 1\n */\n\n /**\n * @default 1\n */\n\n /**\n * Viscosity of the system.\n * @default 0.01\n */\n\n /**\n * @default 0.000001\n */\n constructor() {\n this.particles = [];\n this.density = 1;\n this.smoothingRadius = 1;\n this.speedOfSound = 1;\n this.viscosity = 0.01;\n this.eps = 0.000001; // Stuff Computed per particle\n\n this.pressures = [];\n this.densities = [];\n this.neighbors = [];\n }\n /**\n * Add a particle to the system.\n */\n\n\n add(particle) {\n this.particles.push(particle);\n\n if (this.neighbors.length < this.particles.length) {\n this.neighbors.push([]);\n }\n }\n /**\n * Remove a particle from the system.\n */\n\n\n remove(particle) {\n const idx = this.particles.indexOf(particle);\n\n if (idx !== -1) {\n this.particles.splice(idx, 1);\n\n if (this.neighbors.length > this.particles.length) {\n this.neighbors.pop();\n }\n }\n }\n /**\n * Get neighbors within smoothing volume, save in the array neighbors\n */\n\n\n getNeighbors(particle, neighbors) {\n const N = this.particles.length;\n const id = particle.id;\n const R2 = this.smoothingRadius * this.smoothingRadius;\n const dist = SPHSystem_getNeighbors_dist;\n\n for (let i = 0; i !== N; i++) {\n const p = this.particles[i];\n p.position.vsub(particle.position, dist);\n\n if (id !== p.id && dist.lengthSquared() < R2) {\n neighbors.push(p);\n }\n }\n }\n\n update() {\n const N = this.particles.length;\n const dist = SPHSystem_update_dist;\n const cs = this.speedOfSound;\n const eps = this.eps;\n\n for (let i = 0; i !== N; i++) {\n const p = this.particles[i]; // Current particle\n\n const neighbors = this.neighbors[i]; // Get neighbors\n\n neighbors.length = 0;\n this.getNeighbors(p, neighbors);\n neighbors.push(this.particles[i]); // Add current too\n\n const numNeighbors = neighbors.length; // Accumulate density for the particle\n\n let sum = 0.0;\n\n for (let j = 0; j !== numNeighbors; j++) {\n //printf(\"Current particle has position %f %f %f\\n\",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());\n p.position.vsub(neighbors[j].position, dist);\n const len = dist.length();\n const weight = this.w(len);\n sum += neighbors[j].mass * weight;\n } // Save\n\n\n this.densities[i] = sum;\n this.pressures[i] = cs * cs * (this.densities[i] - this.density);\n } // Add forces\n // Sum to these accelerations\n\n\n const a_pressure = SPHSystem_update_a_pressure;\n const a_visc = SPHSystem_update_a_visc;\n const gradW = SPHSystem_update_gradW;\n const r_vec = SPHSystem_update_r_vec;\n const u = SPHSystem_update_u;\n\n for (let i = 0; i !== N; i++) {\n const particle = this.particles[i];\n a_pressure.set(0, 0, 0);\n a_visc.set(0, 0, 0); // Init vars\n\n let Pij;\n let nabla;\n\n const neighbors = this.neighbors[i];\n const numNeighbors = neighbors.length; //printf(\"Neighbors: \");\n\n for (let j = 0; j !== numNeighbors; j++) {\n const neighbor = neighbors[j]; //printf(\"%d \",nj);\n // Get r once for all..\n\n particle.position.vsub(neighbor.position, r_vec);\n const r = r_vec.length(); // Pressure contribution\n\n Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));\n this.gradw(r_vec, gradW); // Add to pressure acceleration\n\n gradW.scale(Pij, gradW);\n a_pressure.vadd(gradW, a_pressure); // Viscosity contribution\n\n neighbor.velocity.vsub(particle.velocity, u);\n u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);\n nabla = this.nablaw(r);\n u.scale(nabla, u); // Add to viscosity acceleration\n\n a_visc.vadd(u, a_visc);\n } // Calculate force\n\n\n a_visc.scale(particle.mass, a_visc);\n a_pressure.scale(particle.mass, a_pressure); // Add force to particles\n\n particle.force.vadd(a_visc, particle.force);\n particle.force.vadd(a_pressure, particle.force);\n }\n } // Calculate the weight using the W(r) weightfunction\n\n\n w(r) {\n // 315\n const h = this.smoothingRadius;\n return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;\n } // calculate gradient of the weight function\n\n\n gradw(rVec, resultVec) {\n const r = rVec.length();\n const h = this.smoothingRadius;\n rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);\n } // Calculate nabla(W)\n\n\n nablaw(r) {\n const h = this.smoothingRadius;\n const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);\n return nabla;\n }\n\n}\nconst SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation\n\nconst SPHSystem_update_dist = new Vec3(); // Relative velocity\n\nconst SPHSystem_update_a_pressure = new Vec3();\nconst SPHSystem_update_a_visc = new Vec3();\nconst SPHSystem_update_gradW = new Vec3();\nconst SPHSystem_update_r_vec = new Vec3();\nconst SPHSystem_update_u = new Vec3();\n\n/**\n * Cylinder class.\n * @example\n * const radiusTop = 0.5\n * const radiusBottom = 0.5\n * const height = 2\n * const numSegments = 12\n * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)\n * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })\n * world.addBody(cylinderBody)\n */\n\nclass Cylinder extends ConvexPolyhedron {\n /** The radius of the top of the Cylinder. */\n\n /** The radius of the bottom of the Cylinder. */\n\n /** The height of the Cylinder. */\n\n /** The number of segments to build the cylinder out of. */\n\n /**\n * @param radiusTop The radius of the top of the Cylinder.\n * @param radiusBottom The radius of the bottom of the Cylinder.\n * @param height The height of the Cylinder.\n * @param numSegments The number of segments to build the cylinder out of.\n */\n constructor(radiusTop, radiusBottom, height, numSegments) {\n if (radiusTop === void 0) {\n radiusTop = 1;\n }\n\n if (radiusBottom === void 0) {\n radiusBottom = 1;\n }\n\n if (height === void 0) {\n height = 1;\n }\n\n if (numSegments === void 0) {\n numSegments = 8;\n }\n\n if (radiusTop < 0) {\n throw new Error('The cylinder radiusTop cannot be negative.');\n }\n\n if (radiusBottom < 0) {\n throw new Error('The cylinder radiusBottom cannot be negative.');\n }\n\n const N = numSegments;\n const vertices = [];\n const axes = [];\n const faces = [];\n const bottomface = [];\n const topface = [];\n const cos = Math.cos;\n const sin = Math.sin; // First bottom point\n\n vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));\n bottomface.push(0); // First top point\n\n vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));\n topface.push(1);\n\n for (let i = 0; i < N; i++) {\n const theta = 2 * Math.PI / N * (i + 1);\n const thetaN = 2 * Math.PI / N * (i + 0.5);\n\n if (i < N - 1) {\n // Bottom\n vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));\n bottomface.push(2 * i + 2); // Top\n\n vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));\n topface.push(2 * i + 3); // Face\n\n faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);\n } else {\n faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect\n } // Axis: we can cut off half of them if we have even number of segments\n\n\n if (N % 2 === 1 || i < N / 2) {\n axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));\n }\n }\n\n faces.push(bottomface);\n axes.push(new Vec3(0, 1, 0)); // Reorder top face\n\n const temp = [];\n\n for (let i = 0; i < topface.length; i++) {\n temp.push(topface[topface.length - i - 1]);\n }\n\n faces.push(temp);\n super({\n vertices,\n faces,\n axes\n });\n this.type = Shape.types.CYLINDER;\n this.radiusTop = radiusTop;\n this.radiusBottom = radiusBottom;\n this.height = height;\n this.numSegments = numSegments;\n }\n\n}\n\n/**\n * Particle shape.\n * @example\n * const particleShape = new CANNON.Particle()\n * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })\n * world.addBody(particleBody)\n */\nclass Particle extends Shape {\n constructor() {\n super({\n type: Shape.types.PARTICLE\n });\n }\n /**\n * calculateLocalInertia\n */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.set(0, 0, 0);\n return target;\n }\n\n volume() {\n return 0;\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = 0;\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n // Get each axis max\n min.copy(pos);\n max.copy(pos);\n }\n\n}\n\n/**\n * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.\n * @example\n * const planeShape = new CANNON.Plane()\n * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape })\n * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up\n * world.addBody(planeBody)\n */\nclass Plane extends Shape {\n /** worldNormal */\n\n /** worldNormalNeedsUpdate */\n constructor() {\n super({\n type: Shape.types.PLANE\n }); // World oriented normal\n\n this.worldNormal = new Vec3();\n this.worldNormalNeedsUpdate = true;\n this.boundingSphereRadius = Number.MAX_VALUE;\n }\n /** computeWorldNormal */\n\n\n computeWorldNormal(quat) {\n const n = this.worldNormal;\n n.set(0, 0, 1);\n quat.vmult(n, n);\n this.worldNormalNeedsUpdate = false;\n }\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n return target;\n }\n\n volume() {\n return (// The plane is infinite...\n Number.MAX_VALUE\n );\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n // The plane AABB is infinite, except if the normal is pointing along any axis\n tempNormal.set(0, 0, 1); // Default plane normal is z\n\n quat.vmult(tempNormal, tempNormal);\n const maxVal = Number.MAX_VALUE;\n min.set(-maxVal, -maxVal, -maxVal);\n max.set(maxVal, maxVal, maxVal);\n\n if (tempNormal.x === 1) {\n max.x = pos.x;\n } else if (tempNormal.x === -1) {\n min.x = pos.x;\n }\n\n if (tempNormal.y === 1) {\n max.y = pos.y;\n } else if (tempNormal.y === -1) {\n min.y = pos.y;\n }\n\n if (tempNormal.z === 1) {\n max.z = pos.z;\n } else if (tempNormal.z === -1) {\n min.z = pos.z;\n }\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = Number.MAX_VALUE;\n }\n\n}\nconst tempNormal = new Vec3();\n\n/**\n * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.\n * @todo Should be possible to use along all axes, not just y\n * @todo should be possible to scale along all axes\n * @todo Refactor elementSize to elementSizeX and elementSizeY\n *\n * @example\n * // Generate some height data (y-values).\n * const data = []\n * for (let i = 0; i < 1000; i++) {\n * const y = 0.5 * Math.cos(0.2 * i)\n * data.push(y)\n * }\n *\n * // Create the heightfield shape\n * const heightfieldShape = new CANNON.Heightfield(data, {\n * elementSize: 1 // Distance between the data points in X and Y directions\n * })\n * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })\n * world.addBody(heightfieldBody)\n */\nclass Heightfield extends Shape {\n /**\n * An array of numbers, or height values, that are spread out along the x axis.\n */\n\n /**\n * Max value of the data points in the data array.\n */\n\n /**\n * Minimum value of the data points in the data array.\n */\n\n /**\n * World spacing between the data points in X and Y direction.\n * @todo elementSizeX and Y\n * @default 1\n */\n\n /**\n * @default true\n */\n\n /**\n * @param data An array of numbers, or height values, that are spread out along the x axis.\n */\n constructor(data, options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n maxValue: null,\n minValue: null,\n elementSize: 1\n });\n super({\n type: Shape.types.HEIGHTFIELD\n });\n this.data = data;\n this.maxValue = options.maxValue;\n this.minValue = options.minValue;\n this.elementSize = options.elementSize;\n\n if (options.minValue === null) {\n this.updateMinValue();\n }\n\n if (options.maxValue === null) {\n this.updateMaxValue();\n }\n\n this.cacheEnabled = true;\n this.pillarConvex = new ConvexPolyhedron();\n this.pillarOffset = new Vec3();\n this.updateBoundingSphereRadius(); // \"i_j_isUpper\" => { convex: ..., offset: ... }\n // for example:\n // _cachedPillars[\"0_2_1\"]\n\n this._cachedPillars = {};\n }\n /**\n * Call whenever you change the data array.\n */\n\n\n update() {\n this._cachedPillars = {};\n }\n /**\n * Update the `minValue` property\n */\n\n\n updateMinValue() {\n const data = this.data;\n let minValue = data[0][0];\n\n for (let i = 0; i !== data.length; i++) {\n for (let j = 0; j !== data[i].length; j++) {\n const v = data[i][j];\n\n if (v < minValue) {\n minValue = v;\n }\n }\n }\n\n this.minValue = minValue;\n }\n /**\n * Update the `maxValue` property\n */\n\n\n updateMaxValue() {\n const data = this.data;\n let maxValue = data[0][0];\n\n for (let i = 0; i !== data.length; i++) {\n for (let j = 0; j !== data[i].length; j++) {\n const v = data[i][j];\n\n if (v > maxValue) {\n maxValue = v;\n }\n }\n }\n\n this.maxValue = maxValue;\n }\n /**\n * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.\n */\n\n\n setHeightValueAtIndex(xi, yi, value) {\n const data = this.data;\n data[xi][yi] = value; // Invalidate cache\n\n this.clearCachedConvexTrianglePillar(xi, yi, false);\n\n if (xi > 0) {\n this.clearCachedConvexTrianglePillar(xi - 1, yi, true);\n this.clearCachedConvexTrianglePillar(xi - 1, yi, false);\n }\n\n if (yi > 0) {\n this.clearCachedConvexTrianglePillar(xi, yi - 1, true);\n this.clearCachedConvexTrianglePillar(xi, yi - 1, false);\n }\n\n if (yi > 0 && xi > 0) {\n this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);\n }\n }\n /**\n * Get max/min in a rectangle in the matrix data\n * @param result An array to store the results in.\n * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.\n */\n\n\n getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result) {\n if (result === void 0) {\n result = [];\n }\n\n // Get max and min of the data\n const data = this.data; // Set first value\n\n let max = this.minValue;\n\n for (let i = iMinX; i <= iMaxX; i++) {\n for (let j = iMinY; j <= iMaxY; j++) {\n const height = data[i][j];\n\n if (height > max) {\n max = height;\n }\n }\n }\n\n result[0] = this.minValue;\n result[1] = max;\n }\n /**\n * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.\n * @param result Two-element array\n * @param clamp If the position should be clamped to the heightfield edge.\n */\n\n\n getIndexOfPosition(x, y, result, clamp) {\n // Get the index of the data points to test against\n const w = this.elementSize;\n const data = this.data;\n let xi = Math.floor(x / w);\n let yi = Math.floor(y / w);\n result[0] = xi;\n result[1] = yi;\n\n if (clamp) {\n // Clamp index to edges\n if (xi < 0) {\n xi = 0;\n }\n\n if (yi < 0) {\n yi = 0;\n }\n\n if (xi >= data.length - 1) {\n xi = data.length - 1;\n }\n\n if (yi >= data[0].length - 1) {\n yi = data[0].length - 1;\n }\n } // Bail out if we are out of the terrain\n\n\n if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {\n return false;\n }\n\n return true;\n }\n\n getTriangleAt(x, y, edgeClamp, a, b, c) {\n const idx = getHeightAt_idx;\n this.getIndexOfPosition(x, y, idx, edgeClamp);\n let xi = idx[0];\n let yi = idx[1];\n const data = this.data;\n\n if (edgeClamp) {\n xi = Math.min(data.length - 2, Math.max(0, xi));\n yi = Math.min(data[0].length - 2, Math.max(0, yi));\n }\n\n const elementSize = this.elementSize;\n const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;\n const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;\n const upper = lowerDist2 > upperDist2;\n this.getTriangle(xi, yi, upper, a, b, c);\n return upper;\n }\n\n getNormalAt(x, y, edgeClamp, result) {\n const a = getNormalAt_a;\n const b = getNormalAt_b;\n const c = getNormalAt_c;\n const e0 = getNormalAt_e0;\n const e1 = getNormalAt_e1;\n this.getTriangleAt(x, y, edgeClamp, a, b, c);\n b.vsub(a, e0);\n c.vsub(a, e1);\n e0.cross(e1, result);\n result.normalize();\n }\n /**\n * Get an AABB of a square in the heightfield\n * @param xi\n * @param yi\n * @param result\n */\n\n\n getAabbAtIndex(xi, yi, _ref) {\n let {\n lowerBound,\n upperBound\n } = _ref;\n const data = this.data;\n const elementSize = this.elementSize;\n lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]);\n upperBound.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);\n }\n /**\n * Get the height in the heightfield at a given position\n */\n\n\n getHeightAt(x, y, edgeClamp) {\n const data = this.data;\n const a = getHeightAt_a;\n const b = getHeightAt_b;\n const c = getHeightAt_c;\n const idx = getHeightAt_idx;\n this.getIndexOfPosition(x, y, idx, edgeClamp);\n let xi = idx[0];\n let yi = idx[1];\n\n if (edgeClamp) {\n xi = Math.min(data.length - 2, Math.max(0, xi));\n yi = Math.min(data[0].length - 2, Math.max(0, yi));\n }\n\n const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);\n barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);\n const w = getHeightAt_weights;\n\n if (upper) {\n // Top triangle verts\n return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;\n } else {\n // Top triangle verts\n return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;\n }\n }\n\n getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) {\n return `${xi}_${yi}_${getUpperTriangle ? 1 : 0}`;\n }\n\n getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {\n return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];\n }\n\n setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) {\n this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {\n convex,\n offset\n };\n }\n\n clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {\n delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];\n }\n /**\n * Get a triangle from the heightfield\n */\n\n\n getTriangle(xi, yi, upper, a, b, c) {\n const data = this.data;\n const elementSize = this.elementSize;\n\n if (upper) {\n // Top triangle verts\n a.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);\n b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);\n c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);\n } else {\n // Top triangle verts\n a.set(xi * elementSize, yi * elementSize, data[xi][yi]);\n b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);\n c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);\n }\n }\n /**\n * Get a triangle in the terrain in the form of a triangular convex shape.\n */\n\n\n getConvexTrianglePillar(xi, yi, getUpperTriangle) {\n let result = this.pillarConvex;\n let offsetResult = this.pillarOffset;\n\n if (this.cacheEnabled) {\n const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);\n\n if (data) {\n this.pillarConvex = data.convex;\n this.pillarOffset = data.offset;\n return;\n }\n\n result = new ConvexPolyhedron();\n offsetResult = new Vec3();\n this.pillarConvex = result;\n this.pillarOffset = offsetResult;\n }\n\n const data = this.data;\n const elementSize = this.elementSize;\n const faces = result.faces; // Reuse verts if possible\n\n result.vertices.length = 6;\n\n for (let i = 0; i < 6; i++) {\n if (!result.vertices[i]) {\n result.vertices[i] = new Vec3();\n }\n } // Reuse faces if possible\n\n\n faces.length = 5;\n\n for (let i = 0; i < 5; i++) {\n if (!faces[i]) {\n faces[i] = [];\n }\n }\n\n const verts = result.vertices;\n const h = (Math.min(data[xi][yi], data[xi + 1][yi], data[xi][yi + 1], data[xi + 1][yi + 1]) - this.minValue) / 2 + this.minValue;\n\n if (!getUpperTriangle) {\n // Center of the triangle pillar - all polygons are given relative to this one\n offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle\n (yi + 0.25) * elementSize, h // vertical center\n ); // Top triangle verts\n\n verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);\n verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);\n verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts\n\n verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);\n verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);\n verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle\n\n faces[0][0] = 0;\n faces[0][1] = 1;\n faces[0][2] = 2; // bottom triangle\n\n faces[1][0] = 5;\n faces[1][1] = 4;\n faces[1][2] = 3; // -x facing quad\n\n faces[2][0] = 0;\n faces[2][1] = 2;\n faces[2][2] = 5;\n faces[2][3] = 3; // -y facing quad\n\n faces[3][0] = 1;\n faces[3][1] = 0;\n faces[3][2] = 3;\n faces[3][3] = 4; // +xy facing quad\n\n faces[4][0] = 4;\n faces[4][1] = 5;\n faces[4][2] = 2;\n faces[4][3] = 1;\n } else {\n // Center of the triangle pillar - all polygons are given relative to this one\n offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle\n (yi + 0.75) * elementSize, h // vertical center\n ); // Top triangle verts\n\n verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);\n verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);\n verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts\n\n verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);\n verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);\n verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle\n\n faces[0][0] = 0;\n faces[0][1] = 1;\n faces[0][2] = 2; // bottom triangle\n\n faces[1][0] = 5;\n faces[1][1] = 4;\n faces[1][2] = 3; // +x facing quad\n\n faces[2][0] = 2;\n faces[2][1] = 5;\n faces[2][2] = 3;\n faces[2][3] = 0; // +y facing quad\n\n faces[3][0] = 3;\n faces[3][1] = 4;\n faces[3][2] = 1;\n faces[3][3] = 0; // -xy facing quad\n\n faces[4][0] = 1;\n faces[4][1] = 4;\n faces[4][2] = 5;\n faces[4][3] = 2;\n }\n\n result.computeNormals();\n result.computeEdges();\n result.updateBoundingSphereRadius();\n this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);\n }\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.set(0, 0, 0);\n return target;\n }\n\n volume() {\n return (// The terrain is infinite\n Number.MAX_VALUE\n );\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n /** @TODO do it properly */\n min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n }\n\n updateBoundingSphereRadius() {\n // Use the bounding box of the min/max values\n const data = this.data;\n const s = this.elementSize;\n this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).length();\n }\n /**\n * Sets the height values from an image. Currently only supported in browser.\n */\n\n\n setHeightsFromImage(image, scale) {\n const {\n x,\n z,\n y\n } = scale;\n const canvas = document.createElement('canvas');\n canvas.width = image.width;\n canvas.height = image.height;\n const context = canvas.getContext('2d');\n context.drawImage(image, 0, 0);\n const imageData = context.getImageData(0, 0, image.width, image.height);\n const matrix = this.data;\n matrix.length = 0;\n this.elementSize = Math.abs(x) / imageData.width;\n\n for (let i = 0; i < imageData.height; i++) {\n const row = [];\n\n for (let j = 0; j < imageData.width; j++) {\n const a = imageData.data[(i * imageData.height + j) * 4];\n const b = imageData.data[(i * imageData.height + j) * 4 + 1];\n const c = imageData.data[(i * imageData.height + j) * 4 + 2];\n const height = (a + b + c) / 4 / 255 * z;\n\n if (x < 0) {\n row.push(height);\n } else {\n row.unshift(height);\n }\n }\n\n if (y < 0) {\n matrix.unshift(row);\n } else {\n matrix.push(row);\n }\n }\n\n this.updateMaxValue();\n this.updateMinValue();\n this.update();\n }\n\n}\nconst getHeightAt_idx = [];\nconst getHeightAt_weights = new Vec3();\nconst getHeightAt_a = new Vec3();\nconst getHeightAt_b = new Vec3();\nconst getHeightAt_c = new Vec3();\nconst getNormalAt_a = new Vec3();\nconst getNormalAt_b = new Vec3();\nconst getNormalAt_c = new Vec3();\nconst getNormalAt_e0 = new Vec3();\nconst getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system\n\nfunction barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) {\n result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));\n result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));\n result.z = 1 - result.x - result.y;\n}\n\n/**\n * OctreeNode\n */\nclass OctreeNode {\n /** The root node */\n\n /** Boundary of this node */\n\n /** Contained data at the current node level */\n\n /** Children to this node */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.root = options.root || null;\n this.aabb = options.aabb ? options.aabb.clone() : new AABB();\n this.data = [];\n this.children = [];\n }\n /**\n * reset\n */\n\n\n reset() {\n this.children.length = this.data.length = 0;\n }\n /**\n * Insert data into this node\n * @return True if successful, otherwise false\n */\n\n\n insert(aabb, elementData, level) {\n if (level === void 0) {\n level = 0;\n }\n\n const nodeData = this.data; // Ignore objects that do not belong in this node\n\n if (!this.aabb.contains(aabb)) {\n return false; // object cannot be added\n }\n\n const children = this.children;\n const maxDepth = this.maxDepth || this.root.maxDepth;\n\n if (level < maxDepth) {\n // Subdivide if there are no children yet\n let subdivided = false;\n\n if (!children.length) {\n this.subdivide();\n subdivided = true;\n } // add to whichever node will accept it\n\n\n for (let i = 0; i !== 8; i++) {\n if (children[i].insert(aabb, elementData, level + 1)) {\n return true;\n }\n }\n\n if (subdivided) {\n // No children accepted! Might as well just remove em since they contain none\n children.length = 0;\n }\n } // Too deep, or children didnt want it. add it in current node\n\n\n nodeData.push(elementData);\n return true;\n }\n /**\n * Create 8 equally sized children nodes and put them in the `children` array.\n */\n\n\n subdivide() {\n const aabb = this.aabb;\n const l = aabb.lowerBound;\n const u = aabb.upperBound;\n const children = this.children;\n children.push(new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 0, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 0, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 1, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 1, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 1, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 0, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 0, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 1, 0)\n })\n }));\n u.vsub(l, halfDiagonal);\n halfDiagonal.scale(0.5, halfDiagonal);\n const root = this.root || this;\n\n for (let i = 0; i !== 8; i++) {\n const child = children[i]; // Set current node as root\n\n child.root = root; // Compute bounds\n\n const lowerBound = child.aabb.lowerBound;\n lowerBound.x *= halfDiagonal.x;\n lowerBound.y *= halfDiagonal.y;\n lowerBound.z *= halfDiagonal.z;\n lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal\n\n lowerBound.vadd(halfDiagonal, child.aabb.upperBound);\n }\n }\n /**\n * Get all data, potentially within an AABB\n * @return The \"result\" object\n */\n\n\n aabbQuery(aabb, result) {\n this.data; // abort if the range does not intersect this node\n // if (!this.aabb.overlaps(aabb)){\n // return result;\n // }\n // Add objects at this level\n // Array.prototype.push.apply(result, nodeData);\n // Add child data\n // @todo unwrap recursion into a queue / loop, that's faster in JS\n\n this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {\n // children[i].aabbQuery(aabb, result);\n // }\n\n const queue = [this];\n\n while (queue.length) {\n const node = queue.pop();\n\n if (node.aabb.overlaps(aabb)) {\n Array.prototype.push.apply(result, node.data);\n }\n\n Array.prototype.push.apply(queue, node.children);\n }\n\n return result;\n }\n /**\n * Get all data, potentially intersected by a ray.\n * @return The \"result\" object\n */\n\n\n rayQuery(ray, treeTransform, result) {\n // Use aabb query for now.\n\n /** @todo implement real ray query which needs less lookups */\n ray.getAABB(tmpAABB);\n tmpAABB.toLocalFrame(treeTransform, tmpAABB);\n this.aabbQuery(tmpAABB, result);\n return result;\n }\n /**\n * removeEmptyNodes\n */\n\n\n removeEmptyNodes() {\n for (let i = this.children.length - 1; i >= 0; i--) {\n this.children[i].removeEmptyNodes();\n\n if (!this.children[i].children.length && !this.children[i].data.length) {\n this.children.splice(i, 1);\n }\n }\n }\n\n}\n/**\n * Octree\n */\n\n\nclass Octree extends OctreeNode {\n /**\n * Maximum subdivision depth\n * @default 8\n */\n\n /**\n * @param aabb The total AABB of the tree\n */\n constructor(aabb, options) {\n if (options === void 0) {\n options = {};\n }\n\n super({\n root: null,\n aabb\n });\n this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;\n }\n\n}\nconst halfDiagonal = new Vec3();\nconst tmpAABB = new AABB();\n\n/**\n * Trimesh.\n * @example\n * // How to make a mesh with a single triangle\n * const vertices = [\n * 0, 0, 0, // vertex 0\n * 1, 0, 0, // vertex 1\n * 0, 1, 0 // vertex 2\n * ]\n * const indices = [\n * 0, 1, 2 // triangle 0\n * ]\n * const trimeshShape = new CANNON.Trimesh(vertices, indices)\n */\nclass Trimesh extends Shape {\n /**\n * vertices\n */\n\n /**\n * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.\n */\n\n /**\n * The normals data.\n */\n\n /**\n * The local AABB of the mesh.\n */\n\n /**\n * References to vertex pairs, making up all unique edges in the trimesh.\n */\n\n /**\n * Local scaling of the mesh. Use .setScale() to set it.\n */\n\n /**\n * The indexed triangles. Use .updateTree() to update it.\n */\n constructor(vertices, indices) {\n super({\n type: Shape.types.TRIMESH\n });\n this.vertices = new Float32Array(vertices);\n this.indices = new Int16Array(indices);\n this.normals = new Float32Array(indices.length);\n this.aabb = new AABB();\n this.edges = null;\n this.scale = new Vec3(1, 1, 1);\n this.tree = new Octree();\n this.updateEdges();\n this.updateNormals();\n this.updateAABB();\n this.updateBoundingSphereRadius();\n this.updateTree();\n }\n /**\n * updateTree\n */\n\n\n updateTree() {\n const tree = this.tree;\n tree.reset();\n tree.aabb.copy(this.aabb);\n const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled\n\n tree.aabb.lowerBound.x *= 1 / scale.x;\n tree.aabb.lowerBound.y *= 1 / scale.y;\n tree.aabb.lowerBound.z *= 1 / scale.z;\n tree.aabb.upperBound.x *= 1 / scale.x;\n tree.aabb.upperBound.y *= 1 / scale.y;\n tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles\n\n const triangleAABB = new AABB();\n const a = new Vec3();\n const b = new Vec3();\n const c = new Vec3();\n const points = [a, b, c];\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n //this.getTriangleVertices(i, a, b, c);\n // Get unscaled triangle verts\n const i3 = i * 3;\n\n this._getUnscaledVertex(this.indices[i3], a);\n\n this._getUnscaledVertex(this.indices[i3 + 1], b);\n\n this._getUnscaledVertex(this.indices[i3 + 2], c);\n\n triangleAABB.setFromPoints(points);\n tree.insert(triangleAABB, i);\n }\n\n tree.removeEmptyNodes();\n }\n /**\n * Get triangles in a local AABB from the trimesh.\n * @param result An array of integers, referencing the queried triangles.\n */\n\n\n getTrianglesInAABB(aabb, result) {\n unscaledAABB.copy(aabb); // Scale it to local\n\n const scale = this.scale;\n const isx = scale.x;\n const isy = scale.y;\n const isz = scale.z;\n const l = unscaledAABB.lowerBound;\n const u = unscaledAABB.upperBound;\n l.x /= isx;\n l.y /= isy;\n l.z /= isz;\n u.x /= isx;\n u.y /= isy;\n u.z /= isz;\n return this.tree.aabbQuery(unscaledAABB, result);\n }\n /**\n * setScale\n */\n\n\n setScale(scale) {\n const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;\n const isUniform = scale.x === scale.y && scale.y === scale.z;\n\n if (!(wasUniform && isUniform)) {\n // Non-uniform scaling. Need to update normals.\n this.updateNormals();\n }\n\n this.scale.copy(scale);\n this.updateAABB();\n this.updateBoundingSphereRadius();\n }\n /**\n * Compute the normals of the faces. Will save in the `.normals` array.\n */\n\n\n updateNormals() {\n const n = computeNormals_n; // Generate normals\n\n const normals = this.normals;\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n const i3 = i * 3;\n const a = this.indices[i3];\n const b = this.indices[i3 + 1];\n const c = this.indices[i3 + 2];\n this.getVertex(a, va);\n this.getVertex(b, vb);\n this.getVertex(c, vc);\n Trimesh.computeNormal(vb, va, vc, n);\n normals[i3] = n.x;\n normals[i3 + 1] = n.y;\n normals[i3 + 2] = n.z;\n }\n }\n /**\n * Update the `.edges` property\n */\n\n\n updateEdges() {\n const edges = {};\n\n const add = (a, b) => {\n const key = a < b ? `${a}_${b}` : `${b}_${a}`;\n edges[key] = true;\n };\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n const i3 = i * 3;\n const a = this.indices[i3];\n const b = this.indices[i3 + 1];\n const c = this.indices[i3 + 2];\n add(a, b);\n add(b, c);\n add(c, a);\n }\n\n const keys = Object.keys(edges);\n this.edges = new Int16Array(keys.length * 2);\n\n for (let i = 0; i < keys.length; i++) {\n const indices = keys[i].split('_');\n this.edges[2 * i] = parseInt(indices[0], 10);\n this.edges[2 * i + 1] = parseInt(indices[1], 10);\n }\n }\n /**\n * Get an edge vertex\n * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.\n * @param vertexStore Where to store the result\n */\n\n\n getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {\n const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];\n this.getVertex(vertexIndex, vertexStore);\n }\n /**\n * Get a vector along an edge.\n */\n\n\n getEdgeVector(edgeIndex, vectorStore) {\n const va = getEdgeVector_va;\n const vb = getEdgeVector_vb;\n this.getEdgeVertex(edgeIndex, 0, va);\n this.getEdgeVertex(edgeIndex, 1, vb);\n vb.vsub(va, vectorStore);\n }\n /**\n * Get face normal given 3 vertices\n */\n\n\n static computeNormal(va, vb, vc, target) {\n vb.vsub(va, ab);\n vc.vsub(vb, cb);\n cb.cross(ab, target);\n\n if (!target.isZero()) {\n target.normalize();\n }\n }\n /**\n * Get vertex i.\n * @return The \"out\" vector object\n */\n\n\n getVertex(i, out) {\n const scale = this.scale;\n\n this._getUnscaledVertex(i, out);\n\n out.x *= scale.x;\n out.y *= scale.y;\n out.z *= scale.z;\n return out;\n }\n /**\n * Get raw vertex i\n * @return The \"out\" vector object\n */\n\n\n _getUnscaledVertex(i, out) {\n const i3 = i * 3;\n const vertices = this.vertices;\n return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);\n }\n /**\n * Get a vertex from the trimesh,transformed by the given position and quaternion.\n * @return The \"out\" vector object\n */\n\n\n getWorldVertex(i, pos, quat, out) {\n this.getVertex(i, out);\n Transform.pointToWorldFrame(pos, quat, out, out);\n return out;\n }\n /**\n * Get the three vertices for triangle i.\n */\n\n\n getTriangleVertices(i, a, b, c) {\n const i3 = i * 3;\n this.getVertex(this.indices[i3], a);\n this.getVertex(this.indices[i3 + 1], b);\n this.getVertex(this.indices[i3 + 2], c);\n }\n /**\n * Compute the normal of triangle i.\n * @return The \"target\" vector object\n */\n\n\n getNormal(i, target) {\n const i3 = i * 3;\n return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);\n }\n /**\n * @return The \"target\" vector object\n */\n\n\n calculateLocalInertia(mass, target) {\n // Approximate with box inertia\n // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it\n this.computeLocalAABB(cli_aabb);\n const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;\n const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;\n const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;\n return target.set(1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x));\n }\n /**\n * Compute the local AABB for the trimesh\n */\n\n\n computeLocalAABB(aabb) {\n const l = aabb.lowerBound;\n const u = aabb.upperBound;\n const n = this.vertices.length;\n this.vertices;\n const v = computeLocalAABB_worldVert;\n this.getVertex(0, v);\n l.copy(v);\n u.copy(v);\n\n for (let i = 0; i !== n; i++) {\n this.getVertex(i, v);\n\n if (v.x < l.x) {\n l.x = v.x;\n } else if (v.x > u.x) {\n u.x = v.x;\n }\n\n if (v.y < l.y) {\n l.y = v.y;\n } else if (v.y > u.y) {\n u.y = v.y;\n }\n\n if (v.z < l.z) {\n l.z = v.z;\n } else if (v.z > u.z) {\n u.z = v.z;\n }\n }\n }\n /**\n * Update the `.aabb` property\n */\n\n\n updateAABB() {\n this.computeLocalAABB(this.aabb);\n }\n /**\n * Will update the `.boundingSphereRadius` property\n */\n\n\n updateBoundingSphereRadius() {\n // Assume points are distributed with local (0,0,0) as center\n let max2 = 0;\n const vertices = this.vertices;\n const v = new Vec3();\n\n for (let i = 0, N = vertices.length / 3; i !== N; i++) {\n this.getVertex(i, v);\n const norm2 = v.lengthSquared();\n\n if (norm2 > max2) {\n max2 = norm2;\n }\n }\n\n this.boundingSphereRadius = Math.sqrt(max2);\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n /*\n const n = this.vertices.length / 3,\n verts = this.vertices;\n const minx,miny,minz,maxx,maxy,maxz;\n const v = tempWorldVertex;\n for(let i=0; i maxx || maxx===undefined){\n maxx = v.x;\n }\n if (v.y < miny || miny===undefined){\n miny = v.y;\n } else if(v.y > maxy || maxy===undefined){\n maxy = v.y;\n }\n if (v.z < minz || minz===undefined){\n minz = v.z;\n } else if(v.z > maxz || maxz===undefined){\n maxz = v.z;\n }\n }\n min.set(minx,miny,minz);\n max.set(maxx,maxy,maxz);\n */\n // Faster approximation using local AABB\n const frame = calculateWorldAABB_frame;\n const result = calculateWorldAABB_aabb;\n frame.position = pos;\n frame.quaternion = quat;\n this.aabb.toWorldFrame(frame, result);\n min.copy(result.lowerBound);\n max.copy(result.upperBound);\n }\n /**\n * Get approximate volume\n */\n\n\n volume() {\n return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;\n }\n /**\n * Create a Trimesh instance, shaped as a torus.\n */\n\n\n static createTorus(radius, tube, radialSegments, tubularSegments, arc) {\n if (radius === void 0) {\n radius = 1;\n }\n\n if (tube === void 0) {\n tube = 0.5;\n }\n\n if (radialSegments === void 0) {\n radialSegments = 8;\n }\n\n if (tubularSegments === void 0) {\n tubularSegments = 6;\n }\n\n if (arc === void 0) {\n arc = Math.PI * 2;\n }\n\n const vertices = [];\n const indices = [];\n\n for (let j = 0; j <= radialSegments; j++) {\n for (let i = 0; i <= tubularSegments; i++) {\n const u = i / tubularSegments * arc;\n const v = j / radialSegments * Math.PI * 2;\n const x = (radius + tube * Math.cos(v)) * Math.cos(u);\n const y = (radius + tube * Math.cos(v)) * Math.sin(u);\n const z = tube * Math.sin(v);\n vertices.push(x, y, z);\n }\n }\n\n for (let j = 1; j <= radialSegments; j++) {\n for (let i = 1; i <= tubularSegments; i++) {\n const a = (tubularSegments + 1) * j + i - 1;\n const b = (tubularSegments + 1) * (j - 1) + i - 1;\n const c = (tubularSegments + 1) * (j - 1) + i;\n const d = (tubularSegments + 1) * j + i;\n indices.push(a, b, d);\n indices.push(b, c, d);\n }\n }\n\n return new Trimesh(vertices, indices);\n }\n\n}\nconst computeNormals_n = new Vec3();\nconst unscaledAABB = new AABB();\nconst getEdgeVector_va = new Vec3();\nconst getEdgeVector_vb = new Vec3();\nconst cb = new Vec3();\nconst ab = new Vec3();\nconst va = new Vec3();\nconst vb = new Vec3();\nconst vc = new Vec3();\nconst cli_aabb = new AABB();\nconst computeLocalAABB_worldVert = new Vec3();\nconst calculateWorldAABB_frame = new Transform();\nconst calculateWorldAABB_aabb = new AABB();\n\n/**\n * Constraint equation solver base class.\n */\nclass Solver {\n /**\n * All equations to be solved\n */\n\n /**\n * @todo remove useless constructor\n */\n constructor() {\n this.equations = [];\n }\n /**\n * Should be implemented in subclasses!\n * @todo use abstract\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n return (// Should return the number of iterations done!\n 0\n );\n }\n /**\n * Add an equation\n */\n\n\n addEquation(eq) {\n if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {\n this.equations.push(eq);\n }\n }\n /**\n * Remove an equation\n */\n\n\n removeEquation(eq) {\n const eqs = this.equations;\n const i = eqs.indexOf(eq);\n\n if (i !== -1) {\n eqs.splice(i, 1);\n }\n }\n /**\n * Add all equations\n */\n\n\n removeAllEquations() {\n this.equations.length = 0;\n }\n\n}\n\n/**\n * Constraint equation Gauss-Seidel solver.\n * @todo The spook parameters should be specified for each constraint, not globally.\n * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf\n */\nclass GSSolver extends Solver {\n /**\n * The number of solver iterations determines quality of the constraints in the world.\n * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.\n */\n\n /**\n * When tolerance is reached, the system is assumed to be converged.\n */\n\n /**\n * @todo remove useless constructor\n */\n constructor() {\n super();\n this.iterations = 10;\n this.tolerance = 1e-7;\n }\n /**\n * Solve\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n let iter = 0;\n const maxIter = this.iterations;\n const tolSquared = this.tolerance * this.tolerance;\n const equations = this.equations;\n const Neq = equations.length;\n const bodies = world.bodies;\n const Nbodies = bodies.length;\n const h = dt;\n let B;\n let invC;\n let deltalambda;\n let deltalambdaTot;\n let GWlambda;\n let lambdaj; // Update solve mass\n\n if (Neq !== 0) {\n for (let i = 0; i !== Nbodies; i++) {\n bodies[i].updateSolveMassProperties();\n }\n } // Things that do not change during iteration can be computed once\n\n\n const invCs = GSSolver_solve_invCs;\n const Bs = GSSolver_solve_Bs;\n const lambda = GSSolver_solve_lambda;\n invCs.length = Neq;\n Bs.length = Neq;\n lambda.length = Neq;\n\n for (let i = 0; i !== Neq; i++) {\n const c = equations[i];\n lambda[i] = 0.0;\n Bs[i] = c.computeB(h);\n invCs[i] = 1.0 / c.computeC();\n }\n\n if (Neq !== 0) {\n // Reset vlambda\n for (let i = 0; i !== Nbodies; i++) {\n const b = bodies[i];\n const vlambda = b.vlambda;\n const wlambda = b.wlambda;\n vlambda.set(0, 0, 0);\n wlambda.set(0, 0, 0);\n } // Iterate over equations\n\n\n for (iter = 0; iter !== maxIter; iter++) {\n // Accumulate the total error for each iteration.\n deltalambdaTot = 0.0;\n\n for (let j = 0; j !== Neq; j++) {\n const c = equations[j]; // Compute iteration\n\n B = Bs[j];\n invC = invCs[j];\n lambdaj = lambda[j];\n GWlambda = c.computeGWlambda();\n deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval\n\n if (lambdaj + deltalambda < c.minForce) {\n deltalambda = c.minForce - lambdaj;\n } else if (lambdaj + deltalambda > c.maxForce) {\n deltalambda = c.maxForce - lambdaj;\n }\n\n lambda[j] += deltalambda;\n deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)\n\n c.addToWlambda(deltalambda);\n } // If the total error is small enough - stop iterate\n\n\n if (deltalambdaTot * deltalambdaTot < tolSquared) {\n break;\n }\n } // Add result to velocity\n\n\n for (let i = 0; i !== Nbodies; i++) {\n const b = bodies[i];\n const v = b.velocity;\n const w = b.angularVelocity;\n b.vlambda.vmul(b.linearFactor, b.vlambda);\n v.vadd(b.vlambda, v);\n b.wlambda.vmul(b.angularFactor, b.wlambda);\n w.vadd(b.wlambda, w);\n } // Set the `.multiplier` property of each equation\n\n\n let l = equations.length;\n const invDt = 1 / h;\n\n while (l--) {\n equations[l].multiplier = lambda[l] * invDt;\n }\n }\n\n return iter;\n }\n\n} // Just temporary number holders that we want to reuse each iteration.\n\nconst GSSolver_solve_lambda = [];\nconst GSSolver_solve_invCs = [];\nconst GSSolver_solve_Bs = [];\n\n/**\n * Splits the equations into islands and solves them independently. Can improve performance.\n */\nclass SplitSolver extends Solver {\n /**\n * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.\n */\n\n /**\n * When tolerance is reached, the system is assumed to be converged.\n */\n\n /** subsolver */\n constructor(subsolver) {\n super();\n this.iterations = 10;\n this.tolerance = 1e-7;\n this.subsolver = subsolver;\n this.nodes = [];\n this.nodePool = []; // Create needed nodes, reuse if possible\n\n while (this.nodePool.length < 128) {\n this.nodePool.push(this.createNode());\n }\n }\n /**\n * createNode\n */\n\n\n createNode() {\n return {\n body: null,\n children: [],\n eqs: [],\n visited: false\n };\n }\n /**\n * Solve the subsystems\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n const nodes = SplitSolver_solve_nodes;\n const nodePool = this.nodePool;\n const bodies = world.bodies;\n const equations = this.equations;\n const Neq = equations.length;\n const Nbodies = bodies.length;\n const subsolver = this.subsolver; // Create needed nodes, reuse if possible\n\n while (nodePool.length < Nbodies) {\n nodePool.push(this.createNode());\n }\n\n nodes.length = Nbodies;\n\n for (let i = 0; i < Nbodies; i++) {\n nodes[i] = nodePool[i];\n } // Reset node values\n\n\n for (let i = 0; i !== Nbodies; i++) {\n const node = nodes[i];\n node.body = bodies[i];\n node.children.length = 0;\n node.eqs.length = 0;\n node.visited = false;\n }\n\n for (let k = 0; k !== Neq; k++) {\n const eq = equations[k];\n const i = bodies.indexOf(eq.bi);\n const j = bodies.indexOf(eq.bj);\n const ni = nodes[i];\n const nj = nodes[j];\n ni.children.push(nj);\n ni.eqs.push(eq);\n nj.children.push(ni);\n nj.eqs.push(eq);\n }\n\n let child;\n let n = 0;\n let eqs = SplitSolver_solve_eqs;\n subsolver.tolerance = this.tolerance;\n subsolver.iterations = this.iterations;\n const dummyWorld = SplitSolver_solve_dummyWorld;\n\n while (child = getUnvisitedNode(nodes)) {\n eqs.length = 0;\n dummyWorld.bodies.length = 0;\n bfs(child, visitFunc, dummyWorld.bodies, eqs);\n const Neqs = eqs.length;\n eqs = eqs.sort(sortById);\n\n for (let i = 0; i !== Neqs; i++) {\n subsolver.addEquation(eqs[i]);\n }\n\n subsolver.solve(dt, dummyWorld);\n subsolver.removeAllEquations();\n n++;\n }\n\n return n;\n }\n\n} // Returns the number of subsystems\n\nconst SplitSolver_solve_nodes = []; // All allocated node objects\n\nconst SplitSolver_solve_eqs = []; // Temp array\n\nconst SplitSolver_solve_dummyWorld = {\n bodies: []\n}; // Temp object\n\nconst STATIC = Body.STATIC;\n\nfunction getUnvisitedNode(nodes) {\n const Nnodes = nodes.length;\n\n for (let i = 0; i !== Nnodes; i++) {\n const node = nodes[i];\n\n if (!node.visited && !(node.body.type & STATIC)) {\n return node;\n }\n }\n\n return false;\n}\n\nconst queue = [];\n\nfunction bfs(root, visitFunc, bds, eqs) {\n queue.push(root);\n root.visited = true;\n visitFunc(root, bds, eqs);\n\n while (queue.length) {\n const node = queue.pop(); // Loop over unvisited child nodes\n\n let child;\n\n while (child = getUnvisitedNode(node.children)) {\n child.visited = true;\n visitFunc(child, bds, eqs);\n queue.push(child);\n }\n }\n}\n\nfunction visitFunc(node, bds, eqs) {\n bds.push(node.body);\n const Neqs = node.eqs.length;\n\n for (let i = 0; i !== Neqs; i++) {\n const eq = node.eqs[i];\n\n if (!eqs.includes(eq)) {\n eqs.push(eq);\n }\n }\n}\n\nfunction sortById(a, b) {\n return b.id - a.id;\n}\n\n/**\n * For pooling objects that can be reused.\n */\nclass Pool {\n constructor() {\n this.objects = [];\n this.type = Object;\n }\n\n /**\n * Release an object after use\n */\n release() {\n const Nargs = arguments.length;\n\n for (let i = 0; i !== Nargs; i++) {\n this.objects.push(i < 0 || arguments.length <= i ? undefined : arguments[i]);\n }\n\n return this;\n }\n /**\n * Get an object\n */\n\n\n get() {\n if (this.objects.length === 0) {\n return this.constructObject();\n } else {\n return this.objects.pop();\n }\n }\n /**\n * Construct an object. Should be implemented in each subclass.\n */\n\n\n constructObject() {\n throw new Error('constructObject() not implemented in this Pool subclass yet!');\n }\n /**\n * @return Self, for chaining\n */\n\n\n resize(size) {\n const objects = this.objects;\n\n while (objects.length > size) {\n objects.pop();\n }\n\n while (objects.length < size) {\n objects.push(this.constructObject());\n }\n\n return this;\n }\n\n}\n\n/**\n * Vec3Pool\n */\n\nclass Vec3Pool extends Pool {\n constructor() {\n super(...arguments);\n this.type = Vec3;\n }\n\n /**\n * Construct a vector\n */\n constructObject() {\n return new Vec3();\n }\n\n}\n\n// Naming rule: based of the order in SHAPE_TYPES,\n// the first part of the method is formed by the\n// shape type that comes before, in the second part\n// there is the shape type that comes after in the SHAPE_TYPES list\nconst COLLISION_TYPES = {\n sphereSphere: Shape.types.SPHERE,\n spherePlane: Shape.types.SPHERE | Shape.types.PLANE,\n boxBox: Shape.types.BOX | Shape.types.BOX,\n sphereBox: Shape.types.SPHERE | Shape.types.BOX,\n planeBox: Shape.types.PLANE | Shape.types.BOX,\n convexConvex: Shape.types.CONVEXPOLYHEDRON,\n sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,\n planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,\n boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,\n sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,\n boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,\n convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,\n sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,\n planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,\n boxParticle: Shape.types.BOX | Shape.types.PARTICLE,\n convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,\n cylinderCylinder: Shape.types.CYLINDER,\n sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,\n planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,\n boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,\n convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,\n heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,\n particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,\n sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,\n planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH\n};\n\n/**\n * Helper class for the World. Generates ContactEquations.\n * @todo Sphere-ConvexPolyhedron contacts\n * @todo Contact reduction\n * @todo should move methods to prototype\n */\nclass Narrowphase {\n /**\n * Internal storage of pooled contact points.\n */\n\n /**\n * Pooled vectors.\n */\n get [COLLISION_TYPES.sphereSphere]() {\n return this.sphereSphere;\n }\n\n get [COLLISION_TYPES.spherePlane]() {\n return this.spherePlane;\n }\n\n get [COLLISION_TYPES.boxBox]() {\n return this.boxBox;\n }\n\n get [COLLISION_TYPES.sphereBox]() {\n return this.sphereBox;\n }\n\n get [COLLISION_TYPES.planeBox]() {\n return this.planeBox;\n }\n\n get [COLLISION_TYPES.convexConvex]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.sphereConvex]() {\n return this.sphereConvex;\n }\n\n get [COLLISION_TYPES.planeConvex]() {\n return this.planeConvex;\n }\n\n get [COLLISION_TYPES.boxConvex]() {\n return this.boxConvex;\n }\n\n get [COLLISION_TYPES.sphereHeightfield]() {\n return this.sphereHeightfield;\n }\n\n get [COLLISION_TYPES.boxHeightfield]() {\n return this.boxHeightfield;\n }\n\n get [COLLISION_TYPES.convexHeightfield]() {\n return this.convexHeightfield;\n }\n\n get [COLLISION_TYPES.sphereParticle]() {\n return this.sphereParticle;\n }\n\n get [COLLISION_TYPES.planeParticle]() {\n return this.planeParticle;\n }\n\n get [COLLISION_TYPES.boxParticle]() {\n return this.boxParticle;\n }\n\n get [COLLISION_TYPES.convexParticle]() {\n return this.convexParticle;\n }\n\n get [COLLISION_TYPES.cylinderCylinder]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.sphereCylinder]() {\n return this.sphereConvex;\n }\n\n get [COLLISION_TYPES.planeCylinder]() {\n return this.planeConvex;\n }\n\n get [COLLISION_TYPES.boxCylinder]() {\n return this.boxConvex;\n }\n\n get [COLLISION_TYPES.convexCylinder]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.heightfieldCylinder]() {\n return this.heightfieldCylinder;\n }\n\n get [COLLISION_TYPES.particleCylinder]() {\n return this.particleCylinder;\n }\n\n get [COLLISION_TYPES.sphereTrimesh]() {\n return this.sphereTrimesh;\n }\n\n get [COLLISION_TYPES.planeTrimesh]() {\n return this.planeTrimesh;\n } // get [COLLISION_TYPES.convexTrimesh]() {\n // return this.convexTrimesh\n // }\n\n\n constructor(world) {\n this.contactPointPool = [];\n this.frictionEquationPool = [];\n this.result = [];\n this.frictionResult = [];\n this.v3pool = new Vec3Pool();\n this.world = world;\n this.currentContactMaterial = world.defaultContactMaterial;\n this.enableFrictionReduction = false;\n }\n /**\n * Make a contact object, by using the internal pool or creating a new one.\n */\n\n\n createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {\n let c;\n\n if (this.contactPointPool.length) {\n c = this.contactPointPool.pop();\n c.bi = bi;\n c.bj = bj;\n } else {\n c = new ContactEquation(bi, bj);\n }\n\n c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;\n const cm = this.currentContactMaterial;\n c.restitution = cm.restitution;\n c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);\n const matA = si.material || bi.material;\n const matB = sj.material || bj.material;\n\n if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {\n c.restitution = matA.restitution * matB.restitution;\n }\n\n c.si = overrideShapeA || si;\n c.sj = overrideShapeB || sj;\n return c;\n }\n\n createFrictionEquationsFromContact(contactEquation, outArray) {\n const bodyA = contactEquation.bi;\n const bodyB = contactEquation.bj;\n const shapeA = contactEquation.si;\n const shapeB = contactEquation.sj;\n const world = this.world;\n const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them\n\n let friction = cm.friction;\n const matA = shapeA.material || bodyA.material;\n const matB = shapeB.material || bodyB.material;\n\n if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {\n friction = matA.friction * matB.friction;\n }\n\n if (friction > 0) {\n // Create 2 tangent equations\n // Users may provide a force different from global gravity to use when computing contact friction.\n const mug = friction * (world.frictionGravity || world.gravity).length();\n let reducedMass = bodyA.invMass + bodyB.invMass;\n\n if (reducedMass > 0) {\n reducedMass = 1 / reducedMass;\n }\n\n const pool = this.frictionEquationPool;\n const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);\n const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);\n c1.bi = c2.bi = bodyA;\n c1.bj = c2.bj = bodyB;\n c1.minForce = c2.minForce = -mug * reducedMass;\n c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors\n\n c1.ri.copy(contactEquation.ri);\n c1.rj.copy(contactEquation.rj);\n c2.ri.copy(contactEquation.ri);\n c2.rj.copy(contactEquation.rj); // Construct tangents\n\n contactEquation.ni.tangents(c1.t, c2.t); // Set spook params\n\n c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);\n c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);\n c1.enabled = c2.enabled = contactEquation.enabled;\n outArray.push(c1, c2);\n return true;\n }\n\n return false;\n }\n /**\n * Take the average N latest contact point on the plane.\n */\n\n\n createFrictionFromAverage(numContacts) {\n // The last contactEquation\n let c = this.result[this.result.length - 1]; // Create the result: two \"average\" friction equations\n\n if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {\n return;\n }\n\n const f1 = this.frictionResult[this.frictionResult.length - 2];\n const f2 = this.frictionResult[this.frictionResult.length - 1];\n averageNormal.setZero();\n averageContactPointA.setZero();\n averageContactPointB.setZero();\n const bodyA = c.bi;\n c.bj;\n\n for (let i = 0; i !== numContacts; i++) {\n c = this.result[this.result.length - 1 - i];\n\n if (c.bi !== bodyA) {\n averageNormal.vadd(c.ni, averageNormal);\n averageContactPointA.vadd(c.ri, averageContactPointA);\n averageContactPointB.vadd(c.rj, averageContactPointB);\n } else {\n averageNormal.vsub(c.ni, averageNormal);\n averageContactPointA.vadd(c.rj, averageContactPointA);\n averageContactPointB.vadd(c.ri, averageContactPointB);\n }\n }\n\n const invNumContacts = 1 / numContacts;\n averageContactPointA.scale(invNumContacts, f1.ri);\n averageContactPointB.scale(invNumContacts, f1.rj);\n f2.ri.copy(f1.ri); // Should be the same\n\n f2.rj.copy(f1.rj);\n averageNormal.normalize();\n averageNormal.tangents(f1.t, f2.t); // return eq;\n }\n /**\n * Generate all contacts between a list of body pairs\n * @param p1 Array of body indices\n * @param p2 Array of body indices\n * @param result Array to store generated contacts\n * @param oldcontacts Optional. Array of reusable contact objects\n */\n\n\n getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {\n // Save old contact objects\n this.contactPointPool = oldcontacts;\n this.frictionEquationPool = frictionPool;\n this.result = result;\n this.frictionResult = frictionResult;\n const qi = tmpQuat1;\n const qj = tmpQuat2;\n const xi = tmpVec1;\n const xj = tmpVec2;\n\n for (let k = 0, N = p1.length; k !== N; k++) {\n // Get current collision bodies\n const bi = p1[k];\n const bj = p2[k]; // Get contact material\n\n let bodyContactMaterial = null;\n\n if (bi.material && bj.material) {\n bodyContactMaterial = world.getContactMaterial(bi.material, bj.material) || null;\n }\n\n const justTest = bi.type & Body.KINEMATIC && bj.type & Body.STATIC || bi.type & Body.STATIC && bj.type & Body.KINEMATIC || bi.type & Body.KINEMATIC && bj.type & Body.KINEMATIC;\n\n for (let i = 0; i < bi.shapes.length; i++) {\n bi.quaternion.mult(bi.shapeOrientations[i], qi);\n bi.quaternion.vmult(bi.shapeOffsets[i], xi);\n xi.vadd(bi.position, xi);\n const si = bi.shapes[i];\n\n for (let j = 0; j < bj.shapes.length; j++) {\n // Compute world transform of shapes\n bj.quaternion.mult(bj.shapeOrientations[j], qj);\n bj.quaternion.vmult(bj.shapeOffsets[j], xj);\n xj.vadd(bj.position, xj);\n const sj = bj.shapes[j];\n\n if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {\n continue;\n }\n\n if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {\n continue;\n } // Get collision material\n\n\n let shapeContactMaterial = null;\n\n if (si.material && sj.material) {\n shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;\n }\n\n this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts\n\n const resolverIndex = si.type | sj.type;\n const resolver = this[resolverIndex];\n\n if (resolver) {\n let retval = false; // TO DO: investigate why sphereParticle and convexParticle\n // resolvers expect si and sj shapes to be in reverse order\n // (i.e. larger integer value type first instead of smaller first)\n\n if (si.type < sj.type) {\n retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n } else {\n retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);\n }\n\n if (retval && justTest) {\n // Register overlap\n world.shapeOverlapKeeper.set(si.id, sj.id);\n world.bodyOverlapKeeper.set(bi.id, bj.id);\n }\n }\n }\n }\n }\n }\n\n sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n if (justTest) {\n return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;\n } // We will have only one contact in this case\n\n\n const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal\n\n xj.vsub(xi, contactEq.ni);\n contactEq.ni.normalize(); // Contact point locations\n\n contactEq.ri.copy(contactEq.ni);\n contactEq.rj.copy(contactEq.ni);\n contactEq.ri.scale(si.radius, contactEq.ri);\n contactEq.rj.scale(-sj.radius, contactEq.rj);\n contactEq.ri.vadd(xi, contactEq.ri);\n contactEq.ri.vsub(bi.position, contactEq.ri);\n contactEq.rj.vadd(xj, contactEq.rj);\n contactEq.rj.vsub(bj.position, contactEq.rj);\n this.result.push(contactEq);\n this.createFrictionEquationsFromContact(contactEq, this.frictionResult);\n }\n\n spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n // We will have one contact in this case\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal\n\n r.ni.set(0, 0, 1);\n qj.vmult(r.ni, r.ni);\n r.ni.negate(r.ni); // body i is the sphere, flip normal\n\n r.ni.normalize(); // Needed?\n // Vector from sphere center to contact point\n\n r.ni.scale(si.radius, r.ri); // Project down sphere on plane\n\n xi.vsub(xj, point_on_plane_to_sphere);\n r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);\n point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane\n\n if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {\n if (justTest) {\n return true;\n } // Make it relative to the body\n\n\n const ri = r.ri;\n const rj = r.rj;\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n sj.convexPolyhedronRepresentation.material = sj.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;\n return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n const v3pool = this.v3pool; // we refer to the box as body j\n\n const sides = sphereBox_sides;\n xi.vsub(xj, box_to_sphere);\n sj.getSideNormals(sides, qj);\n const R = si.radius;\n\n let found = false; // Store the resulting side penetration info\n\n const side_ns = sphereBox_side_ns;\n const side_ns1 = sphereBox_side_ns1;\n const side_ns2 = sphereBox_side_ns2;\n let side_h = null;\n let side_penetrations = 0;\n let side_dot1 = 0;\n let side_dot2 = 0;\n let side_distance = null;\n\n for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {\n // Get the plane side normal (ns)\n const ns = sphereBox_ns;\n ns.copy(sides[idx]);\n const h = ns.length();\n ns.normalize(); // The normal/distance dot product tells which side of the plane we are\n\n const dot = box_to_sphere.dot(ns);\n\n if (dot < h + R && dot > 0) {\n // Intersects plane. Now check the other two dimensions\n const ns1 = sphereBox_ns1;\n const ns2 = sphereBox_ns2;\n ns1.copy(sides[(idx + 1) % 3]);\n ns2.copy(sides[(idx + 2) % 3]);\n const h1 = ns1.length();\n const h2 = ns2.length();\n ns1.normalize();\n ns2.normalize();\n const dot1 = box_to_sphere.dot(ns1);\n const dot2 = box_to_sphere.dot(ns2);\n\n if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {\n const dist = Math.abs(dot - h - R);\n\n if (side_distance === null || dist < side_distance) {\n side_distance = dist;\n side_dot1 = dot1;\n side_dot2 = dot2;\n side_h = h;\n side_ns.copy(ns);\n side_ns1.copy(ns1);\n side_ns2.copy(ns2);\n side_penetrations++;\n\n if (justTest) {\n return true;\n }\n }\n }\n }\n }\n\n if (side_penetrations) {\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n side_ns.scale(-R, r.ri); // Sphere r\n\n r.ni.copy(side_ns);\n r.ni.negate(r.ni); // Normal should be out of sphere\n\n side_ns.scale(side_h, side_ns);\n side_ns1.scale(side_dot1, side_ns1);\n side_ns.vadd(side_ns1, side_ns);\n side_ns2.scale(side_dot2, side_ns2);\n side_ns.vadd(side_ns2, r.rj); // Make relative to bodies\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n } // Check corners\n\n\n let rj = v3pool.get();\n const sphere_to_corner = sphereBox_sphere_to_corner;\n\n for (let j = 0; j !== 2 && !found; j++) {\n for (let k = 0; k !== 2 && !found; k++) {\n for (let l = 0; l !== 2 && !found; l++) {\n rj.set(0, 0, 0);\n\n if (j) {\n rj.vadd(sides[0], rj);\n } else {\n rj.vsub(sides[0], rj);\n }\n\n if (k) {\n rj.vadd(sides[1], rj);\n } else {\n rj.vsub(sides[1], rj);\n }\n\n if (l) {\n rj.vadd(sides[2], rj);\n } else {\n rj.vsub(sides[2], rj);\n } // World position of corner\n\n\n xj.vadd(rj, sphere_to_corner);\n sphere_to_corner.vsub(xi, sphere_to_corner);\n\n if (sphere_to_corner.lengthSquared() < R * R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ri.copy(sphere_to_corner);\n r.ri.normalize();\n r.ni.copy(r.ri);\n r.ri.scale(R, r.ri);\n r.rj.copy(rj); // Make relative to bodies\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n }\n\n v3pool.release(rj);\n rj = null; // Check edges\n\n const edgeTangent = v3pool.get();\n const edgeCenter = v3pool.get();\n const r = v3pool.get(); // r = edge center to sphere center\n\n const orthogonal = v3pool.get();\n const dist = v3pool.get();\n const Nsides = sides.length;\n\n for (let j = 0; j !== Nsides && !found; j++) {\n for (let k = 0; k !== Nsides && !found; k++) {\n if (j % 3 !== k % 3) {\n // Get edge tangent\n sides[k].cross(sides[j], edgeTangent);\n edgeTangent.normalize();\n sides[j].vadd(sides[k], edgeCenter);\n r.copy(xi);\n r.vsub(edgeCenter, r);\n r.vsub(xj, r);\n const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction\n\n edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction\n // Find the third side orthogonal to this one\n\n let l = 0;\n\n while (l === j % 3 || l === k % 3) {\n l++;\n } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent\n\n\n dist.copy(xi);\n dist.vsub(orthogonal, dist);\n dist.vsub(edgeCenter, dist);\n dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it\n\n const tdist = Math.abs(orthonorm);\n const ndist = dist.length();\n\n if (tdist < sides[l].length() && ndist < R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n edgeCenter.vadd(orthogonal, res.rj); // box rj\n\n res.rj.copy(res.rj);\n dist.negate(res.ni);\n res.ni.normalize();\n res.ri.copy(res.rj);\n res.ri.vadd(xj, res.ri);\n res.ri.vsub(xi, res.ri);\n res.ri.normalize();\n res.ri.scale(R, res.ri); // Make relative to bodies\n\n res.ri.vadd(xi, res.ri);\n res.ri.vsub(bi.position, res.ri);\n res.rj.vadd(xj, res.rj);\n res.rj.vsub(bj.position, res.rj);\n this.result.push(res);\n this.createFrictionEquationsFromContact(res, this.frictionResult);\n }\n }\n }\n }\n\n v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);\n }\n\n planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n sj.convexPolyhedronRepresentation.material = sj.material;\n sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;\n sj.convexPolyhedronRepresentation.id = sj.id;\n return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {\n const sepAxis = convexConvex_sepAxis;\n\n if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {\n return;\n }\n\n if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {\n const res = [];\n const q = convexConvex_q;\n si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res);\n let numContacts = 0;\n\n for (let j = 0; j !== res.length; j++) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n const ri = r.ri;\n const rj = r.rj;\n sepAxis.negate(r.ni);\n res[j].normal.negate(q);\n q.scale(res[j].depth, q);\n res[j].point.vadd(q, ri);\n rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative\n\n ri.vsub(xi, ri);\n rj.vsub(xj, rj); // Make relative to bodies\n\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n numContacts++;\n\n if (!this.enableFrictionReduction) {\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n if (this.enableFrictionReduction && numContacts) {\n this.createFrictionFromAverage(numContacts);\n }\n }\n }\n\n sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n const v3pool = this.v3pool;\n xi.vsub(xj, convex_to_sphere);\n const normals = sj.faceNormals;\n const faces = sj.faces;\n const verts = sj.vertices;\n const R = si.radius;\n // return;\n // }\n\n let found = false; // Check corners\n\n for (let i = 0; i !== verts.length; i++) {\n const v = verts[i]; // World position of corner\n\n const worldCorner = sphereConvex_worldCorner;\n qj.vmult(v, worldCorner);\n xj.vadd(worldCorner, worldCorner);\n const sphere_to_corner = sphereConvex_sphereToCorner;\n worldCorner.vsub(xi, sphere_to_corner);\n\n if (sphere_to_corner.lengthSquared() < R * R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ri.copy(sphere_to_corner);\n r.ri.normalize();\n r.ni.copy(r.ri);\n r.ri.scale(R, r.ri);\n worldCorner.vsub(xj, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n return;\n }\n } // Check side (plane) intersections\n\n\n for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {\n const normal = normals[i];\n const face = faces[i]; // Get world-transformed normal of the face\n\n const worldNormal = sphereConvex_worldNormal;\n qj.vmult(normal, worldNormal); // Get a world vertex from the face\n\n const worldPoint = sphereConvex_worldPoint;\n qj.vmult(verts[face[0]], worldPoint);\n worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal\n\n const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;\n worldNormal.scale(-R, worldSpherePointClosestToPlane);\n xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere\n\n const penetrationVec = sphereConvex_penetrationVec;\n worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.\n\n const penetration = penetrationVec.dot(worldNormal);\n const worldPointToSphere = sphereConvex_sphereToWorldPoint;\n xi.vsub(worldPoint, worldPointToSphere);\n\n if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {\n // Intersects plane. Now check if the sphere is inside the face polygon\n const faceVerts = []; // Face vertices, in world coords\n\n for (let j = 0, Nverts = face.length; j !== Nverts; j++) {\n const worldVertex = v3pool.get();\n qj.vmult(verts[face[j]], worldVertex);\n xj.vadd(worldVertex, worldVertex);\n faceVerts.push(worldVertex);\n }\n\n if (pointInPolygon(faceVerts, worldNormal, xi)) {\n // Is the sphere center in the face polygon?\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact\n\n worldNormal.negate(r.ni); // Normal pointing out of sphere\n\n const penetrationVec2 = v3pool.get();\n worldNormal.scale(-penetration, penetrationVec2);\n const penetrationSpherePoint = v3pool.get();\n worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);\n\n xi.vsub(xj, r.rj);\n r.rj.vadd(penetrationSpherePoint, r.rj);\n r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n v3pool.release(penetrationVec2);\n v3pool.release(penetrationSpherePoint);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n\n return; // We only expect *one* face contact\n } else {\n // Edge?\n for (let j = 0; j !== face.length; j++) {\n // Get two world transformed vertices\n const v1 = v3pool.get();\n const v2 = v3pool.get();\n qj.vmult(verts[face[(j + 1) % face.length]], v1);\n qj.vmult(verts[face[(j + 2) % face.length]], v2);\n xj.vadd(v1, v1);\n xj.vadd(v2, v2); // Construct edge vector\n\n const edge = sphereConvex_edge;\n v2.vsub(v1, edge); // Construct the same vector, but normalized\n\n const edgeUnit = sphereConvex_edgeUnit;\n edge.unit(edgeUnit); // p is xi projected onto the edge\n\n const p = v3pool.get();\n const v1_to_xi = v3pool.get();\n xi.vsub(v1, v1_to_xi);\n const dot = v1_to_xi.dot(edgeUnit);\n edgeUnit.scale(dot, p);\n p.vadd(v1, p); // Compute a vector from p to the center of the sphere\n\n const xi_to_p = v3pool.get();\n p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius\n // AND if p is in between v1 and v2\n\n if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {\n // Collision if the edge-sphere distance is less than the radius\n // Edge contact!\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n p.vsub(xj, r.rj);\n p.vsub(xi, r.ni);\n r.ni.normalize();\n r.ni.scale(R, r.ri); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n\n v3pool.release(v1);\n v3pool.release(v2);\n v3pool.release(p);\n v3pool.release(xi_to_p);\n v3pool.release(v1_to_xi);\n return;\n }\n\n v3pool.release(v1);\n v3pool.release(v2);\n v3pool.release(p);\n v3pool.release(xi_to_p);\n v3pool.release(v1_to_xi);\n }\n } // Release world vertices\n\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n }\n }\n }\n\n planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {\n // Simply return the points behind the plane.\n const worldVertex = planeConvex_v;\n const worldNormal = planeConvex_normal;\n worldNormal.set(0, 0, 1);\n planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation\n\n let numContacts = 0;\n const relpos = planeConvex_relpos;\n\n for (let i = 0; i !== convexShape.vertices.length; i++) {\n // Get world convex vertex\n worldVertex.copy(convexShape.vertices[i]);\n convexQuat.vmult(worldVertex, worldVertex);\n convexPosition.vadd(worldVertex, worldVertex);\n worldVertex.vsub(planePosition, relpos);\n const dot = worldNormal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane\n\n const projected = planeConvex_projected;\n worldNormal.scale(worldNormal.dot(relpos), projected);\n worldVertex.vsub(projected, projected);\n projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane\n\n r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane\n // rj is now just the vector from the convex center to the vertex\n\n worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body\n\n r.ri.vadd(planePosition, r.ri);\n r.ri.vsub(planeBody.position, r.ri);\n r.rj.vadd(convexPosition, r.rj);\n r.rj.vsub(convexBody.position, r.rj);\n this.result.push(r);\n numContacts++;\n\n if (!this.enableFrictionReduction) {\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n\n if (this.enableFrictionReduction && numContacts) {\n this.createFrictionFromAverage(numContacts);\n }\n }\n\n boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {\n const data = hfShape.data;\n const radius = sphereShape.radius;\n const w = hfShape.elementSize;\n const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!\n\n const localSpherePos = sphereHeightfield_tmp1;\n Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against\n\n let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;\n let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;\n let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;\n let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain\n\n if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {\n return;\n } // Clamp index to edges\n\n\n if (iMinX < 0) {\n iMinX = 0;\n }\n\n if (iMaxX < 0) {\n iMaxX = 0;\n }\n\n if (iMinY < 0) {\n iMinY = 0;\n }\n\n if (iMaxY < 0) {\n iMaxY = 0;\n }\n\n if (iMinX >= data.length) {\n iMinX = data.length - 1;\n }\n\n if (iMaxX >= data.length) {\n iMaxX = data.length - 1;\n }\n\n if (iMaxY >= data[0].length) {\n iMaxY = data[0].length - 1;\n }\n\n if (iMinY >= data[0].length) {\n iMinY = data[0].length - 1;\n }\n\n const minMax = [];\n hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);\n const min = minMax[0];\n const max = minMax[1]; // Bail out if we can't touch the bounding height box\n\n if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {\n return;\n }\n\n const result = this.result;\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n const numContactsBefore = result.length;\n let intersecting = false; // Lower triangle\n\n hfShape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {\n intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);\n }\n\n if (justTest && intersecting) {\n return true;\n } // Upper triangle\n\n\n hfShape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {\n intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);\n }\n\n if (justTest && intersecting) {\n return true;\n }\n\n const numContacts = result.length - numContactsBefore;\n\n if (numContacts > 2) {\n return;\n }\n /*\n // Skip all but 1\n for (let k = 0; k < numContacts - 1; k++) {\n result.pop();\n }\n */\n\n }\n }\n }\n\n boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexHeightfield(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest) {\n const data = hfShape.data;\n const w = hfShape.elementSize;\n const radius = convexShape.boundingSphereRadius;\n const worldPillarOffset = convexHeightfield_tmp2;\n const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!\n\n const localConvexPos = convexHeightfield_tmp1;\n Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against\n\n let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;\n let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;\n let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;\n let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain\n\n if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {\n return;\n } // Clamp index to edges\n\n\n if (iMinX < 0) {\n iMinX = 0;\n }\n\n if (iMaxX < 0) {\n iMaxX = 0;\n }\n\n if (iMinY < 0) {\n iMinY = 0;\n }\n\n if (iMaxY < 0) {\n iMaxY = 0;\n }\n\n if (iMinX >= data.length) {\n iMinX = data.length - 1;\n }\n\n if (iMaxX >= data.length) {\n iMaxX = data.length - 1;\n }\n\n if (iMaxY >= data[0].length) {\n iMaxY = data[0].length - 1;\n }\n\n if (iMinY >= data[0].length) {\n iMinY = data[0].length - 1;\n }\n\n const minMax = [];\n hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);\n const min = minMax[0];\n const max = minMax[1]; // Bail out if we're cant touch the bounding height box\n\n if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {\n return;\n }\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n let intersecting = false; // Lower triangle\n\n hfShape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {\n intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);\n }\n\n if (justTest && intersecting) {\n return true;\n } // Upper triangle\n\n\n hfShape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {\n intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);\n }\n\n if (justTest && intersecting) {\n return true;\n }\n }\n }\n }\n\n sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n // The normal is the unit vector from sphere center to particle center\n const normal = particleSphere_normal;\n normal.set(0, 0, 1);\n xi.vsub(xj, normal);\n const lengthSquared = normal.lengthSquared();\n\n if (lengthSquared <= sj.radius * sj.radius) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n normal.normalize();\n r.rj.copy(normal);\n r.rj.scale(sj.radius, r.rj);\n r.ni.copy(normal); // Contact normal\n\n r.ni.negate(r.ni);\n r.ri.set(0, 0, 0); // Center of particle\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n const normal = particlePlane_normal;\n normal.set(0, 0, 1);\n bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation\n\n const relpos = particlePlane_relpos;\n xi.vsub(bj.position, relpos);\n const dot = normal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ni.copy(normal); // Contact normal is the plane normal\n\n r.ni.negate(r.ni);\n r.ri.set(0, 0, 0); // Center of particle\n // Get particle position projected on plane\n\n const projected = particlePlane_projected;\n normal.scale(normal.dot(xi), projected);\n xi.vsub(projected, projected); //projected.vadd(bj.position,projected);\n // rj is now the projected world position minus plane position\n\n r.rj.copy(projected);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n let penetratedFaceIndex = -1;\n const penetratedFaceNormal = convexParticle_penetratedFaceNormal;\n const worldPenetrationVec = convexParticle_worldPenetrationVec;\n let minPenetration = null;\n\n const local = convexParticle_local;\n local.copy(xi);\n local.vsub(xj, local); // Convert position to relative the convex origin\n\n qj.conjugate(cqj);\n cqj.vmult(local, local);\n\n if (sj.pointIsInside(local)) {\n if (sj.worldVerticesNeedsUpdate) {\n sj.computeWorldVertices(xj, qj);\n }\n\n if (sj.worldFaceNormalsNeedsUpdate) {\n sj.computeWorldFaceNormals(qj);\n } // For each world polygon in the polyhedra\n\n\n for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {\n // Construct world face vertices\n const verts = [sj.worldVertices[sj.faces[i][0]]];\n const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.\n\n xi.vsub(verts[0], convexParticle_vertexToParticle);\n const penetration = -normal.dot(convexParticle_vertexToParticle);\n\n if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {\n if (justTest) {\n return true;\n }\n\n minPenetration = penetration;\n penetratedFaceIndex = i;\n penetratedFaceNormal.copy(normal);\n }\n }\n\n if (penetratedFaceIndex !== -1) {\n // Setup contact\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face\n\n worldPenetrationVec.vadd(xi, worldPenetrationVec);\n worldPenetrationVec.vsub(xj, worldPenetrationVec);\n r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);\n //projectedToFace.copy(r.rj);\n //qj.vmult(r.rj,r.rj);\n\n penetratedFaceNormal.negate(r.ni); // Contact normal\n\n r.ri.set(0, 0, 0); // Center of particle\n\n const ri = r.ri;\n const rj = r.rj; // Make relative to bodies\n\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n } else {\n console.warn('Point found inside convex, but did not find penetrating face!');\n }\n }\n }\n\n heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {\n return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);\n }\n\n particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);\n }\n\n sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {\n const edgeVertexA = sphereTrimesh_edgeVertexA;\n const edgeVertexB = sphereTrimesh_edgeVertexB;\n const edgeVector = sphereTrimesh_edgeVector;\n const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;\n const localSpherePos = sphereTrimesh_localSpherePos;\n const tmp = sphereTrimesh_tmp;\n const localSphereAABB = sphereTrimesh_localSphereAABB;\n const v2 = sphereTrimesh_v2;\n const relpos = sphereTrimesh_relpos;\n const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh\n\n Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh\n\n const sphereRadius = sphereShape.radius;\n localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);\n localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);\n trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All\n // Vertices\n\n const v = sphereTrimesh_v;\n const radiusSquared = sphereShape.radius * sphereShape.radius;\n\n for (let i = 0; i < triangles.length; i++) {\n for (let j = 0; j < 3; j++) {\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere\n\n v.vsub(localSpherePos, relpos);\n\n if (relpos.lengthSquared() <= radiusSquared) {\n // Safe up\n v2.copy(v);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);\n v.vsub(spherePos, relpos);\n\n if (justTest) {\n return true;\n }\n\n let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n r.ni.copy(relpos);\n r.ni.normalize(); // ri is the vector from sphere center to the sphere surface\n\n r.ri.copy(r.ni);\n r.ri.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n r.rj.copy(v);\n r.rj.vsub(trimeshBody.position, r.rj); // Store result\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n } // Check all edges\n\n\n for (let i = 0; i < triangles.length; i++) {\n for (let j = 0; j < 3; j++) {\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);\n edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge\n\n localSpherePos.vsub(edgeVertexB, tmp);\n const positionAlongEdgeB = tmp.dot(edgeVector);\n localSpherePos.vsub(edgeVertexA, tmp);\n let positionAlongEdgeA = tmp.dot(edgeVector);\n\n if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {\n // Now check the orthogonal distance from edge to sphere center\n localSpherePos.vsub(edgeVertexA, tmp);\n edgeVectorUnit.copy(edgeVector);\n edgeVectorUnit.normalize();\n positionAlongEdgeA = tmp.dot(edgeVectorUnit);\n edgeVectorUnit.scale(positionAlongEdgeA, tmp);\n tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame\n\n const dist = tmp.distanceTo(localSpherePos);\n\n if (dist < sphereShape.radius) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n tmp.vsub(localSpherePos, r.ni);\n r.ni.normalize();\n r.ni.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);\n tmp.vsub(trimeshBody.position, r.rj);\n Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);\n Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n } // Triangle faces\n\n\n const va = sphereTrimesh_va;\n const vb = sphereTrimesh_vb;\n const vc = sphereTrimesh_vc;\n const normal = sphereTrimesh_normal;\n\n for (let i = 0, N = triangles.length; i !== N; i++) {\n trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);\n trimeshShape.getNormal(triangles[i], normal);\n localSpherePos.vsub(va, tmp);\n let dist = tmp.dot(normal);\n normal.scale(dist, tmp);\n localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane\n\n dist = tmp.distanceTo(localSpherePos);\n\n if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {\n if (justTest) {\n return true;\n }\n\n let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n tmp.vsub(localSpherePos, r.ni);\n r.ni.normalize();\n r.ni.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);\n tmp.vsub(trimeshBody.position, r.rj);\n Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);\n Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n triangles.length = 0;\n }\n\n planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {\n // Make contacts!\n const v = new Vec3();\n const normal = planeTrimesh_normal;\n normal.set(0, 0, 1);\n planeQuat.vmult(normal, normal); // Turn normal according to plane\n\n for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {\n // Get world vertex from trimesh\n trimeshShape.getVertex(i, v); // Safe up\n\n const v2 = new Vec3();\n v2.copy(v);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side\n\n const relpos = planeTrimesh_relpos;\n v.vsub(planePos, relpos);\n const dot = normal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);\n r.ni.copy(normal); // Contact normal is the plane normal\n // Get vertex position projected on plane\n\n const projected = planeTrimesh_projected;\n normal.scale(relpos.dot(normal), projected);\n v.vsub(projected, projected); // ri is the projected world position minus plane position\n\n r.ri.copy(projected);\n r.ri.vsub(planeBody.position, r.ri);\n r.rj.copy(v);\n r.rj.vsub(trimeshBody.position, r.rj); // Store result\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n } // convexTrimesh(\n // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,\n // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,\n // faceListA?: number[] | null, faceListB?: number[] | null,\n // ) {\n // const sepAxis = convexConvex_sepAxis;\n // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){\n // return;\n // }\n // // Construct a temp hull for each triangle\n // const hullB = new ConvexPolyhedron();\n // hullB.faces = [[0,1,2]];\n // const va = new Vec3();\n // const vb = new Vec3();\n // const vc = new Vec3();\n // hullB.vertices = [\n // va,\n // vb,\n // vc\n // ];\n // for (let i = 0; i < sj.indices.length / 3; i++) {\n // const triangleNormal = new Vec3();\n // sj.getNormal(i, triangleNormal);\n // hullB.faceNormals = [triangleNormal];\n // sj.getTriangleVertices(i, va, vb, vc);\n // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);\n // if(!d){\n // triangleNormal.scale(-1, triangleNormal);\n // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);\n // if(!d){\n // continue;\n // }\n // }\n // const res: ConvexPolyhedronContactPoint[] = [];\n // const q = convexConvex_q;\n // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);\n // for(let j = 0; j !== res.length; j++){\n // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),\n // ri = r.ri,\n // rj = r.rj;\n // r.ni.copy(triangleNormal);\n // r.ni.negate(r.ni);\n // res[j].normal.negate(q);\n // q.mult(res[j].depth, q);\n // res[j].point.vadd(q, ri);\n // rj.copy(res[j].point);\n // // Contact points are in world coordinates. Transform back to relative\n // ri.vsub(xi,ri);\n // rj.vsub(xj,rj);\n // // Make relative to bodies\n // ri.vadd(xi, ri);\n // ri.vsub(bi.position, ri);\n // rj.vadd(xj, rj);\n // rj.vsub(bj.position, rj);\n // result.push(r);\n // }\n // }\n // }\n\n\n}\nconst averageNormal = new Vec3();\nconst averageContactPointA = new Vec3();\nconst averageContactPointB = new Vec3();\nconst tmpVec1 = new Vec3();\nconst tmpVec2 = new Vec3();\nconst tmpQuat1 = new Quaternion();\nconst tmpQuat2 = new Quaternion();\n\nconst planeTrimesh_normal = new Vec3();\nconst planeTrimesh_relpos = new Vec3();\nconst planeTrimesh_projected = new Vec3();\nconst sphereTrimesh_normal = new Vec3();\nconst sphereTrimesh_relpos = new Vec3();\nnew Vec3();\nconst sphereTrimesh_v = new Vec3();\nconst sphereTrimesh_v2 = new Vec3();\nconst sphereTrimesh_edgeVertexA = new Vec3();\nconst sphereTrimesh_edgeVertexB = new Vec3();\nconst sphereTrimesh_edgeVector = new Vec3();\nconst sphereTrimesh_edgeVectorUnit = new Vec3();\nconst sphereTrimesh_localSpherePos = new Vec3();\nconst sphereTrimesh_tmp = new Vec3();\nconst sphereTrimesh_va = new Vec3();\nconst sphereTrimesh_vb = new Vec3();\nconst sphereTrimesh_vc = new Vec3();\nconst sphereTrimesh_localSphereAABB = new AABB();\nconst sphereTrimesh_triangles = [];\nconst point_on_plane_to_sphere = new Vec3();\nconst plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html\n\nconst pointInPolygon_edge = new Vec3();\nconst pointInPolygon_edge_x_normal = new Vec3();\nconst pointInPolygon_vtp = new Vec3();\n\nfunction pointInPolygon(verts, normal, p) {\n let positiveResult = null;\n const N = verts.length;\n\n for (let i = 0; i !== N; i++) {\n const v = verts[i]; // Get edge to the next vertex\n\n const edge = pointInPolygon_edge;\n verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge\n\n const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();\n\n edge.cross(normal, edge_x_normal); // Get vector between point and current vertex\n\n const vertex_to_p = pointInPolygon_vtp;\n p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is\n\n const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.\n\n if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {\n if (positiveResult === null) {\n positiveResult = r > 0;\n }\n\n continue;\n } else {\n return false; // Encountered some other sign. Exit.\n }\n } // If we got here, all dot products were of the same sign.\n\n\n return true;\n}\n\nconst box_to_sphere = new Vec3();\nconst sphereBox_ns = new Vec3();\nconst sphereBox_ns1 = new Vec3();\nconst sphereBox_ns2 = new Vec3();\nconst sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\nconst sphereBox_sphere_to_corner = new Vec3();\nconst sphereBox_side_ns = new Vec3();\nconst sphereBox_side_ns1 = new Vec3();\nconst sphereBox_side_ns2 = new Vec3();\nconst convex_to_sphere = new Vec3();\nconst sphereConvex_edge = new Vec3();\nconst sphereConvex_edgeUnit = new Vec3();\nconst sphereConvex_sphereToCorner = new Vec3();\nconst sphereConvex_worldCorner = new Vec3();\nconst sphereConvex_worldNormal = new Vec3();\nconst sphereConvex_worldPoint = new Vec3();\nconst sphereConvex_worldSpherePointClosestToPlane = new Vec3();\nconst sphereConvex_penetrationVec = new Vec3();\nconst sphereConvex_sphereToWorldPoint = new Vec3();\nnew Vec3();\nnew Vec3();\nconst planeConvex_v = new Vec3();\nconst planeConvex_normal = new Vec3();\nconst planeConvex_relpos = new Vec3();\nconst planeConvex_projected = new Vec3();\nconst convexConvex_sepAxis = new Vec3();\nconst convexConvex_q = new Vec3();\nconst particlePlane_normal = new Vec3();\nconst particlePlane_relpos = new Vec3();\nconst particlePlane_projected = new Vec3();\nconst particleSphere_normal = new Vec3(); // WIP\n\nconst cqj = new Quaternion();\nconst convexParticle_local = new Vec3();\nnew Vec3();\nconst convexParticle_penetratedFaceNormal = new Vec3();\nconst convexParticle_vertexToParticle = new Vec3();\nconst convexParticle_worldPenetrationVec = new Vec3();\nconst convexHeightfield_tmp1 = new Vec3();\nconst convexHeightfield_tmp2 = new Vec3();\nconst convexHeightfield_faceList = [0];\nconst sphereHeightfield_tmp1 = new Vec3();\nconst sphereHeightfield_tmp2 = new Vec3();\n\nclass OverlapKeeper {\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n this.current = [];\n this.previous = [];\n }\n /**\n * getKey\n */\n\n\n getKey(i, j) {\n if (j < i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return i << 16 | j;\n }\n /**\n * set\n */\n\n\n set(i, j) {\n // Insertion sort. This way the diff will have linear complexity.\n const key = this.getKey(i, j);\n const current = this.current;\n let index = 0;\n\n while (key > current[index]) {\n index++;\n }\n\n if (key === current[index]) {\n return; // Pair was already added\n }\n\n for (let j = current.length - 1; j >= index; j--) {\n current[j + 1] = current[j];\n }\n\n current[index] = key;\n }\n /**\n * tick\n */\n\n\n tick() {\n const tmp = this.current;\n this.current = this.previous;\n this.previous = tmp;\n this.current.length = 0;\n }\n /**\n * getDiff\n */\n\n\n getDiff(additions, removals) {\n const a = this.current;\n const b = this.previous;\n const al = a.length;\n const bl = b.length;\n let j = 0;\n\n for (let i = 0; i < al; i++) {\n let found = false;\n const keyA = a[i];\n\n while (keyA > b[j]) {\n j++;\n }\n\n found = keyA === b[j];\n\n if (!found) {\n unpackAndPush(additions, keyA);\n }\n }\n\n j = 0;\n\n for (let i = 0; i < bl; i++) {\n let found = false;\n const keyB = b[i];\n\n while (keyB > a[j]) {\n j++;\n }\n\n found = a[j] === keyB;\n\n if (!found) {\n unpackAndPush(removals, keyB);\n }\n }\n }\n\n}\n\nfunction unpackAndPush(array, key) {\n array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);\n}\n\nconst getKey = (i, j) => i < j ? `${i}-${j}` : `${j}-${i}`;\n/**\n * TupleDictionary\n */\n\n\nclass TupleDictionary {\n constructor() {\n this.data = {\n keys: []\n };\n }\n\n /** get */\n get(i, j) {\n const key = getKey(i, j);\n return this.data[key];\n }\n /** set */\n\n\n set(i, j, value) {\n const key = getKey(i, j); // Check if key already exists\n\n if (!this.get(i, j)) {\n this.data.keys.push(key);\n }\n\n this.data[key] = value;\n }\n /** delete */\n\n\n delete(i, j) {\n const key = getKey(i, j);\n const index = this.data.keys.indexOf(key);\n\n if (index !== -1) {\n this.data.keys.splice(index, 1);\n }\n\n delete this.data[key];\n }\n /** reset */\n\n\n reset() {\n const data = this.data;\n const keys = data.keys;\n\n while (keys.length > 0) {\n const key = keys.pop();\n delete data[key];\n }\n }\n\n}\n\n/**\n * The physics world\n */\nclass World extends EventTarget {\n /**\n * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is \"fresh\" inside event callbacks.\n */\n\n /**\n * Makes bodies go to sleep when they've been inactive.\n * @default false\n */\n\n /**\n * All the current contacts (instances of ContactEquation) in the world.\n */\n\n /**\n * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).\n * @default 0\n */\n\n /**\n * Set to true to use fast quaternion normalization. It is often enough accurate to use.\n * If bodies tend to explode, set to false.\n * @default false\n */\n\n /**\n * The wall-clock time since simulation start.\n */\n\n /**\n * Number of timesteps taken since start.\n */\n\n /**\n * Default and last timestep sizes.\n */\n\n /**\n * The gravity of the world.\n */\n\n /**\n * Gravity to use when approximating the friction max force (mu*mass*gravity).\n * If undefined, global gravity will be used.\n * Use to enable friction in a World with a null gravity vector (no gravity).\n */\n\n /**\n * The broadphase algorithm to use.\n * @default NaiveBroadphase\n */\n\n /**\n * All bodies in this world\n */\n\n /**\n * True if any bodies are not sleeping, false if every body is sleeping.\n */\n\n /**\n * The solver algorithm to use.\n * @default GSSolver\n */\n\n /**\n * collisionMatrix\n */\n\n /**\n * CollisionMatrix from the previous step.\n */\n\n /**\n * All added contactmaterials.\n */\n\n /**\n * Used to look up a ContactMaterial given two instances of Material.\n */\n\n /**\n * The default material of the bodies.\n */\n\n /**\n * This contact material is used if no suitable contactmaterial is found for a contact.\n */\n\n /**\n * Time accumulator for interpolation.\n * @see https://gafferongames.com/game-physics/fix-your-timestep/\n */\n\n /**\n * Dispatched after a body has been added to the world.\n */\n\n /**\n * Dispatched after a body has been removed from the world.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n super();\n this.dt = -1;\n this.allowSleep = !!options.allowSleep;\n this.contacts = [];\n this.frictionEquations = [];\n this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;\n this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;\n this.time = 0.0;\n this.stepnumber = 0;\n this.default_dt = 1 / 60;\n this.nextId = 0;\n this.gravity = new Vec3();\n\n if (options.gravity) {\n this.gravity.copy(options.gravity);\n }\n\n if (options.frictionGravity) {\n this.frictionGravity = new Vec3();\n this.frictionGravity.copy(options.frictionGravity);\n }\n\n this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();\n this.bodies = [];\n this.hasActiveBodies = false;\n this.solver = options.solver !== undefined ? options.solver : new GSSolver();\n this.constraints = [];\n this.narrowphase = new Narrowphase(this);\n this.collisionMatrix = new ArrayCollisionMatrix();\n this.collisionMatrixPrevious = new ArrayCollisionMatrix();\n this.bodyOverlapKeeper = new OverlapKeeper();\n this.shapeOverlapKeeper = new OverlapKeeper();\n this.contactmaterials = [];\n this.contactMaterialTable = new TupleDictionary();\n this.defaultMaterial = new Material('default');\n this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {\n friction: 0.3,\n restitution: 0.0\n });\n this.doProfiling = false;\n this.profile = {\n solve: 0,\n makeContactConstraints: 0,\n broadphase: 0,\n integrate: 0,\n narrowphase: 0\n };\n this.accumulator = 0;\n this.subsystems = [];\n this.addBodyEvent = {\n type: 'addBody',\n body: null\n };\n this.removeBodyEvent = {\n type: 'removeBody',\n body: null\n };\n this.idToBodyMap = {};\n this.broadphase.setWorld(this);\n }\n /**\n * Get the contact material between materials m1 and m2\n * @return The contact material if it was found.\n */\n\n\n getContactMaterial(m1, m2) {\n return this.contactMaterialTable.get(m1.id, m2.id);\n }\n /**\n * Store old collision state info\n */\n\n\n collisionMatrixTick() {\n const temp = this.collisionMatrixPrevious;\n this.collisionMatrixPrevious = this.collisionMatrix;\n this.collisionMatrix = temp;\n this.collisionMatrix.reset();\n this.bodyOverlapKeeper.tick();\n this.shapeOverlapKeeper.tick();\n }\n /**\n * Add a constraint to the simulation.\n */\n\n\n addConstraint(c) {\n this.constraints.push(c);\n }\n /**\n * Removes a constraint\n */\n\n\n removeConstraint(c) {\n const idx = this.constraints.indexOf(c);\n\n if (idx !== -1) {\n this.constraints.splice(idx, 1);\n }\n }\n /**\n * Raycast test\n * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.\n */\n\n\n rayTest(from, to, result) {\n if (result instanceof RaycastResult) {\n // Do raycastClosest\n this.raycastClosest(from, to, {\n skipBackfaces: true\n }, result);\n } else {\n // Do raycastAll\n this.raycastAll(from, to, {\n skipBackfaces: true\n }, result);\n }\n }\n /**\n * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.\n * @return True if any body was hit.\n */\n\n\n raycastAll(from, to, options, callback) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.ALL;\n options.from = from;\n options.to = to;\n options.callback = callback;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.\n * @return True if any body was hit.\n */\n\n\n raycastAny(from, to, options, result) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.ANY;\n options.from = from;\n options.to = to;\n options.result = result;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Ray cast, and return information of the closest hit.\n * @return True if any body was hit.\n */\n\n\n raycastClosest(from, to, options, result) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.CLOSEST;\n options.from = from;\n options.to = to;\n options.result = result;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Add a rigid body to the simulation.\n * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.\n * @todo Adding an array of bodies should be possible. This would save some loops too\n */\n\n\n addBody(body) {\n if (this.bodies.includes(body)) {\n return;\n }\n\n body.index = this.bodies.length;\n this.bodies.push(body);\n body.world = this;\n body.initPosition.copy(body.position);\n body.initVelocity.copy(body.velocity);\n body.timeLastSleepy = this.time;\n\n if (body instanceof Body) {\n body.initAngularVelocity.copy(body.angularVelocity);\n body.initQuaternion.copy(body.quaternion);\n }\n\n this.collisionMatrix.setNumObjects(this.bodies.length);\n this.addBodyEvent.body = body;\n this.idToBodyMap[body.id] = body;\n this.dispatchEvent(this.addBodyEvent);\n }\n /**\n * Remove a rigid body from the simulation.\n */\n\n\n removeBody(body) {\n body.world = null;\n const n = this.bodies.length - 1;\n const bodies = this.bodies;\n const idx = bodies.indexOf(body);\n\n if (idx !== -1) {\n bodies.splice(idx, 1); // Todo: should use a garbage free method\n // Recompute index\n\n for (let i = 0; i !== bodies.length; i++) {\n bodies[i].index = i;\n }\n\n this.collisionMatrix.setNumObjects(n);\n this.removeBodyEvent.body = body;\n delete this.idToBodyMap[body.id];\n this.dispatchEvent(this.removeBodyEvent);\n }\n }\n\n getBodyById(id) {\n return this.idToBodyMap[id];\n }\n /**\n * @todo Make a faster map\n */\n\n\n getShapeById(id) {\n const bodies = this.bodies;\n\n for (let i = 0; i < bodies.length; i++) {\n const shapes = bodies[i].shapes;\n\n for (let j = 0; j < shapes.length; j++) {\n const shape = shapes[j];\n\n if (shape.id === id) {\n return shape;\n }\n }\n }\n\n return null;\n }\n /**\n * Adds a contact material to the World\n */\n\n\n addContactMaterial(cmat) {\n // Add contact material\n this.contactmaterials.push(cmat); // Add current contact material to the material table\n\n this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);\n }\n /**\n * Removes a contact material from the World.\n */\n\n\n removeContactMaterial(cmat) {\n const idx = this.contactmaterials.indexOf(cmat);\n\n if (idx === -1) {\n return;\n }\n\n this.contactmaterials.splice(idx, 1);\n this.contactMaterialTable.delete(cmat.materials[0].id, cmat.materials[1].id);\n }\n /**\n * Step the simulation forward keeping track of last called time\n * to be able to step the world at a fixed rate, independently of framerate.\n *\n * @param dt The fixed time step size to use (default: 1 / 60).\n * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).\n * @see https://gafferongames.com/post/fix_your_timestep/\n * @example\n * // Run the simulation independently of framerate every 1 / 60 ms\n * world.fixedStep()\n */\n\n\n fixedStep(dt, maxSubSteps) {\n if (dt === void 0) {\n dt = 1 / 60;\n }\n\n if (maxSubSteps === void 0) {\n maxSubSteps = 10;\n }\n\n const time = performance.now() / 1000; // seconds\n\n if (!this.lastCallTime) {\n this.step(dt, undefined, maxSubSteps);\n } else {\n const timeSinceLastCalled = time - this.lastCallTime;\n this.step(dt, timeSinceLastCalled, maxSubSteps);\n }\n\n this.lastCallTime = time;\n }\n /**\n * Step the physics world forward in time.\n *\n * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.\n *\n * @param dt The fixed time step size to use.\n * @param timeSinceLastCalled The time elapsed since the function was last called.\n * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).\n * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F\n * @example\n * // fixed timestepping without interpolation\n * world.step(1 / 60)\n */\n\n\n step(dt, timeSinceLastCalled, maxSubSteps) {\n if (maxSubSteps === void 0) {\n maxSubSteps = 10;\n }\n\n if (timeSinceLastCalled === undefined) {\n // Fixed, simple stepping\n this.internalStep(dt); // Increment time\n\n this.time += dt;\n } else {\n this.accumulator += timeSinceLastCalled;\n const t0 = performance.now();\n let substeps = 0;\n\n while (this.accumulator >= dt && substeps < maxSubSteps) {\n // Do fixed steps to catch up\n this.internalStep(dt);\n this.accumulator -= dt;\n substeps++;\n\n if (performance.now() - t0 > dt * 1000) {\n // The framerate is not interactive anymore.\n // We are below the target framerate.\n // Better bail out.\n break;\n }\n } // Remove the excess accumulator, since we may not\n // have had enough substeps available to catch up\n\n\n this.accumulator = this.accumulator % dt;\n const t = this.accumulator / dt;\n\n for (let j = 0; j !== this.bodies.length; j++) {\n const b = this.bodies[j];\n b.previousPosition.lerp(b.position, t, b.interpolatedPosition);\n b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);\n b.previousQuaternion.normalize();\n }\n\n this.time += timeSinceLastCalled;\n }\n }\n\n internalStep(dt) {\n this.dt = dt;\n const contacts = this.contacts;\n const p1 = World_step_p1;\n const p2 = World_step_p2;\n const N = this.bodies.length;\n const bodies = this.bodies;\n const solver = this.solver;\n const gravity = this.gravity;\n const doProfiling = this.doProfiling;\n const profile = this.profile;\n const DYNAMIC = Body.DYNAMIC;\n let profilingStart = -Infinity;\n const constraints = this.constraints;\n const frictionEquationPool = World_step_frictionEquationPool;\n gravity.length();\n const gx = gravity.x;\n const gy = gravity.y;\n const gz = gravity.z;\n let i = 0;\n\n if (doProfiling) {\n profilingStart = performance.now();\n } // Add gravity to all objects\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.type === DYNAMIC) {\n // Only for dynamic bodies\n const f = bi.force;\n const m = bi.mass;\n f.x += m * gx;\n f.y += m * gy;\n f.z += m * gz;\n }\n } // Update subsystems\n\n\n for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {\n this.subsystems[i].update();\n } // Collision detection\n\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n p1.length = 0; // Clean up pair arrays from last step\n\n p2.length = 0;\n this.broadphase.collisionPairs(this, p1, p2);\n\n if (doProfiling) {\n profile.broadphase = performance.now() - profilingStart;\n } // Remove constrained pairs with collideConnected == false\n\n\n let Nconstraints = constraints.length;\n\n for (i = 0; i !== Nconstraints; i++) {\n const c = constraints[i];\n\n if (!c.collideConnected) {\n for (let j = p1.length - 1; j >= 0; j -= 1) {\n if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {\n p1.splice(j, 1);\n p2.splice(j, 1);\n }\n }\n }\n }\n\n this.collisionMatrixTick(); // Generate contacts\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n const oldcontacts = World_step_oldContacts;\n const NoldContacts = contacts.length;\n\n for (i = 0; i !== NoldContacts; i++) {\n oldcontacts.push(contacts[i]);\n }\n\n contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse\n\n const NoldFrictionEquations = this.frictionEquations.length;\n\n for (i = 0; i !== NoldFrictionEquations; i++) {\n frictionEquationPool.push(this.frictionEquations[i]);\n }\n\n this.frictionEquations.length = 0;\n this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused\n this.frictionEquations, frictionEquationPool);\n\n if (doProfiling) {\n profile.narrowphase = performance.now() - profilingStart;\n } // Loop over all collisions\n\n\n if (doProfiling) {\n profilingStart = performance.now();\n } // Add all friction eqs\n\n\n for (i = 0; i < this.frictionEquations.length; i++) {\n solver.addEquation(this.frictionEquations[i]);\n }\n\n const ncontacts = contacts.length;\n\n for (let k = 0; k !== ncontacts; k++) {\n // Current contact\n const c = contacts[k]; // Get current collision indeces\n\n const bi = c.bi;\n const bj = c.bj;\n const si = c.si;\n const sj = c.sj; // Get collision properties\n\n let cm;\n\n if (bi.material && bj.material) {\n cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;\n } else {\n cm = this.defaultContactMaterial;\n } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;\n\n\n cm.friction; // c.restitution = cm.restitution;\n // If friction or restitution were specified in the material, use them\n\n if (bi.material && bj.material) {\n if (bi.material.friction >= 0 && bj.material.friction >= 0) {\n bi.material.friction * bj.material.friction;\n }\n\n if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {\n c.restitution = bi.material.restitution * bj.material.restitution;\n }\n } // c.setSpookParams(\n // cm.contactEquationStiffness,\n // cm.contactEquationRelaxation,\n // dt\n // );\n\n\n solver.addEquation(c); // // Add friction constraint equation\n // if(mu > 0){\n // \t// Create 2 tangent equations\n // \tconst mug = mu * gnorm;\n // \tconst reducedMass = (bi.invMass + bj.invMass);\n // \tif(reducedMass > 0){\n // \t\treducedMass = 1/reducedMass;\n // \t}\n // \tconst pool = frictionEquationPool;\n // \tconst c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);\n // \tconst c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);\n // \tthis.frictionEquations.push(c1, c2);\n // \tc1.bi = c2.bi = bi;\n // \tc1.bj = c2.bj = bj;\n // \tc1.minForce = c2.minForce = -mug*reducedMass;\n // \tc1.maxForce = c2.maxForce = mug*reducedMass;\n // \t// Copy over the relative vectors\n // \tc1.ri.copy(c.ri);\n // \tc1.rj.copy(c.rj);\n // \tc2.ri.copy(c.ri);\n // \tc2.rj.copy(c.rj);\n // \t// Construct tangents\n // \tc.ni.tangents(c1.t, c2.t);\n // // Set spook params\n // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);\n // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);\n // c1.enabled = c2.enabled = c.enabled;\n // \t// Add equations to solver\n // \tsolver.addEquation(c1);\n // \tsolver.addEquation(c2);\n // }\n\n if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {\n const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();\n const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;\n\n if (speedSquaredB >= speedLimitSquaredB * 2) {\n bi.wakeUpAfterNarrowphase = true;\n }\n }\n\n if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {\n const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();\n const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;\n\n if (speedSquaredA >= speedLimitSquaredA * 2) {\n bj.wakeUpAfterNarrowphase = true;\n }\n } // Now we know that i and j are in contact. Set collision matrix state\n\n\n this.collisionMatrix.set(bi, bj, true);\n\n if (!this.collisionMatrixPrevious.get(bi, bj)) {\n // First contact!\n // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.\n World_step_collideEvent.body = bj;\n World_step_collideEvent.contact = c;\n bi.dispatchEvent(World_step_collideEvent);\n World_step_collideEvent.body = bi;\n bj.dispatchEvent(World_step_collideEvent);\n }\n\n this.bodyOverlapKeeper.set(bi.id, bj.id);\n this.shapeOverlapKeeper.set(si.id, sj.id);\n }\n\n this.emitContactEvents();\n\n if (doProfiling) {\n profile.makeContactConstraints = performance.now() - profilingStart;\n profilingStart = performance.now();\n } // Wake up bodies\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.wakeUpAfterNarrowphase) {\n bi.wakeUp();\n bi.wakeUpAfterNarrowphase = false;\n }\n } // Add user-added constraints\n\n\n Nconstraints = constraints.length;\n\n for (i = 0; i !== Nconstraints; i++) {\n const c = constraints[i];\n c.update();\n\n for (let j = 0, Neq = c.equations.length; j !== Neq; j++) {\n const eq = c.equations[j];\n solver.addEquation(eq);\n }\n } // Solve the constrained system\n\n\n solver.solve(dt, this);\n\n if (doProfiling) {\n profile.solve = performance.now() - profilingStart;\n } // Remove all contacts from solver\n\n\n solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details\n\n const pow = Math.pow;\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.type & DYNAMIC) {\n // Only for dynamic bodies\n const ld = pow(1.0 - bi.linearDamping, dt);\n const v = bi.velocity;\n v.scale(ld, v);\n const av = bi.angularVelocity;\n\n if (av) {\n const ad = pow(1.0 - bi.angularDamping, dt);\n av.scale(ad, av);\n }\n }\n }\n\n this.dispatchEvent(World_step_preStepEvent); // Leap frog\n // vnew = v + h*f/m\n // xnew = x + h*vnew\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n const stepnumber = this.stepnumber;\n const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;\n const quatNormalizeFast = this.quatNormalizeFast;\n\n for (i = 0; i !== N; i++) {\n bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);\n }\n\n this.clearForces();\n this.broadphase.dirty = true;\n\n if (doProfiling) {\n profile.integrate = performance.now() - profilingStart;\n } // Update step number\n\n\n this.stepnumber += 1;\n this.dispatchEvent(World_step_postStepEvent); // Sleeping update\n\n let hasActiveBodies = true;\n\n if (this.allowSleep) {\n hasActiveBodies = false;\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n bi.sleepTick(this.time);\n\n if (bi.sleepState !== Body.SLEEPING) {\n hasActiveBodies = true;\n }\n }\n }\n\n this.hasActiveBodies = hasActiveBodies;\n }\n\n emitContactEvents() {\n const hasBeginContact = this.hasAnyEventListener('beginContact');\n const hasEndContact = this.hasAnyEventListener('endContact');\n\n if (hasBeginContact || hasEndContact) {\n this.bodyOverlapKeeper.getDiff(additions, removals);\n }\n\n if (hasBeginContact) {\n for (let i = 0, l = additions.length; i < l; i += 2) {\n beginContactEvent.bodyA = this.getBodyById(additions[i]);\n beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);\n this.dispatchEvent(beginContactEvent);\n }\n\n beginContactEvent.bodyA = beginContactEvent.bodyB = null;\n }\n\n if (hasEndContact) {\n for (let i = 0, l = removals.length; i < l; i += 2) {\n endContactEvent.bodyA = this.getBodyById(removals[i]);\n endContactEvent.bodyB = this.getBodyById(removals[i + 1]);\n this.dispatchEvent(endContactEvent);\n }\n\n endContactEvent.bodyA = endContactEvent.bodyB = null;\n }\n\n additions.length = removals.length = 0;\n const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');\n const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');\n\n if (hasBeginShapeContact || hasEndShapeContact) {\n this.shapeOverlapKeeper.getDiff(additions, removals);\n }\n\n if (hasBeginShapeContact) {\n for (let i = 0, l = additions.length; i < l; i += 2) {\n const shapeA = this.getShapeById(additions[i]);\n const shapeB = this.getShapeById(additions[i + 1]);\n beginShapeContactEvent.shapeA = shapeA;\n beginShapeContactEvent.shapeB = shapeB;\n if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;\n if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;\n this.dispatchEvent(beginShapeContactEvent);\n }\n\n beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;\n }\n\n if (hasEndShapeContact) {\n for (let i = 0, l = removals.length; i < l; i += 2) {\n const shapeA = this.getShapeById(removals[i]);\n const shapeB = this.getShapeById(removals[i + 1]);\n endShapeContactEvent.shapeA = shapeA;\n endShapeContactEvent.shapeB = shapeB;\n if (shapeA) endShapeContactEvent.bodyA = shapeA.body;\n if (shapeB) endShapeContactEvent.bodyB = shapeB.body;\n this.dispatchEvent(endShapeContactEvent);\n }\n\n endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;\n }\n }\n /**\n * Sets all body forces in the world to zero.\n */\n\n\n clearForces() {\n const bodies = this.bodies;\n const N = bodies.length;\n\n for (let i = 0; i !== N; i++) {\n const b = bodies[i];\n b.force;\n b.torque;\n b.force.set(0, 0, 0);\n b.torque.set(0, 0, 0);\n }\n }\n\n} // Temp stuff\n\nnew AABB();\nconst tmpRay = new Ray(); // performance.now() fallback on Date.now()\n\nconst performance = globalThis.performance || {};\n\nif (!performance.now) {\n let nowOffset = Date.now();\n\n if (performance.timing && performance.timing.navigationStart) {\n nowOffset = performance.timing.navigationStart;\n }\n\n performance.now = () => Date.now() - nowOffset;\n}\n\nnew Vec3(); // Dispatched after the world has stepped forward in time.\n// Reusable event objects to save memory.\n\nconst World_step_postStepEvent = {\n type: 'postStep'\n}; // Dispatched before the world steps forward in time.\n\nconst World_step_preStepEvent = {\n type: 'preStep'\n};\nconst World_step_collideEvent = {\n type: Body.COLLIDE_EVENT_NAME,\n body: null,\n contact: null\n}; // Pools for unused objects\n\nconst World_step_oldContacts = [];\nconst World_step_frictionEquationPool = []; // Reusable arrays for collision pairs\n\nconst World_step_p1 = [];\nconst World_step_p2 = []; // Stuff for emitContactEvents\n\nconst additions = [];\nconst removals = [];\nconst beginContactEvent = {\n type: 'beginContact',\n bodyA: null,\n bodyB: null\n};\nconst endContactEvent = {\n type: 'endContact',\n bodyA: null,\n bodyB: null\n};\nconst beginShapeContactEvent = {\n type: 'beginShapeContact',\n bodyA: null,\n bodyB: null,\n shapeA: null,\n shapeB: null\n};\nconst endShapeContactEvent = {\n type: 'endShapeContact',\n bodyA: null,\n bodyB: null,\n shapeA: null,\n shapeB: null\n};\n\nexport { AABB, ArrayCollisionMatrix, BODY_SLEEP_STATES, BODY_TYPES, Body, Box, Broadphase, COLLISION_TYPES, ConeTwistConstraint, Constraint, ContactEquation, ContactMaterial, ConvexPolyhedron, Cylinder, DistanceConstraint, Equation, EventTarget, FrictionEquation, GSSolver, GridBroadphase, Heightfield, HingeConstraint, JacobianElement, LockConstraint, Mat3, Material, NaiveBroadphase, Narrowphase, ObjectCollisionMatrix, Particle, Plane, PointToPointConstraint, Pool, Quaternion, RAY_MODES, Ray, RaycastResult, RaycastVehicle, RigidVehicle, RotationalEquation, RotationalMotorEquation, SAPBroadphase, SHAPE_TYPES, SPHSystem, Shape, Solver, Sphere, SplitSolver, Spring, Transform, Trimesh, Vec3, Vec3Pool, WheelInfo, World };\n","// ===== tuples.ts ======================================================\n// Types & helpers for 3-tuples, used for positions, vectors and colours\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { vec3 } from 'gl-matrix'\nimport * as CANNON from 'cannon-es'\n\n/** A simple 3D position or vector tuple */\nexport type XYZ = [number, number, number]\n\n/** A simple 4D position or vector tuple */\nexport type XYZW = [number, number, number, number]\n\n/** A simple RGB colour tuple */\nexport type RGB = [number, number, number]\n\n/** A simple RGBA colour tuple */\nexport type RGBA = [number, number, number, number]\n\n// ============================================================================\n// Tuple helpers\n// ============================================================================\n\n/**\n * Normalizes a 3-tuple to a unit vector.\n * @param tuple The tuple to normalize\n */\nfunction normalize(tuple: XYZ | RGB | number[]) {\n const [x, y, z] = tuple\n const len = Math.sqrt(x * x + y * y + z * z)\n\n return tuple.map((v) => v / len) as XYZ\n}\n\n/**\n * Scales a 3-tuple by a scalar.\n * @param tuple The tuple to scale\n * @param scale The scalar to scale by\n */\nfunction scale(tuple: XYZ | RGB | RGBA | number[], amount: number) {\n return tuple.map((v) => v * amount) as XYZ\n}\n\n/**\n * Scales a 3-tuple by a scalar, clamping the result to 0-1.\n * @param tuple The tuple to scale\n * @param scale The scalar to scale by\n */\nfunction scaleClamped(colour: RGB | RGBA, amount: number) {\n scale(colour, amount)\n\n // Clamp to 0-1\n return colour.map((v) => Math.min(Math.max(v, 0), 1)) as RGB | RGBA\n}\n\n/**\n * Converts a 3-tuple to a gl-matrix vec3\n * @param tuple The tuple to convert\n */\nfunction toVec3(tuple: XYZ) {\n return vec3.fromValues(tuple[0], tuple[1], tuple[2])\n}\n\n/**\n * Calculates the distance between two 3-tuples\n * @param a First tuple\n * @param b Second tuple\n */\nfunction distance(a: XYZ, b: XYZ) {\n return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)\n}\n\nfunction add(a: XYZ, b: XYZ) {\n return [a[0] + b[0], a[1] + b[1], a[2] + b[2]] as XYZ\n}\n\n/**\n * Converts a Cannon.js vector or quaternion to a tuple\n * @param value The Cannon.js vector or quaternion to convert\n */\nfunction fromCannon(value: CANNON.Vec3 | CANNON.Quaternion) {\n if (value instanceof CANNON.Vec3) {\n return [value.x, value.y, value.z] as XYZ\n }\n\n return [value.x, value.y, value.z, value.w] as XYZW\n}\n\n// ============================================================================\n// Colour helpers\n// ============================================================================\n\n/**\n * Creates a RGB 3-tuple from 0-255 values.\n * @param r Red value (0-255)\n * @param g Green value (0-255)\n * @param b Blue value (0-255)\n */\nfunction rgbColour255(r: number, g: number, b: number) {\n return [r / 255, g / 255, b / 255] as RGB\n}\n\n/**\n * Converts a hex string to an RGB 3-tuple.\n * @param hexString\n */\nfunction rgbColourHex(hexString: string) {\n const hex = hexString.replace('#', '')\n const r = parseInt(hex.substring(0, 2), 16)\n const g = parseInt(hex.substring(2, 4), 16)\n const b = parseInt(hex.substring(4, 6), 16)\n\n return rgbColour255(r, g, b)\n}\n\n/**\n * A set of common colours as RGB tuples\n */\nexport const Colours = {\n RED: [1, 0, 0] as RGB,\n GREEN: [0, 1, 0] as RGB,\n BLUE: [0, 0, 1] as RGB,\n YELLOW: [1, 1, 0] as RGB,\n CYAN: [0, 1, 1] as RGB,\n MAGENTA: [1, 0, 1] as RGB,\n BLACK: [0, 0, 0] as RGB,\n WHITE: [1, 1, 1] as RGB,\n}\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport const Tuples = {\n normalize,\n scale,\n scaleClamped,\n rgbColour255,\n rgbColourHex,\n toVec3,\n distance,\n fromCannon,\n add,\n}\n","// ===== cache.ts =============================================================\n// Caches and managers for models and textures\n// Ben Coleman, 2023\n// ============================================================================\n\nimport log from 'loglevel'\nimport { Model } from '../renderable/model.ts'\nimport { ProgramInfo, createTexture } from 'twgl.js'\n\n/** @ignore */\nexport const PROG_DEFAULT = 'phong'\n/** @ignore */\nexport const PROG_BILLBOARD = 'billboard'\n\n/**\n * A singleton cache for parsed and loaded models, indexed by name\n */\nexport class ModelCache {\n private cache: Map\n private static _instance: ModelCache\n\n private constructor() {\n this.cache = new Map()\n }\n\n /**\n * Return the singleton instance of the model cache\n */\n static get instance() {\n if (!ModelCache._instance) {\n ModelCache._instance = new ModelCache()\n }\n\n return ModelCache._instance\n }\n\n /**\n * Return a model from the cache by name\n * @param name Name of model without extension\n * @param warn If true, log a warning if model not found\n */\n get(name: string, warn = true) {\n if (!this.cache.has(name) && warn) {\n log.warn(`⚠️ Model '${name}' not found, please load it first`)\n return undefined\n }\n\n return this.cache.get(name)\n }\n\n /**\n * Add a model to the cache, using the model name as key\n */\n add(model: Model) {\n log.debug(`🧰 Adding model '${model.name}' to cache`)\n\n this.cache.set(model.name, model)\n }\n}\n\n/**\n * A caching texture manager\n * It is instantiated with a WebGL context and then used to load and cache textures\n */\nexport class TextureCache {\n private cache: Map\n private gl: WebGL2RenderingContext\n private static _instance: TextureCache\n private static initialized = false\n private defaultWhite: WebGLTexture\n private defaultRand: WebGLTexture\n\n private constructor() {\n this.cache = new Map()\n this.gl = {} as WebGL2RenderingContext\n this.defaultWhite = {} as WebGLTexture\n this.defaultRand = {} as WebGLTexture\n }\n\n // Create a new texture cache\n static init(gl: WebGL2RenderingContext, randSize = 512) {\n this._instance = new TextureCache()\n this._instance.gl = gl\n\n // 1 pixel white texture used as base for materials\n const white1pixel = createTexture(gl, {\n min: gl.NEAREST,\n mag: gl.NEAREST,\n src: [255, 255, 255, 255],\n })\n\n // Random RGB texture, used for pseudo random number generation\n const randArray = new Uint8Array(randSize * randSize * 4)\n for (let i = 0; i < randSize * randSize * 4; i++) {\n randArray[i] = Math.floor(Math.random() * 255)\n }\n const randomRGB = createTexture(gl, {\n min: gl.NEAREST,\n mag: gl.NEAREST,\n src: randArray,\n width: randSize,\n height: randSize,\n wrap: gl.REPEAT,\n })\n\n this._instance.defaultWhite = white1pixel\n this._instance.defaultRand = randomRGB\n\n TextureCache.initialized = true\n }\n\n /**\n * Return the singleton instance of the texture cache\n */\n static get instance() {\n if (!TextureCache.initialized) {\n throw new Error('💥 TextureCache not initialized, call TextureCache.init() first')\n }\n\n return this._instance\n }\n\n /**\n * Return a texture from the cache by name\n * @param key Key of texture, this is usually the URL or filename path\n */\n get(key: string) {\n if (!this.cache.has(key)) {\n log.warn(`💥 Texture ${key} not found in cache`)\n return undefined\n }\n\n log.trace(`👍 Returning texture '${key}' from cache, nice!`)\n return this.cache.get(key)\n }\n\n /**\n * Add a texture to the cache\n * @param key Key of texture, this is usually the URL or filename path\n * @param texture WebGL texture\n */\n add(key: string, texture: WebGLTexture) {\n if (this.cache.has(key)) {\n log.warn(`🤔 Texture '${key}' already in cache, not adding again`)\n return\n }\n\n log.debug(`🧰 Adding texture '${key}' to cache`)\n\n this.cache.set(key, texture)\n }\n\n /**\n * Create or return a texture from the cache by name\n * @param src URL or filename path of texture image, or ArrayBufferView holding texture\n * @param filter Enable texture filtering and mipmaps (default true)\n * @param flipY Flip the texture vertically (default true)\n */\n getCreate(src: string | ArrayBufferView, filter = true, flipY = false, textureKey = '') {\n let key = ''\n\n if (typeof src === 'string') {\n key = src\n } else {\n if (textureKey === '') {\n throw new Error('💥 ArrayBuffer textures need a unique key')\n }\n\n key = textureKey\n }\n\n // Check if texture already exists, if so return it\n if (this.cache.has(key)) {\n log.trace(`👍 Returning texture '${key}' from cache, nice!`, flipY)\n return this.get(key)\n }\n\n // Create texture and add to cache\n // NOTE. Catching errors here is very hard, as twgl.createTexture() doesn't throw errors\n const texture = createTexture(\n this.gl,\n {\n min: filter ? this.gl.LINEAR_MIPMAP_LINEAR : this.gl.NEAREST,\n mag: filter ? this.gl.LINEAR : this.gl.NEAREST,\n src,\n flipY: flipY ? 1 : 0,\n },\n (err) => {\n if (err) {\n // There's not much we can do here, but log the error\n log.error('💥 Error loading texture', err)\n }\n },\n )\n\n this.add(key, texture)\n return texture\n }\n\n /**\n * Return the default white 1x1 texture\n */\n static get defaultWhite() {\n return this.instance.defaultWhite\n }\n\n /**\n * Return the default random RGB texture\n */\n static get defaultRand() {\n return this.instance.defaultRand\n }\n\n /**\n * Return the number of textures in the cache\n */\n static get size() {\n return this.instance.cache.size\n }\n\n /**\n * Clear the texture cache\n */\n static clear() {\n this.instance.cache.clear()\n }\n}\n\n/**\n * Singleton cache for parsed and loaded GL programs, indexed by name\n */\nexport class ProgramCache {\n private cache: Map\n private _default: ProgramInfo\n private static _instance: ProgramCache\n private static initialized = false\n\n public static PROG_PHONG = 'phong'\n public static PROG_BILLBOARD = 'billboard'\n public static PROG_SHADOWMAP = 'shadowmap'\n\n /**\n * Create a new program cache, can't be used until init() is called\n */\n private constructor() {\n this.cache = new Map()\n // This is pretty nasty, but we really trust people to call init() first\n this._default = {} as ProgramInfo\n }\n\n /**\n * Initialise the program cache with a default program.\n * This MUST be called before using the cache\n * @param defaultProg The default program that can be used by most things\n */\n public static init(defaultProg: ProgramInfo) {\n if (ProgramCache._instance) {\n log.warn('🤔 Program cache already initialised, not doing it again')\n return\n }\n\n ProgramCache._instance = new ProgramCache()\n ProgramCache._instance._default = defaultProg\n ProgramCache.initialized = true\n }\n\n /**\n * Return the singleton instance of the program cache\n */\n static get instance() {\n if (!ProgramCache.initialized) {\n throw new Error('💥 Program cache not initialised, call init() first')\n }\n\n return ProgramCache._instance\n }\n\n /**\n * Return a program from the cache by name\n * @param name Name of program\n */\n get(name: string): ProgramInfo {\n const prog = this.cache.get(name)\n\n if (!prog) {\n log.warn(`⚠️ Program '${name}' not found, returning default`)\n return this._default\n }\n\n return prog\n }\n\n add(name: string, program: ProgramInfo) {\n log.debug(`🧰 Adding program '${name}' to cache`)\n\n this.cache.set(name, program)\n }\n\n get default() {\n return this._default\n }\n}\n","// ===== camera.ts ============================================================\n// Represents a camera in 3D space\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4, vec3 } from 'gl-matrix'\nimport { XYZ } from './tuples.ts'\nimport { getGl } from '../core/gl.ts'\n\nimport log from 'loglevel'\n\nexport enum CameraType {\n PERSPECTIVE,\n ORTHOGRAPHIC,\n}\n\nexport class Camera {\n /** Camera position */\n public position: XYZ\n\n /** Camera look at point, default: [0, 0, 0] */\n public lookAt: XYZ\n\n /** Field of view in degrees, default: 45 */\n public fov: number\n\n /** Near clipping plane, default: 0.1 */\n public near: number\n\n /** Far clipping plane, default: 100 */\n public far: number\n\n /** Camera up vector, default: [0, 1, 0] */\n public up: XYZ\n\n /** Change camera projection, default: CameraType.PERSPECTIVE */\n public type: CameraType\n\n /** Is this camera active, default: true */\n public active: boolean\n\n /** Orthographic zoom level, only used when type is orthographic, default: 20 */\n public orthoZoom: number\n\n /** Is this camera used for a dynamic environment map, default: false */\n public usedForEnvMap: boolean\n\n /** Is this camera used for a shadow map, default: false */\n public usedForShadowMap: boolean\n\n /** Aspect ratio of the camera, default: 1 */\n public aspectRatio: number\n\n // Used for first person mode\n private fpAngleY: number\n private fpAngleX: number\n private fpMode: boolean\n private fpHandlersAdded: boolean\n private fpTurnSpeed: number\n private fpMoveSpeed: number\n\n // Used to clamp first person up/down angle\n private maxAngleUp: number = Math.PI / 2 - 0.01\n private maxAngleDown: number = -Math.PI / 2 + 0.01\n\n // Used to track keys pressed in FP mode for better movement\n private keysDown: Set\n private touches: Touch[] = []\n\n /**\n * Create a new default camera\n */\n constructor(type = CameraType.PERSPECTIVE, aspectRatio = 1) {\n this.type = type\n this.active = true\n\n this.position = [0, 0, 30]\n this.lookAt = [0, 0, 0]\n this.up = [0, 1, 0]\n this.near = 0.1\n this.far = 100\n this.fov = 45\n this.aspectRatio = aspectRatio\n this.orthoZoom = 20\n this.usedForEnvMap = false\n this.usedForShadowMap = false\n\n this.fpMode = false\n this.fpAngleY = 0\n this.fpAngleX = 0\n this.fpTurnSpeed = 0.001\n this.fpMoveSpeed = 1.0\n this.fpHandlersAdded = false\n\n this.keysDown = new Set()\n }\n\n /**\n * Get the current view matrix for the camera\n */\n get matrix() {\n // Standard view matrix with position and lookAt for non-FPS camera\n if (!this.fpMode) {\n const camView = mat4.targetTo(mat4.create(), this.position, this.lookAt, this.up)\n return camView\n }\n\n // FPS camera is handled different, we need to rotate the camera around the Y axis\n const camView = mat4.targetTo(mat4.create(), [0, 0, 0], [0, 0, -1], this.up)\n mat4.translate(camView, camView, this.position)\n mat4.rotateY(camView, camView, this.fpAngleY)\n mat4.rotateX(camView, camView, this.fpAngleX)\n\n return camView\n }\n\n /**\n * Get the projection matrix for this camera\n * @param aspectRatio Aspect ratio of the canvas\n */\n get projectionMatrix() {\n if (this.type === CameraType.ORTHOGRAPHIC) {\n const camProj = mat4.ortho(\n mat4.create(),\n -this.aspectRatio * this.orthoZoom,\n this.aspectRatio * this.orthoZoom,\n -this.orthoZoom,\n this.orthoZoom,\n this.near,\n this.far,\n )\n\n return camProj\n } else {\n const camProj = mat4.perspective(mat4.create(), this.fov * (Math.PI / 180), this.aspectRatio, this.near, this.far)\n return camProj\n }\n }\n\n /**\n * Get the corners of the view frustum for this camera in world space\n * @param scaleFar Scale the far plane to bring the frustum closer, default: 1\n */\n frustumCornersWorld(scaleFar = 1) {\n const far = this.far * scaleFar\n const nearHeight = Math.tan((this.fov * (Math.PI / 180)) / 2) * this.near\n const nearWidth = nearHeight * this.aspectRatio\n\n const farHeight = Math.tan((this.fov * (Math.PI / 180)) / 2) * far\n const farWidth = farHeight * this.aspectRatio\n\n const nearTopLeft = vec3.fromValues(nearWidth, nearHeight, -this.near)\n const nearTopRight = vec3.fromValues(-nearWidth, nearHeight, -this.near)\n const nearBottomLeft = vec3.fromValues(nearWidth, -nearHeight, -this.near)\n const nearBottomRight = vec3.fromValues(-nearWidth, -nearHeight, -this.near)\n\n const farTopLeft = vec3.fromValues(farWidth, farHeight, -far)\n const farTopRight = vec3.fromValues(-farWidth, farHeight, -far)\n const farBottomLeft = vec3.fromValues(farWidth, -farHeight, -far)\n const farBottomRight = vec3.fromValues(-farWidth, -farHeight, -far)\n\n const nearTopLeftWorld = vec3.transformMat4(vec3.create(), nearTopLeft, this.matrix)\n const nearTopRightWorld = vec3.transformMat4(vec3.create(), nearTopRight, this.matrix)\n const nearBottomLeftWorld = vec3.transformMat4(vec3.create(), nearBottomLeft, this.matrix)\n const nearBottomRightWorld = vec3.transformMat4(vec3.create(), nearBottomRight, this.matrix)\n\n const farTopLeftWorld = vec3.transformMat4(vec3.create(), farTopLeft, this.matrix)\n const farTopRightWorld = vec3.transformMat4(vec3.create(), farTopRight, this.matrix)\n const farBottomLeftWorld = vec3.transformMat4(vec3.create(), farBottomLeft, this.matrix)\n const farBottomRightWorld = vec3.transformMat4(vec3.create(), farBottomRight, this.matrix)\n\n // calculate the center of the frustum\n const center = vec3.create()\n vec3.add(center, nearTopLeftWorld, nearTopRightWorld)\n vec3.add(center, center, nearBottomLeftWorld)\n vec3.add(center, center, nearBottomRightWorld)\n vec3.add(center, center, farTopLeftWorld)\n vec3.add(center, center, farTopRightWorld)\n vec3.add(center, center, farBottomLeftWorld)\n vec3.add(center, center, farBottomRightWorld)\n vec3.scale(center, center, 1 / 8)\n\n return {\n nearTopLeftWorld,\n nearTopRightWorld,\n nearBottomLeftWorld,\n nearBottomRightWorld,\n farTopLeftWorld,\n farTopRightWorld,\n farBottomLeftWorld,\n farBottomRightWorld,\n center,\n }\n }\n\n /**\n * Get the camera position as a string for debugging\n */\n toString() {\n const pos = this.position.map((p) => p.toFixed(2))\n return `position: [${pos}]`\n }\n\n /**\n * Switches the camera to first person mode, where the camera is controlled by\n * the mouse and keyboard. The mouse controls look direction and the keyboard\n * controls movement.\n * @param angleY Starting look up/down angle in radians, default 0\n * @param angleX Starting look left/right angle in radians, default 0\n * @param turnSpeed Speed of looking in radians, default 0.001\n * @param moveSpeed Speed of moving in units, default 1.0\n */\n enableFPControls(angleY = 0, angleX = 0, turnSpeed = 0.001, moveSpeed = 1.0) {\n this.fpMode = true\n this.fpAngleY = angleY\n this.fpAngleX = angleX\n this.fpTurnSpeed = turnSpeed\n this.fpMoveSpeed = moveSpeed\n\n if (this.fpHandlersAdded) return // Prevent multiple event listeners being added\n\n // Handle enable/disable for pointer lock on main canvas\n // See: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API\n const gl = getGl()\n gl?.canvas.addEventListener('click', async () => {\n if (!this.fpMode || !this.active) return\n\n if (document.pointerLockElement) {\n document.exitPointerLock()\n } else {\n await (gl?.canvas).requestPointerLock()\n }\n })\n\n // Handle mouse movement for looking around\n window.addEventListener('mousemove', (e) => {\n if (!document.pointerLockElement) {\n return\n }\n\n if (!this.fpMode || !this.active) return\n this.fpAngleY += e.movementX * -this.fpTurnSpeed\n this.fpAngleX += e.movementY * -this.fpTurnSpeed\n\n // Clamp up/down angle\n if (this.fpAngleX > this.maxAngleUp) this.fpAngleX = this.maxAngleUp\n if (this.fpAngleX < this.maxAngleDown) this.fpAngleX = this.maxAngleDown\n\n // update the lookAt point\n const dZ = -Math.cos(this.fpAngleY) * 1\n const dX = -Math.sin(this.fpAngleY) * 1\n const dY = Math.sin(this.fpAngleX) * 1\n\n this.lookAt = [this.position[0] + dX, this.position[1] + dY, this.position[2] + dZ]\n })\n\n // Track keys pressed for movement\n window.addEventListener('keydown', (e) => {\n if (!this.fpMode || !this.active) return\n this.keysDown.add(e.key)\n })\n\n window.addEventListener('keyup', (e) => {\n if (!this.fpMode || !this.active) return\n this.keysDown.delete(e.key)\n })\n\n window.addEventListener('touchstart', (e) => {\n if (!this.fpMode || !this.active) return\n\n // If the touch is on the right side of the screen, it's for looking\n if (e.touches[0].clientX > window.innerWidth / 2) {\n this.touches[0] = e.touches[0]\n }\n\n // If the touch is on the left side of the screen, it's for moving\n if (e.touches[0].clientX < window.innerWidth / 2) {\n // Top half of screen is forward, bottom half is backward\n if (e.touches[0].clientY < window.innerHeight / 2) {\n this.keysDown.add('w')\n }\n if (e.touches[0].clientY > window.innerHeight / 2) {\n this.keysDown.add('s')\n }\n }\n })\n\n window.addEventListener('touchend', () => {\n if (!this.fpMode || !this.active) return\n\n this.touches = []\n this.keysDown.clear()\n })\n\n window.addEventListener('touchmove', (e) => {\n if (!this.fpMode || !this.active) return\n\n if (this.touches.length === 0) return\n\n const touch = e.touches[0]\n\n const dx = touch.clientX - this.touches[0].clientX\n const dy = touch.clientY - this.touches[0].clientY\n\n this.fpAngleY += dx * -this.fpTurnSpeed * touch.force * 4\n this.fpAngleX += dy * -this.fpTurnSpeed * touch.force * 4\n\n // Clamp up/down angle\n if (this.fpAngleX > this.maxAngleUp) this.fpAngleX = this.maxAngleUp\n if (this.fpAngleX < this.maxAngleDown) this.fpAngleX = this.maxAngleDown\n\n this.touches[0] = touch\n })\n\n this.fpHandlersAdded = true\n log.info('🎥 Camera: first person mode & controls enabled')\n }\n\n /**\n * Disable FP mode\n */\n disableFPControls() {\n this.fpMode = false\n document.exitPointerLock()\n log.debug('🎥 Camera: FPS mode disabled')\n }\n\n /**\n * Get FP mode state\n */\n get fpModeEnabled() {\n return this.fpMode\n }\n\n /**\n * Called every frame to update the camera, currently only used for movement in FP mode\n */\n update() {\n if (!this.fpMode || !this.active) return\n if (this.keysDown.size === 0) return\n\n // Use fpAngleY to calculate the direction we are facing\n const dZ = -Math.cos(this.fpAngleY) * this.fpMoveSpeed\n const dX = -Math.sin(this.fpAngleY) * this.fpMoveSpeed\n\n // Use keysDown to move the camera\n for (const key of this.keysDown.values()) {\n switch (key) {\n case 'ArrowUp':\n case 'w':\n this.position[0] += dX\n this.position[2] += dZ\n this.lookAt[0] += dX\n this.lookAt[2] += dZ\n break\n\n case 'ArrowDown':\n case 's':\n this.position[0] -= dX\n this.position[2] -= dZ\n this.lookAt[0] -= dX\n this.lookAt[2] -= dZ\n break\n\n case 'ArrowLeft':\n case 'a':\n this.position[0] += dZ\n this.position[2] -= dX\n this.lookAt[0] += dZ\n this.lookAt[2] -= dX\n break\n\n case 'ArrowRight':\n case 'd':\n // Move right\n this.position[0] -= dZ\n this.position[2] += dX\n this.lookAt[0] -= dZ\n this.lookAt[2] += dX\n break\n\n case ']':\n // Move up\n this.position[1] += this.fpMoveSpeed * 0.75\n this.lookAt[1] += this.fpMoveSpeed * 0.75\n break\n\n case '[':\n // Move down\n this.position[1] -= this.fpMoveSpeed * 0.75\n this.lookAt[1] -= this.fpMoveSpeed * 0.75\n break\n }\n }\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Shadow map fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nvoid main() {\n // Yeah I don't understand this either, but it works\n}\n","#version 300 es\n\n// ============================================================================\n// Shadow map vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\n\nuniform mat4 u_worldViewProjection;\n\nvoid main() {\n gl_Position = u_worldViewProjection * position;\n}\n","// ===== light.ts =============================================================\n// All light types, including directional and point\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport * as twgl from 'twgl.js'\n\nimport { UniformSet, getGl } from '../core/gl.ts'\nimport { Camera, CameraType } from './camera.ts'\nimport { Colours, Tuples, XYZ, RGB } from './tuples.ts'\n\nimport fragShaderShadow from '../../shaders/shadowmap/glsl.frag'\nimport vertShaderShadow from '../../shaders/shadowmap/glsl.vert'\n\n/**\n * Options to configure how shadows are calculated & rendered\n */\nexport type ShadowOptions = {\n /** Size of the shadow map texture. Default: 512 */\n mapSize: number\n\n /** Zoom level of the shadow map camera, larger will cover more of the scene, but results in more blocky shadows. Default 120 */\n zoom: number\n\n /** Far clipping pane of shadow map camera, default 1000 */\n distance: number\n\n /** Blur the edges of shadows, higher values them more random, default 0.2 */\n // scatter: number\n\n /** Offset used to reduce shadow acne especially when self shadowing */\n polygonOffset: number\n}\n\n/**\n * A directional light source, typically global with the context having only a single instance\n * Having multiple directional lights is not supported\n */\nexport class LightDirectional {\n private _direction: XYZ\n private _shadowMapProgram?: twgl.ProgramInfo\n private _shadowMapFB?: twgl.FramebufferInfo\n private _shadowMapTex?: WebGLTexture\n private _shadowOptions?: ShadowOptions\n\n /** Colour of the light, used for both diffuse and specular. Default: [0, 0, 0] */\n public colour: RGB\n\n /** Ambient colour of the light. Default: [0, 0, 0] */\n public ambient: RGB\n\n /** Is this light enabled. Default: true */\n public enabled: boolean\n\n /** Create a default directional light, pointing downward */\n constructor() {\n this._direction = [0, -1, 0]\n this.colour = Colours.WHITE\n this.ambient = Colours.BLACK\n this.enabled = true\n\n const gl = getGl()\n if (!gl) {\n throw new Error('💥 LightDirectional: Cannot create shadow map shader, no GL context')\n }\n\n this._shadowMapProgram = twgl.createProgramInfo(gl, [vertShaderShadow, fragShaderShadow], ['shadowProgram'])\n }\n\n /**\n * Set the direction of the light ensuring it is normalized\n * @param direction - Direction vector\n */\n set direction(direction: XYZ) {\n // Ensure direction is normalized\n this._direction = Tuples.normalize(direction)\n }\n\n /**\n * Get the direction of the light\n */\n get direction() {\n return this._direction\n }\n\n /**\n * Convenience method allows setting the direction as a point relative to the world origin\n * Values are always converted to a normalized unit direction vector\n * @param x - X position\n * @param y - Y position\n * @param z - Z position\n */\n setAsPosition(x: number, y: number, z: number) {\n this._direction = Tuples.normalize([0 - x, 0 - y, 0 - z])\n }\n\n /**\n * Return the base set of uniforms for this light\n */\n get uniforms() {\n return {\n direction: this.direction,\n colour: this.enabled ? this.colour : [0, 0, 0],\n ambient: this.ambient ? this.ambient : [0, 0, 0],\n } as UniformSet\n }\n\n /**\n * Enable shadows for this light, this will create a shadow map texture and framebuffer\n * There is no way to disabled shadows once enabled\n * @param options A set of ShadowOptions to configure how shadows are calculated\n */\n enableShadows(options?: ShadowOptions) {\n this._shadowOptions = options ?? ({} as ShadowOptions)\n if (!this._shadowOptions.mapSize) {\n this._shadowOptions.mapSize = 512\n }\n if (!this._shadowOptions.zoom) {\n this._shadowOptions.zoom = 120\n }\n if (!this._shadowOptions.distance) {\n this._shadowOptions.distance = 1000\n }\n // if (!this._shadowOptions.scatter) {\n // this._shadowOptions.scatter = 0.22\n // }\n if (!this._shadowOptions.polygonOffset) {\n this._shadowOptions.polygonOffset = 0\n }\n\n const gl = getGl()\n if (!gl) {\n throw new Error('💥 LightDirectional: Cannot create shadow map, no GL context')\n }\n\n // This is a special type of texture, used for depth comparison and shadow mapping\n this._shadowMapTex = twgl.createTexture(gl, {\n width: this._shadowOptions.mapSize,\n height: this._shadowOptions.mapSize,\n internalFormat: gl.DEPTH_COMPONENT32F, // Makes this a depth texture\n compareMode: gl.COMPARE_REF_TO_TEXTURE, // Becomes a shadow map, e.g. sampler2DShadow\n minMag: gl.LINEAR, // Can be linear sampled only if compare mode is set\n })\n\n // Framebuffer to render the shadow map into\n this._shadowMapFB = twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._shadowMapTex, attachmentPoint: gl.DEPTH_ATTACHMENT }],\n this._shadowOptions.mapSize,\n this._shadowOptions.mapSize,\n )\n }\n\n /**\n * Get a virtual camera that can be used to render a shadow map for this light\n * @param viewCam - The main camera used to view the scene, needed to get a good shadow view\n */\n getShadowCamera(viewCam: Camera) {\n if (!this._shadowOptions) {\n return undefined\n }\n\n // Get view frustum corners & center to calculate a good shadow map view\n const corners = viewCam.frustumCornersWorld(this._shadowOptions.zoom / viewCam.far)\n const viewFrustumCenter = corners.center as XYZ\n\n // Create a virtual camera to render the shadow map\n const cam = new Camera(CameraType.ORTHOGRAPHIC, 1)\n cam.usedForShadowMap = true\n cam.position = [\n viewFrustumCenter[0] + -this.direction[0] * this._shadowOptions.distance,\n viewFrustumCenter[1] + -this.direction[1] * this._shadowOptions.distance,\n viewFrustumCenter[2] + -this.direction[2] * this._shadowOptions.distance,\n ]\n\n cam.lookAt = viewFrustumCenter\n cam.far = this._shadowOptions.distance * 2\n cam.orthoZoom = this._shadowOptions.zoom\n\n return cam\n }\n\n /**\n * Get the forward view matrix for the virtual camera used to render the shadow map.\n * Returns undefined if shadows are not enabled\n * @param viewCam - The main camera used to view the scene, needed to get a good shadow view\n */\n getShadowMatrix(viewCam: Camera) {\n if (!this._shadowOptions) {\n return undefined\n }\n\n const shadowCam = this.getShadowCamera(viewCam)\n if (!shadowCam) {\n return undefined\n }\n\n const shadowMat = mat4.multiply(\n mat4.create(),\n shadowCam.projectionMatrix,\n mat4.invert(mat4.create(), shadowCam.matrix),\n )\n\n return shadowMat\n }\n\n /**\n * Are shadows enabled for this light?\n */\n get shadowsEnabled() {\n return this._shadowOptions !== undefined\n }\n\n /**\n * Get the shadow map program, will be undefined if shadows are not enabled\n */\n get shadowMapProgram() {\n return this._shadowMapProgram\n }\n\n /**\n * Get the shadow map framebuffer, will be undefined if shadows are not enabled\n */\n get shadowMapFrameBufffer() {\n return this._shadowMapFB\n }\n\n /**\n * Get the shadow map texture, will be undefined if shadows are not enabled\n */\n get shadowMapTexture() {\n return this._shadowMapTex\n }\n\n /**\n * Get the shadow map options, will be undefined if shadows are not enabled\n */\n get shadowMapOptions() {\n return this._shadowOptions\n }\n}\n\n/*\n * A point light source, doesn't cast shadows but does attenuate with distance\n */\nexport class LightPoint {\n /** Position of the light in world space. */\n public position: XYZ\n\n /** Colour of the light. Default: [1, 1, 1] */\n public colour: RGB\n\n /** Ambient colour of the light. Normally none for point lights. Default [0, 0, 0] */\n public ambient: RGB\n\n /** Light attenuation parameter for constant drop off rate. Default: 0.5 */\n public constant: number\n\n /** Light attenuation parameter for linear drop off rate. Default: 0.018 */\n public linear: number\n\n /** Light attenuation parameter for quadratic drop off rate. Default: 0.0003 */\n public quad: number\n\n /** Is this light enabled? Default: true */\n public enabled: boolean\n\n /**\n * Create a default point light, positioned at the world origin\n * @param position - Position of the light in world space\n * @param colour - Colour of the light\n * @param constant - Attenuation constant drop off rate, default 0.5\n * @param linear - Attenuation linear drop off rate, default 0.018\n * @param quad - Attenuation quadratic drop off rate, default 0.0003\n */\n constructor(position: XYZ, colour: RGB, constant = 0.5, linear = 0.018, quad = 0.0003) {\n this.position = position\n this.colour = colour\n this.constant = constant\n this.linear = linear\n this.quad = quad\n\n // No ambient contribution by default, this can get messy otherwise\n this.ambient = Colours.BLACK\n this.enabled = true\n }\n\n /**\n * Return the base set of uniforms for this light\n */\n public get uniforms() {\n return {\n enabled: this.enabled,\n quad: this.quad,\n position: this.position,\n colour: this.colour,\n ambient: this.ambient,\n constant: this.constant,\n linear: this.linear,\n } as UniformSet\n }\n}\n","// ===== envmap.ts ==========================================================\n// EnvironmentMap class, for rendering reflections\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { mat4 } from 'gl-matrix'\nimport log from 'loglevel'\n\nimport { Camera, CameraType } from './camera.ts'\nimport { XYZ } from './tuples.ts'\n\nimport fragShaderEnvmap from '../../shaders/envmap/glsl.frag'\nimport vertShaderEnvmap from '../../shaders/envmap/glsl.vert'\nimport { Stats } from '../core/stats.ts'\nimport { Context } from '../core/context.ts'\n\nexport class EnvironmentMap {\n private programInfo: twgl.ProgramInfo\n private gl: WebGL2RenderingContext\n private _texture: WebGLTexture\n private cube: twgl.BufferInfo\n\n /**\n * Render the environment map as a background, like a skybox\n */\n public renderAsBackground: boolean\n\n /**\n * Create a new environment map with 6 textures for each side\n * @param gl GL context\n * @param textureURLs Array of 6 texture URLs, in order: +x, -x, +y, -y, +z, -z\n */\n constructor(gl: WebGL2RenderingContext, textureURLs: string[]) {\n this.gl = gl\n\n // Create shader program for special envmap rendering\n this.programInfo = twgl.createProgramInfo(gl, [vertShaderEnvmap, fragShaderEnvmap])\n\n // Create the cube\n this.cube = twgl.primitives.createCubeBufferInfo(gl, 1)\n this.renderAsBackground = true\n\n log.info(`🏔️ EnvironmentMap created!`)\n\n // Don't go via the texture cache, as cube maps are a special case\n if (textureURLs.length !== 6) {\n throw new Error('💥 Cubemap requires 6 textures')\n }\n\n this._texture = twgl.createTexture(gl, {\n target: gl.TEXTURE_CUBE_MAP,\n src: textureURLs,\n min: gl.LINEAR_MIPMAP_LINEAR,\n mag: gl.LINEAR,\n cubeFaceOrder: [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ],\n flipY: 0,\n })\n }\n\n /**\n * Render this envmap as a cube around the given camera & matrices\n * This is used for rendering the envmap as a background and skybox around the scene\n * @param viewMatrix View matrix\n * @param projMatrix Projection matrix\n * @param camera Camera\n */\n render(viewMatrix: mat4, projMatrix: mat4, camera: Camera) {\n if (!this.renderAsBackground) return\n\n this.gl.useProgram(this.programInfo.program)\n // Note: Disable depth test so envmap is always drawn behind everything else\n this.gl.disable(this.gl.DEPTH_TEST)\n\n const uniforms = {\n u_envMapTex: this._texture,\n u_worldViewProjection: mat4.create(),\n }\n\n const world = mat4.create()\n // Envmap magic 1 - translate envmap is always centered on camera\n mat4.translate(world, world, camera.position)\n // Envmap magic 2 - scale the envmap to be the same size as the camera far plane\n // This means it will always be drawn\n mat4.scale(world, world, [camera.far, camera.far, camera.far])\n\n // Create worldView matrix, used for positioning\n const worldView = mat4.multiply(mat4.create(), viewMatrix, world)\n\n mat4.multiply(uniforms.u_worldViewProjection, projMatrix, worldView)\n\n twgl.setBuffersAndAttributes(this.gl, this.programInfo, this.cube)\n twgl.setUniforms(this.programInfo, uniforms)\n twgl.drawBufferInfo(this.gl, this.cube)\n Stats.drawCallsPerFrame++\n\n this.gl.enable(this.gl.DEPTH_TEST)\n }\n\n get texture(): WebGLTexture {\n return this._texture\n }\n}\n\n/**\n * Used for rendering a dynamic environment map, to create realtime reflections\n * For performance reasons, there is only one dynamic envmap per scene context\n */\nexport class DynamicEnvironmentMap {\n private _texture: WebGLTexture\n private facings: DynamicEnvMapFace[] = []\n private camera: Camera\n\n /**\n * Create a new dynamic environment map\n * @param gl GL context\n * @param size Size of each face of the cube map\n * @param position Position of the center of the cube map, reflections will be rendered from here\n */\n constructor(gl: WebGL2RenderingContext, size: number, position: XYZ, far: number) {\n // The main texture cubemap\n this._texture = twgl.createTexture(gl, {\n target: gl.TEXTURE_CUBE_MAP,\n width: size,\n height: size,\n minMag: gl.LINEAR,\n cubeFaceOrder: [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ],\n })\n\n // This array holds the 6 faces of the cube map and the framebuffer info plus direction\n this.facings = [\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n direction: [1, 0, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_X }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n direction: [-1, 0, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_X }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n direction: [0, 1, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_Y }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n direction: [0, -1, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n direction: [0, 0, 1],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_Z }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n direction: [0, 0, -1],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n ]\n\n this.camera = new Camera(CameraType.PERSPECTIVE)\n this.camera.position = position\n this.camera.fov = 90 // 90 degree FOV for cubemap to work properly\n\n // IMPORTANT: Mark this as a special camera used for envmaps\n this.camera.usedForEnvMap = true\n\n this.camera.far = far\n }\n\n /** Get the texture of the environment cubemap */\n get texture(): WebGLTexture {\n return this._texture\n }\n\n /**\n * This is used to position the camera for creating the reflection map\n * @param position Position of the center of the cube map\n */\n set position(pos: XYZ) {\n this.camera.position = pos\n }\n\n /**\n * Update the environment map, by rendering the scene from the given position into the cubemap texture\n * @param ctx GSOTS Context\n */\n update(gl: WebGL2RenderingContext, ctx: Context) {\n // Render each face of the cubemap into the texture & framebuffer\n // NOTE: This requires SIX calls to renderWithCamera!\n for (const facing of this.facings) {\n // Update the camera to look in the direction of the face\n this.camera.lookAt = [\n this.camera.position[0] + facing.direction[0],\n this.camera.position[1] + facing.direction[1],\n this.camera.position[2] + facing.direction[2],\n ]\n\n // Stops the camera from flipping upside down and other weirdness\n this.camera.up = [0, -1, 0]\n if (facing.face === gl.TEXTURE_CUBE_MAP_NEGATIVE_Y) {\n this.camera.up = [0, 0, -1]\n }\n if (facing.face === gl.TEXTURE_CUBE_MAP_POSITIVE_Y) {\n this.camera.up = [0, 0, 1]\n }\n\n twgl.bindFramebufferInfo(gl, facing.buffer)\n ctx.renderWithCamera(this.camera)\n }\n }\n}\n\n/**\n * Internal type for storing a dynamic envmap facing info\n */\ntype DynamicEnvMapFace = {\n face: number\n direction: XYZ\n buffer: twgl.FramebufferInfo\n}\n","#version 300 es\n\n// ============================================================================\n// Environment map fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec3 v_texCoord;\n\nuniform samplerCube u_envMapTex;\n\nout vec4 outColour;\n\nvoid main() {\n // Use the texture cube map as the colour\n // Note: We don't need to do any lighting calculations here\n outColour = texture(u_envMapTex, v_texCoord);\n}\n","#version 300 es\n\n// ============================================================================\n// Environment map vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\n\nuniform mat4 u_worldViewProjection;\n\nout vec3 v_texCoord;\n\nvoid main() {\n // This essentially is what makes the envmap work, texCoords\n // are taken from the vertex position\n v_texCoord = position.xyz;\n\n gl_Position = u_worldViewProjection * position;\n}\n","// ===== stats.ts =======================================================\n// Global singleton for keeping track of stats, timers performance\n// Ben Coleman, 2023\n// ======================================================================\n\nexport const Stats = {\n drawCallsPerFrame: 0,\n instances: 0,\n triangles: 0,\n\n prevTime: 0,\n deltaTime: 0,\n totalTime: 0,\n frameCount: 0,\n fpsBucket: [] as number[],\n\n resetPerFrame() {\n Stats.drawCallsPerFrame = 0\n },\n\n updateTime(now: number) {\n Stats.deltaTime = now * 0.001 - Stats.prevTime // Get smoothed time difference\n Stats.prevTime = now * 0.001\n Stats.totalTime += Stats.deltaTime\n\n Stats.fpsBucket.push(Stats.deltaTime)\n if (Stats.fpsBucket.length > 10) {\n Stats.fpsBucket.shift()\n }\n },\n\n get FPS() {\n const sum = Stats.fpsBucket.reduce((a, b) => a + b, 0)\n return Math.round(1 / (sum / Stats.fpsBucket.length))\n },\n\n get totalTimeRound() {\n return Math.round(Stats.totalTime)\n },\n}\n","// ===== node.ts ===============================================================================\n// Node in the scene used to position, rotate and scale them, with a parent/child relationship\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport { mat4, quat } from 'gl-matrix'\nimport { Tuples, XYZ, XYZW } from './tuples.ts'\n\nimport log from 'loglevel'\nimport * as CANNON from 'cannon-es'\n\nconst EVENT_POSITION = 'position'\n\n/** Event triggered when a node position, rotation or scale changes */\nexport type NodeEvent = {\n position: XYZ\n rotation: XYZW\n scale: XYZ\n nodeId: string\n}\n\n/**\n * A Node with position, rotation, scale, all Instances extend this class.\n * But Nodes also be created to group instances and simplify transformations.\n */\nexport class Node {\n /** Unique ID for this node */\n public readonly id: string\n\n /** Position of this Node in world space, relative to any parent nodes (if any) */\n public position: XYZ\n\n /** Scale of this Node in world space, relative to any parent nodes (if any) */\n public scale: XYZ\n\n /** Rotation quaternion of this Node in world space, relative to any parent nodes (if any) */\n public quaternion: quat\n\n /** Metadata is a key/value store for any extra data you want to store on a node */\n public metadata: Record\n\n // Private properties with getters/setters\n private _receiveShadow: boolean\n private _castShadow: boolean\n private _enabled: boolean\n private _parent?: Node\n private _children: Node[] = []\n private _physicsBody?: CANNON.Body\n\n // Event handlers\n private eventHandlers: Map void)[]>\n\n /** Create a default node, at origin with scale of [1,1,1] and no rotation */\n constructor() {\n this.id = uniqueId()\n this.metadata = {}\n this.eventHandlers = new Map()\n this.eventHandlers.set(EVENT_POSITION, [])\n\n this.position = [0, 0, 0]\n this.scale = [1, 1, 1]\n this.quaternion = quat.create()\n\n this._enabled = true\n this._receiveShadow = true\n this._castShadow = true\n this._physicsBody = undefined\n\n log.debug(`📍 Node created with id ${this.id}`)\n }\n\n /** Rotate this instance around the X, Y and Z axis in radians */\n rotate(ax: number, ay: number, az: number) {\n quat.rotateX(this.quaternion, this.quaternion, ax)\n quat.rotateY(this.quaternion, this.quaternion, ay)\n quat.rotateZ(this.quaternion, this.quaternion, az)\n }\n\n /** Rotate this instance around the X axis*/\n rotateX(angle: number) {\n quat.rotateX(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the Y axis*/\n rotateY(angle: number) {\n quat.rotateY(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the Z axis, in radians*/\n rotateZ(angle: number) {\n quat.rotateZ(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the X axis by a given angle in degrees */\n rotateZDeg(angle: number) {\n this.rotateZ((angle * Math.PI) / 180)\n }\n\n /** Rotate this instance around the Y axis by a given angle in degrees */\n rotateYDeg(angle: number) {\n this.rotateY((angle * Math.PI) / 180)\n }\n\n /** Rotate this instance around the Z axis by a given angle in degrees */\n rotateXDeg(angle: number) {\n this.rotateX((angle * Math.PI) / 180)\n }\n\n /** Set the rotation quaternion directly, normally users should use the rotate methods.\n * This method is for advanced uses, like integration with an external physics system */\n setQuaternion(quatArray: XYZW) {\n this.quaternion = quat.fromValues(quatArray[0], quatArray[1], quatArray[2], quatArray[3])\n }\n\n /** Get the rotation quaternion as a XYZW 4-tuple */\n getQuaternion(): XYZW {\n return [this.quaternion[0], this.quaternion[1], this.quaternion[2], this.quaternion[3]]\n }\n\n /**\n * Return the world or model matrix for this node, this is the matrix that places this node in the world.\n * This will be in relation to the parent node, if there is one.\n */\n get modelMatrix(): mat4 {\n const modelMatrix = mat4.fromRotationTranslationScale(mat4.create(), this.quaternion, this.position, this.scale)\n\n if (!this.parent) {\n return modelMatrix\n }\n\n mat4.multiply(modelMatrix, this.parent.modelMatrix ?? mat4.create(), modelMatrix)\n\n return modelMatrix\n }\n\n /** Convenience method to make another Node a child of this one */\n addChild(node: Node) {\n node._parent = this\n\n this._children.push(node)\n }\n\n /** Convenience method to remove a child Node */\n removeChild(node: Node) {\n node._parent = undefined\n\n this._children = this._children.filter((child) => child.id !== node.id)\n }\n\n /** Convenience method to remove all child Nodes */\n removeAllChildren() {\n this._children.forEach((child) => {\n child._parent = undefined\n })\n\n this._children = []\n }\n\n /** Sets the parent this Node, to the provided Node */\n set parent(node: Node | undefined) {\n // remove from old parent if there is one\n if (this._parent) {\n this._parent.removeChild(this)\n }\n\n // Add to new parent if there is one\n if (node) {\n node.addChild(this)\n }\n }\n\n /** Fetch all child Nodes of this Node */\n get children(): Node[] {\n return this._children\n }\n\n /** Get current parent of this Node */\n get parent(): Node | undefined {\n return this._parent\n }\n\n /** Is this Node enabled. Disabled nodes will not be rendered */\n get enabled(): boolean {\n return this._enabled\n }\n\n /** Set enabled state of this Node, this will also set all child nodes */\n set enabled(enabled: boolean) {\n this._enabled = enabled\n\n this._children.forEach((child) => {\n child.enabled = enabled\n })\n }\n\n /** Does this Node cast shadows, default true */\n public get castShadow(): boolean {\n return this._castShadow\n }\n\n /** Set will this Node cast shadows, this will also set all child nodes */\n public set castShadow(value: boolean) {\n this._castShadow = value\n\n this._children.forEach((child) => {\n child.castShadow = value\n })\n }\n\n /** Does this Node receive shadows, default true */\n public get receiveShadow(): boolean {\n return this._receiveShadow\n }\n\n /** Set will this Node receive shadows, this will also set all child nodes */\n public set receiveShadow(value: boolean) {\n this._receiveShadow = value\n\n this._children.forEach((child) => {\n child.receiveShadow = value\n })\n }\n\n /** Get the physics body for this Node, if there is one */\n public get physicsBody(): CANNON.Body | undefined {\n return this._physicsBody\n }\n\n /** Set the physics body for this Node */\n public set physicsBody(body: CANNON.Body | undefined) {\n this._physicsBody = body\n }\n\n /**\n * Updates the position & rotation of this node to match it's linked physics Body\n * This is called automatically by the engine, but can be called manually if needed\n */\n public updateFromPhysicsBody() {\n if (!this._physicsBody) return\n\n this.position = Tuples.fromCannon(this._physicsBody.position) as XYZ\n this.setQuaternion(Tuples.fromCannon(this._physicsBody.quaternion) as XYZW)\n\n // Trigger position event handlers\n for (const handler of this.eventHandlers.get(EVENT_POSITION) ?? []) {\n handler({\n position: this.position,\n rotation: this.getQuaternion(),\n scale: this.scale,\n nodeId: this.id,\n })\n }\n }\n\n /**\n * Add an event handler to listen for node changes\n * @param event NodeEvent type, one of 'position', 'rotation', 'scale'\n * @param handler Function to call when event is triggered\n */\n addEventHandler(event: string, handler: (event: NodeEvent) => void) {\n this.eventHandlers.get(event)?.push(handler)\n }\n}\n\n/** Generate a unique ID for a node */\nfunction uniqueId() {\n const dateString = Date.now().toString(36).substring(0, 5)\n const randomness = Math.random().toString(36).substring(0, 5)\n return dateString + randomness\n}\n","// ===== instance.ts ==========================================================\n// Instance class, holds position, rotation, scale etc for a renderable\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { XYZ } from '../engine/tuples.ts'\nimport { ProgramInfo } from 'twgl.js'\nimport { Node } from '../engine/node.ts'\n\n/**\n * An instance of thing in the world to be rendered, with position, rotation, scale etc\n */\nexport class Instance extends Node {\n /** Main renderable thing this instance represents */\n public readonly renderable: Renderable | undefined\n\n /** Flip all textures on this instance on the X axis */\n public flipTextureX = false\n\n /** Flip all textures on this instance on the Y axis */\n public flipTextureY = false\n\n /** Material override. This will override the renderable's material.\n * This is only useful on simple models that probably consist of one surface */\n public material?: Material\n\n /**\n * Create a new instace of a renderable thing\n * @param {Renderable} renderable - Renderable to use for this instance\n */\n constructor(renderable: Renderable) {\n super()\n this.renderable = renderable\n }\n\n setPosition(x: number | XYZ, y?: number, z?: number) {\n if (x instanceof Array) {\n this.position = x\n return\n }\n\n if (y === undefined || z === undefined) throw new Error('setPosition requires either an array or 3 numbers')\n\n this.position = [x, y, z]\n }\n\n /**\n * Render this instance in the world, called internally by the context when rendering\n * @param {WebGL2RenderingContext} gl - WebGL context to render into\n * @param {UniformSet} uniforms - Map of uniforms to pass to shader\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet, programOverride?: ProgramInfo) {\n if (!this.enabled) return\n if (!this.renderable) return\n if (!gl) return\n\n // HACK: As programOverride is CURRENTLY only used for shadow map rendering\n // We need a better way to to know if we are rendering a shadow map!!\n if (programOverride && !this.castShadow) {\n return\n }\n\n const world = this.modelMatrix\n\n // Populate u_world - used for normals & shading\n uniforms.u_world = world\n\n // Populate u_worldInverseTranspose - used for normals & shading\n mat4.invert(uniforms.u_worldInverseTranspose, world)\n mat4.transpose(uniforms.u_worldInverseTranspose, uniforms.u_worldInverseTranspose)\n\n // Create worldView matrix, used for positioning\n const worldView = mat4.multiply(mat4.create(), uniforms.u_view, world)\n\n // Finally populate u_worldViewProjection used for rendering\n mat4.multiply(uniforms.u_worldViewProjection, uniforms.u_proj, worldView)\n\n // Apply per instance uniforms for the shader\n uniforms.u_flipTextureX = this.flipTextureX\n uniforms.u_flipTextureY = this.flipTextureY\n uniforms.u_receiveShadow = this.receiveShadow\n\n // Render the renderable thing wrapped by this instance\n this.renderable.render(gl, uniforms, this.material, programOverride)\n }\n}\n","// ===== billboard.ts =========================================================\n// For drawing 2D billboards, like trees, grass, etc\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4, vec3 } from 'gl-matrix'\nimport * as twgl from 'twgl.js'\n\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/** Billboarding modes, most things will ue NONE */\nexport enum BillboardType {\n SPHERICAL,\n CYLINDRICAL,\n}\n\n/**\n * A simple 2D billboard, like a tree or grass. These are square by default, but can be scaled XY if needed.\n * Both cylindrical and spherical billboards are supported. You must assign material with a texture\n * to be rendered as a sprite on the billboard\n * @see http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/billboards/\n */\nexport class Billboard implements Renderable {\n protected bufferInfo: twgl.BufferInfo\n private programInfo: twgl.ProgramInfo\n public material: Material\n public type: BillboardType = BillboardType.CYLINDRICAL\n\n /** Creates a square billboard */\n constructor(gl: WebGL2RenderingContext, type: BillboardType, material: Material, size: number) {\n this.material = material\n this.type = type\n\n // Create quad vertices\n const verts = twgl.primitives.createXYQuadVertices(size, 0, size / 2)\n\n // Flip Y axis, so texture is not upside down\n for (let i = 1; i < verts.texcoord.length; i += 2) {\n verts.texcoord[i] = 1 - verts.texcoord[i]\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n\n // Use the billboard shader for this renderable\n this.programInfo = ProgramCache.instance.get(ProgramCache.PROG_BILLBOARD)\n }\n\n /**\n * Render is used draw this billboard, this is called from the Instance that wraps\n * this renderable\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet, materialOverride?: Material): void {\n // We ignore programOverride here, as we always use the billboard shader\n const programInfo = this.programInfo\n\n gl.useProgram(programInfo.program)\n\n if (materialOverride === undefined) {\n this.material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n // We're doubling up on work done in the Instance class here, hard to get around this\n const worldView = mat4.multiply(mat4.create(), uniforms.u_view, uniforms.u_world)\n\n // Extract scale from worldView matrix, before we zap it\n const scale = mat4.getScaling(vec3.create(), worldView)\n\n // For CYLINDRICAL billboarding, we need to remove some parts of the worldView matrix\n // See: https://www.geeks3d.com/20140807/billboarding-vertex-shader-glsl/\n worldView[0] = scale[0]\n worldView[1] = 0\n worldView[2] = 0\n worldView[8] = 0\n worldView[9] = 0\n worldView[10] = scale[2]\n\n if (this.type == BillboardType.SPHERICAL) {\n // For SPHERICAL billboarding, we remove some more\n worldView[4] = 0\n worldView[5] = scale[1]\n worldView[6] = 0\n }\n\n // We're doubling up on work again :/\n mat4.multiply(uniforms.u_worldViewProjection, uniforms.u_proj, worldView)\n\n twgl.setBuffersAndAttributes(gl, programInfo, this.bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, this.bufferInfo)\n Stats.drawCallsPerFrame++\n }\n}\n","// ===== material.ts ==========================================================\n// Represents a material, with all the properties from the MTL file\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { RGB } from './tuples.ts'\nimport { MtlMaterial } from '../parsers/mtl-parser.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { TextureCache } from '../core/cache.ts'\n\nexport class Material {\n /**\n * Ambient colour will be multiplied with the ambient light level & colour\n */\n public ambient: RGB\n\n /**\n * Diffuse colour will be multiplied with the diffuse texture\n * @default [1, 1, 1]\n */\n public diffuse: RGB\n\n /**\n * Specular colour will be multiplied with the specular texture\n * @default [0, 0, 0]\n */\n public specular: RGB\n\n /**\n * Emissive colour will be added to the final colour, use for glowing materials\n */\n public emissive: RGB\n\n /**\n * Shininess, for size of specular highlights\n * @default 20\n */\n public shininess: number\n\n /**\n * Opacity, 0.0 to 1.0\n * @default 1.0\n */\n public opacity: number\n\n /**\n * Reflectivity, 0.0 to 1.0\n * @default 0.0\n */\n public reflectivity: number\n\n /**\n * Diffuse texture map\n * @default \"1 pixel white texture\"\n */\n public diffuseTex?: WebGLTexture\n\n /**\n * Specular texture map\n * @default \"1 pixel white texture\"\n */\n public specularTex?: WebGLTexture\n\n /**\n * Normal texture map\n * @default \"1 pixel white texture\"\n */\n public normalTex?: WebGLTexture\n\n /**\n * Don't apply any lighting or shading to this material\n * @default false\n */\n public unshaded: boolean\n\n /**\n * Create a new default material with diffuse white colour, all all default properties\n */\n constructor() {\n this.ambient = [1, 1, 1]\n this.diffuse = [1, 1, 1]\n this.specular = [0, 0, 0]\n this.emissive = [0, 0, 0]\n\n this.shininess = 20\n this.opacity = 1.0\n this.reflectivity = 0.0\n\n this.unshaded = false\n\n // 1 pixel white texture is used for solid colour & flat materials\n // A trick to avoid having multiple shaders for textured & non-textured materials\n this.diffuseTex = TextureCache.defaultWhite\n this.specularTex = TextureCache.defaultWhite\n }\n\n /**\n * Create a new material from a raw MTL material. Users are not expected to call this directly as it is used internally by the OBJ parser\n * @param rawMtl Raw MTL material\n * @param basePath Base path for locating & loading textures in MTL file\n * @param filter Apply texture filtering to textures, default: true\n * @param flipY Flip the Y axis of textures, default: false\n */\n static fromMtl(rawMtl: MtlMaterial, basePath: string, filter = true, flipY = false) {\n const m = new Material()\n\n m.ambient = rawMtl.ka ? rawMtl.ka : [1, 1, 1]\n m.diffuse = rawMtl.kd ? rawMtl.kd : [1, 1, 1]\n m.specular = rawMtl.ks ? rawMtl.ks : [0, 0, 0]\n m.emissive = rawMtl.ke ? rawMtl.ke : [0, 0, 0]\n m.shininess = rawMtl.ns ? rawMtl.ns : 0\n m.opacity = rawMtl.d ? rawMtl.d : 1.0\n\n if (rawMtl.texDiffuse) {\n m.diffuseTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texDiffuse}`, filter, flipY)\n }\n\n if (rawMtl.texSpecular) {\n m.specularTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texSpecular}`, filter, flipY)\n }\n\n if (rawMtl.texNormal) {\n m.normalTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texNormal}`, filter, flipY)\n }\n\n // This is a kludge, a guess; if illum is 3 or more and Ks is set, then we have\n // A reflective material of some kind\n if (rawMtl.illum && rawMtl.illum > 2) {\n m.reflectivity = (m.specular[0] + m.specular[1] + m.specular[2]) / 3\n }\n\n return m\n }\n\n /**\n * Create a basic Material with a solid/flat diffuse colour\n * @param r Red component, 0.0 to 1.0\n * @param g Green component, 0.0 to 1.0\n * @param b Blue component, 0.0 to 1.0\n */\n static createSolidColour(r: number, g: number, b: number) {\n const m = new Material()\n m.diffuse = [r, g, b]\n\n return m\n }\n\n /**\n * Create a new Material with a texture map loaded from a URL/filepath or Buffer\n * @param src URL or filename path of texture image, or ArrayBufferView holding texture\n * @param filter Enable texture filtering and mipmaps (default true)\n * @param flipY Flip the texture vertically (default false)\n */\n static createBasicTexture(src: string | ArrayBufferView, filter = true, flipY = false) {\n const m = new Material()\n\n if (typeof src === 'string') {\n m.diffuseTex = TextureCache.instance.getCreate(src, filter, flipY)\n } else {\n // Invent a unique key for this texture\n const key = `arraybuffer_${TextureCache.size}`\n m.diffuseTex = TextureCache.instance.getCreate(src, filter, flipY, key)\n }\n\n return m\n }\n\n /**\n * Add a specular texture map to existing material, probably created with createBasicTexture\n * @param url\n * @param filter\n */\n addSpecularTexture(url: string, filter = true, flipY = false) {\n this.specularTex = TextureCache.instance.getCreate(url, filter, flipY)\n this.specular = [1, 1, 1]\n this.shininess = 20\n }\n\n /**\n * Add a normal texture map to existing material, probably created with createBasicTexture\n * @param url\n * @param filter\n */\n addNormalTexture(url: string, filter = true, flipY = false) {\n this.normalTex = TextureCache.instance.getCreate(url, filter, flipY)\n }\n\n /** Create a simple diffuse red Material */\n static get RED() {\n return Material.createSolidColour(1.0, 0.0, 0.0)\n }\n\n /** Create a simple diffuse green Material */\n static get GREEN() {\n return Material.createSolidColour(0.0, 1.0, 0.0)\n }\n\n /** Create a simple diffuse blue Material */\n static get BLUE() {\n return Material.createSolidColour(0.0, 0.0, 1.0)\n }\n\n /** Create a simple diffuse white Material */\n static get WHITE() {\n return Material.createSolidColour(1.0, 1.0, 1.0)\n }\n\n /** Create a simple diffuse black Material */\n static get BLACK() {\n return Material.createSolidColour(0.0, 0.0, 0.0)\n }\n\n /** Create a simple diffuse yellow Material */\n static get YELLOW() {\n return Material.createSolidColour(1.0, 1.0, 0.0)\n }\n\n /** Create a simple diffuse magenta Material */\n static get MAGENTA() {\n return Material.createSolidColour(1.0, 0.0, 1.0)\n }\n\n /** Create a simple diffuse cyan Material */\n static get CYAN() {\n return Material.createSolidColour(0.0, 1.0, 1.0)\n }\n\n /**\n * Adds this material to a program, as a set of uniforms\n * @param programInfo ProgramInfo object to update with uniforms\n * @param uniformSuffix Optional suffix to add to uniform names\n */\n apply(programInfo: twgl.ProgramInfo, uniformSuffix = '') {\n const uni = {\n [`u_mat${uniformSuffix}`]: this.uniforms,\n }\n\n twgl.setUniforms(programInfo, uni)\n }\n\n /**\n * Return the base set of uniforms for this material\n * @returns UniformSet object with all material properties\n */\n get uniforms(): UniformSet {\n return {\n ambient: this.ambient,\n diffuse: this.diffuse,\n specular: this.specular,\n emissive: this.emissive,\n shininess: this.shininess,\n opacity: this.opacity,\n reflectivity: this.reflectivity,\n diffuseTex: this.diffuseTex ? this.diffuseTex : null,\n specularTex: this.specularTex ? this.specularTex : null,\n normalTex: this.normalTex ? this.normalTex : null,\n hasNormalTex: this.normalTex ? true : false,\n unshaded: this.unshaded,\n } as UniformSet\n }\n\n /**\n * Clone this material, returns a new material with the same properties\n */\n clone() {\n const m = new Material()\n m.ambient = this.ambient\n m.diffuse = this.diffuse\n m.specular = this.specular\n m.emissive = this.emissive\n m.shininess = this.shininess\n m.opacity = this.opacity\n m.reflectivity = this.reflectivity\n m.diffuseTex = this.diffuseTex\n m.specularTex = this.specularTex\n m.normalTex = this.normalTex\n\n return m\n }\n}\n","// ======== primitive.ts ======================================================\n// Main model class, holds a list of parts, each with a material\n// Models are parsed from OBJ files\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/**\n * A simple primitive 3D object, like a sphere or cube\n */\nexport abstract class Primitive implements Renderable {\n protected bufferInfo: twgl.BufferInfo | undefined\n private programInfo: twgl.ProgramInfo\n public material: Material\n protected triangles: number\n\n constructor() {\n this.material = new Material()\n this.triangles = 0\n this.programInfo = ProgramCache.instance.default\n }\n\n get triangleCount(): number {\n return this.triangles\n }\n\n /**\n * Render is used draw this primitive, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ) {\n if (!this.bufferInfo) return\n\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n if (materialOverride === undefined) {\n this.material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, this.bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n // If cylinder without caps, disable culling\n let disableCulling = false\n\n if (this instanceof PrimitiveCylinder && !this.caps) {\n gl.disable(gl.CULL_FACE)\n disableCulling = true\n }\n\n twgl.drawBufferInfo(gl, this.bufferInfo)\n\n if (disableCulling) {\n gl.enable(gl.CULL_FACE)\n }\n\n Stats.drawCallsPerFrame++\n }\n}\n\n/**\n * A simple sphere primitive with a given radius and subdivisions\n */\nexport class PrimitiveSphere extends Primitive {\n readonly radius: number\n\n /**\n * Create a new sphere primitive\n * @param gl WebGL2RenderingContext\n * @param radius Radius of the sphere\n * @param subdivisionsH Number of horizontal subdivisions\n * @param subdivisionsV Number of vertical subdivisions\n */\n constructor(gl: WebGL2RenderingContext, radius: number, subdivisionsH: number, subdivisionsV: number) {\n super()\n\n this.bufferInfo = twgl.primitives.createSphereBufferInfo(gl, radius, subdivisionsH, subdivisionsV)\n this.triangles += this.bufferInfo.numElements / 3\n this.radius = radius\n }\n}\n\n/**\n * A simple cube primitive with a given size\n */\nexport class PrimitiveCube extends Primitive {\n readonly size: number\n\n /**\n * Create a new cube primitive\n * @param gl WebGL2RenderingContext\n * @param size Size of the cube\n */\n constructor(gl: WebGL2RenderingContext, size: number, tilingFactor?: number) {\n super()\n\n const verts = twgl.primitives.createCubeVertices(size)\n\n // Mutate the texture coords to tile the texture\n if (tilingFactor) {\n for (let i = 0; i < verts.texcoord.length; i++) {\n verts.texcoord[i] = verts.texcoord[i] * tilingFactor\n }\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n\n this.triangles += this.bufferInfo.numElements / 3\n this.size = size\n }\n}\n\n/**\n * A simple plane primitive with a given size, subdivisions & tiling factor\n */\nexport class PrimitivePlane extends Primitive {\n /**\n * Create a new plane primitive\n * @param gl WebGL2RenderingContext\n * @param width Width of the plane\n * @param height Height of the plane\n * @param subdivisionsW Number of horizontal subdivisions\n * @param subdivisionsH Number of vertical subdivisions\n * @param tilingFactor Number of times to tile the texture across the plane\n */\n constructor(\n gl: WebGL2RenderingContext,\n width: number,\n height: number,\n subdivisionsW: number,\n subdivisionsH: number,\n tilingFactor: number,\n ) {\n super()\n\n const verts = twgl.primitives.createPlaneVertices(width, height, subdivisionsW, subdivisionsH)\n\n // Mutate the texture coords to tile the texture\n for (let i = 0; i < verts.texcoord.length; i++) {\n verts.texcoord[i] = verts.texcoord[i] * tilingFactor\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n this.triangles += this.bufferInfo.numElements / 3\n }\n}\n\n/**\n * A simple cylinder primitive with a given radius, height and subdivisions\n */\nexport class PrimitiveCylinder extends Primitive {\n public readonly caps: boolean\n /**\n * Create a new cylinder primitive\n * @param gl WebGL2RenderingContext\n * @param radius Radius of the cylinder\n * @param height Height of the cylinder\n * @param subdivisionsR Subdivisions around the cylinder\n * @param subdivisionsV Subdivisions vertically\n * @param caps Should the cylinder have caps\n */\n constructor(\n gl: WebGL2RenderingContext,\n radius: number,\n height: number,\n subdivisionsR: number,\n subdivisionsV: number,\n caps: boolean,\n ) {\n super()\n\n this.caps = caps\n this.bufferInfo = twgl.primitives.createCylinderBufferInfo(\n gl,\n radius,\n height,\n subdivisionsR,\n subdivisionsV,\n caps,\n caps,\n )\n\n this.triangles += this.bufferInfo.numElements / 3\n }\n}\n","// ===== particles.ts =========================================================\n// Particle system using GPU for particle simulation and VAO instancing\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport log from 'loglevel'\n\nimport updateFS from '../../shaders/particles/update.frag'\nimport updateVS from '../../shaders/particles/update.vert'\nimport renderFS from '../../shaders/particles/render.frag'\nimport renderVS from '../../shaders/particles/render.vert'\n\nimport { Renderable } from './types.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { Stats } from '../core/stats.ts'\nimport { RGBA, XYZ } from '../engine/tuples.ts'\nimport { TextureCache } from '../core/cache.ts'\nimport { mat4, vec3 } from 'gl-matrix'\n\nconst emptyMat = mat4.create()\n\n/**\n * Particle system, uses transform feedback on the GPU to update particles\n * and VAO instancing to render them\n */\nexport class ParticleSystem implements Renderable {\n private progInfoUpdate: twgl.ProgramInfo\n private progInfoRender: twgl.ProgramInfo\n private inputBuffInfo: twgl.BufferInfo\n private outputBuffInfo: twgl.BufferInfo\n private outputVAO: twgl.VertexArrayInfo\n\n /** When enabled, particles will be spawned and emitted */\n public enabled: boolean\n /** Texture to use for particles */\n public texture: WebGLTexture\n /** Emission rate, number of particles per frame */\n public emitRate: number\n /** Min lifetime of particles in seconds */\n public minLifetime: number\n /** Max lifetime of particles in seconds */\n public maxLifetime: number\n /** Gravity vector. Default: [0, -9.81, 0] */\n public gravity: XYZ\n /** Min power (speed) of particles, this is multiplied by the direction vector */\n public minPower: number\n /** Max power (speed) of particles, this is multiplied by the direction vector */\n public maxPower: number\n /** Particles will randomly emit in a direction between this vector and direction2 */\n public direction1: XYZ\n /** Particles will randomly emit in a direction between this vector and direction1 */\n public direction2: XYZ\n /** Particles are spawned in a bounding box, defined by this vector as one corner */\n public emitterBoxMin: XYZ\n /** Particles are spawned in a bounding box, defined by this vector as one corner */\n public emitterBoxMax: XYZ\n /** Speed up or slow down time */\n public timeScale: number\n /** Change colour and alpha as particle reaches it's lifetime. Default: [0,0,0,1] */\n public ageColour: RGBA\n /** Min random size of particles */\n public minSize: number\n /** Max random size of particles */\n public maxSize: number\n /** Min initial random rotation of particles in radians */\n public minInitialRotation: number\n /** Max initial random rotation of particles in radians */\n public maxInitialRotation: number\n /** Min random rotation speed of particles in radians per second */\n public minRotationSpeed: number\n /** Max random rotation speed of particles in radians per second */\n public maxRotationSpeed: number\n /** Duration of particle system in frames, -1 = forever. Default: -1 */\n public duration: number\n /** Acceleration or deceleration multiplier, default 1.0. Applied every frame, so keep values *very* close to 1.0 */\n public acceleration: number\n /** Blend source mode, default: 'SRC_ALPHA', leave alone unless you know what you are doing */\n public blendSource: number\n /** Blend destination mode, default: 'ONE', leave alone unless you know what you are doing */\n public blendDest: number\n /** Colour multiplier pre-applied to particle texture before ageing */\n public preColour: RGBA\n /** Age power curve */\n public agePower: number\n /** Particles transformed fixed to local coordinate space, generally leave as false */\n public localSpace: boolean\n\n /**\n * Create a new particle system\n * @param gl WebGL2 rendering context\n * @param maxParticles Maximum number of particles in the system\n * @param baseSize Size of the particle quad\n */\n constructor(gl: WebGL2RenderingContext, maxParticles: number, baseSize: number) {\n this.emitRate = 300\n this.minLifetime = 2.0\n this.maxLifetime = 6.0\n this.minPower = 25\n this.maxPower = 35\n this.gravity = [0, -9.81, 0]\n this.direction1 = [-0.5, 1, -0.5]\n this.direction2 = [0.5, 1, 0.5]\n this.timeScale = 3.0\n this.ageColour = [0.0, 0.0, 0.0, 1.0]\n this.minSize = 1.0\n this.maxSize = 1.0\n this.minInitialRotation = 0.0\n this.maxInitialRotation = 0.0\n this.minRotationSpeed = 0.0\n this.maxRotationSpeed = 0.0\n this.duration = -1\n this.enabled = true\n this.emitterBoxMin = [0, 0, 0]\n this.emitterBoxMax = [0, 0, 0]\n this.acceleration = 1.0\n this.blendSource = gl.SRC_ALPHA\n this.blendDest = gl.ONE\n this.preColour = [1.0, 1.0, 1.0, 1.0]\n this.agePower = 1.0\n this.localSpace = false\n\n // Create shaders and programs\n this.progInfoUpdate = twgl.createProgramInfo(gl, [updateVS, updateFS], {\n transformFeedbackVaryings: ['tf_position', 'tf_velocity', 'tf_age', 'tf_props'],\n })\n this.progInfoRender = twgl.createProgramInfo(gl, [renderVS, renderFS])\n\n // Create initial buffers, note these are for ALL particles regardless of emission rate\n // These are all updated in the shader\n const positions = new Float32Array(maxParticles * 4)\n const velocities = new Float32Array(maxParticles * 3)\n const ages = new Float32Array(maxParticles * 2)\n const props = new Float32Array(maxParticles * 4)\n const seeds = new Float32Array(maxParticles)\n for (let i = 0; i < maxParticles; i++) {\n positions[i * 3] = 0\n positions[i * 3 + 1] = 0\n positions[i * 3 + 2] = 0\n positions[i * 3 + 3] = 0 // Rotation\n\n velocities[i * 3] = 0\n velocities[i * 3 + 1] = 0\n velocities[i * 3 + 2] = 0\n\n ages[i * 2] = 0 // Age\n // Lifetime, initial random value to stop \"bursting\"\n ages[i * 2 + 1] = Math.random() * 3\n\n props[i * 4] = 1.0 // Size\n props[i * 4 + 1] = 0 // Rotation speed\n props[i * 4 + 2] = 0 // Unused\n props[i * 4 + 3] = 0 // Unused\n\n seeds[i] = Math.random()\n }\n\n // Create input buffer used by transform feedback & update shader\n // Note the divisor of 0, this means the data is static and will not change\n this.inputBuffInfo = twgl.createBufferInfoFromArrays(gl, {\n position: { numComponents: 4, data: positions, divisor: 0 },\n velocity: { numComponents: 3, data: velocities, divisor: 0 },\n age: { numComponents: 2, data: ages, divisor: 0 },\n props: { numComponents: 4, data: props, divisor: 0 },\n seed: { numComponents: 1, data: seeds, divisor: 0 },\n })\n\n // Create output buffer used by transform feedback & update shader\n // Note the divisor of 1, this means the data is dynamic and will change\n const quadVerts = twgl.primitives.createXYQuadVertices(baseSize)\n // Mutate/merge the quadVerts object to add our custom attributes\n Object.assign(quadVerts, {\n tf_position: { numComponents: 4, data: positions, divisor: 1 },\n tf_velocity: { numComponents: 3, data: velocities, divisor: 1 },\n tf_age: { numComponents: 2, data: ages, divisor: 1 },\n tf_props: { numComponents: 4, data: props, divisor: 1 },\n })\n // Now create the buffer and VAO\n this.outputBuffInfo = twgl.createBufferInfoFromArrays(gl, quadVerts)\n\n this.outputVAO = twgl.createVertexArrayInfo(gl, this.progInfoRender, this.outputBuffInfo)\n\n // Create texture for particle\n this.texture = TextureCache.defaultWhite\n\n log.info('✨ Created particle system with', maxParticles, 'particles')\n }\n\n /**\n * Render the particle system and implement the renderable interface\n * @param gl WebGL2 rendering context\n * @param uniforms Uniforms to pass to the shaders\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet) {\n if (this.duration == 0) {\n this.enabled = false\n }\n if (this.duration > 0) {\n this.duration--\n }\n\n gl.blendFunc(this.blendSource, this.blendDest)\n this.updateParticles(gl, uniforms.u_world as mat4)\n this.renderParticles(gl, uniforms)\n\n // Swap the buffers between input & output, kinda weird and ugly but it works!\n for (const attribName in this.inputBuffInfo.attribs) {\n const tempBuff = this.inputBuffInfo.attribs[attribName].buffer\n\n if (this.outputBuffInfo && this.outputBuffInfo.attribs && this.outputBuffInfo.attribs[`tf_${attribName}`]) {\n this.inputBuffInfo.attribs[attribName].buffer = this.outputBuffInfo.attribs[`tf_${attribName}`].buffer\n this.outputBuffInfo.attribs[`tf_${attribName}`].buffer = tempBuff\n }\n }\n }\n\n /**\n * Update the particles positions and velocities\n */\n private updateParticles(gl: WebGL2RenderingContext, worldTrans: mat4) {\n const tf = twgl.createTransformFeedback(gl, this.progInfoUpdate, this.outputBuffInfo)\n\n const pos = [0, 0, 0] as vec3\n if (!this.localSpace) {\n vec3.transformMat4(pos, pos, worldTrans)\n }\n\n gl.enable(gl.RASTERIZER_DISCARD)\n gl.useProgram(this.progInfoUpdate.program)\n\n twgl.setBuffersAndAttributes(gl, this.progInfoUpdate, this.inputBuffInfo)\n gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf)\n\n gl.beginTransformFeedback(gl.POINTS)\n\n twgl.setUniforms(this.progInfoUpdate, {\n u_time: Stats.totalTime,\n u_deltaTime: Stats.deltaTime * this.timeScale,\n u_randTex: TextureCache.defaultRand,\n\n // NOTE: ULTRA IMPORTANT! Without this the rand function in the shader will not work\n u_maxInstances: this.inputBuffInfo.numElements,\n\n u_enabled: this.enabled,\n u_lifetimeMinMax: [this.minLifetime, this.maxLifetime],\n u_gravity: this.gravity,\n u_powerMinMax: [this.minPower, this.maxPower],\n u_direction1: this.direction1,\n u_direction2: this.direction2,\n u_timeScale: this.timeScale,\n u_sizeMinMax: [this.minSize, this.maxSize],\n u_initialRotationMinMax: [this.minInitialRotation, this.maxInitialRotation],\n u_rotationSpeedMinMax: [this.minRotationSpeed, this.maxRotationSpeed],\n u_emitterBoxMin: this.emitterBoxMin,\n u_emitterBoxMax: this.emitterBoxMax,\n u_accel: this.acceleration,\n u_posOffset: pos,\n })\n\n twgl.drawBufferInfo(gl, this.inputBuffInfo, gl.POINTS, this.emitRate)\n\n gl.endTransformFeedback()\n gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null)\n gl.disable(gl.RASTERIZER_DISCARD)\n }\n\n /**\n * Render the particles to the world\n */\n private renderParticles(gl: WebGL2RenderingContext, uniforms: UniformSet) {\n gl.useProgram(this.progInfoRender.program)\n\n const particleUniforms = {\n ...uniforms,\n u_world: this.localSpace ? uniforms.u_world : emptyMat,\n u_texture: this.texture,\n u_ageColour: this.ageColour,\n u_preColour: this.preColour,\n u_agePower: this.agePower,\n }\n\n twgl.setUniforms(this.progInfoRender, particleUniforms)\n\n const objList = [\n {\n programInfo: this.progInfoRender,\n vertexArrayInfo: this.outputVAO,\n uniforms: particleUniforms,\n instanceCount: this.emitRate,\n },\n ]\n\n twgl.setBuffersAndAttributes(gl, this.progInfoRender, this.outputVAO)\n twgl.drawObjectList(gl, objList)\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Particle update fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// Does nothing, just here to make the WebGL compiler happy!\nvoid main() {}\n","#version 300 es\n\n// ============================================================================\n// Particle update vertex shader, for on GPU particle simulation\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\nin vec3 velocity;\nin vec2 age;\nin vec4 props;\nin float seed;\n\nuniform float u_deltaTime;\nuniform sampler2D u_randTex;\nuniform float u_maxInstances;\nuniform vec2 u_lifetimeMinMax;\nuniform vec2 u_powerMinMax;\nuniform vec3 u_gravity;\nuniform vec3 u_direction1;\nuniform vec3 u_direction2;\nuniform float u_timeScale;\nuniform vec2 u_sizeMinMax;\nuniform vec2 u_initialRotationMinMax;\nuniform vec2 u_rotationSpeedMinMax;\nuniform bool u_enabled;\nuniform vec3 u_emitterBoxMin;\nuniform vec3 u_emitterBoxMax;\nuniform float u_accel;\nuniform vec3 u_posOffset;\n\nout vec4 tf_position;\nout vec3 tf_velocity;\nout vec2 tf_age;\nout vec4 tf_props;\n\nvec4 rand(float offset) {\n float uv = float(gl_VertexID) / u_maxInstances + offset;\n return texture(u_randTex, vec2(uv)).rgba;\n}\n\nfloat randBetween(float min, float max, float offset) {\n vec4 r = rand(offset);\n return min + (max - min) * r.w;\n}\n\n// NOTES: TF varyings & packing\n// * position[0,1,2] = current position\n// * position[3] = rotation\n// * age[0] = current age\n// * age[1] = lifetime\n// * props[0] = size\n// * props[1] = rotation speed\n\nvoid main() {\n float t = u_deltaTime;\n float new_age = age[0] + t;\n\n float rot = position[3] + props[1] * t;\n\n tf_velocity = velocity * u_accel + u_gravity * t;\n tf_position = vec4(position.xyz + tf_velocity * t, rot);\n tf_age[0] = new_age;\n tf_age[1] = age[1];\n tf_props = props;\n\n // Dead particles are respawned\n if (new_age > age[1] && u_enabled) {\n vec4 r = rand(seed);\n\n tf_age[0] = 0.0;\n tf_position[0] = randBetween(u_emitterBoxMin.x, u_emitterBoxMax.x, r.x) + u_posOffset.x;\n tf_position[1] = randBetween(u_emitterBoxMin.y, u_emitterBoxMax.y, r.y) + u_posOffset.y;\n tf_position[2] = randBetween(u_emitterBoxMin.z, u_emitterBoxMax.z, r.z) + u_posOffset.z;\n tf_position[3] = randBetween(u_initialRotationMinMax.x, u_initialRotationMinMax.y, seed);\n\n float power = randBetween(u_powerMinMax.x, u_powerMinMax.y, 0.0);\n\n tf_velocity = vec3(\n randBetween(u_direction1.x, u_direction2.x, r.x + position.x) * power,\n randBetween(u_direction1.y, u_direction2.y, r.y + position.y) * power,\n randBetween(u_direction1.z, u_direction2.z, r.z + position.z) * power\n );\n\n tf_age[1] = randBetween(u_lifetimeMinMax.x, u_lifetimeMinMax.y, seed + position.x);\n tf_props[0] = randBetween(u_sizeMinMax.x, u_sizeMinMax.y, seed + position.y);\n tf_props[1] = randBetween(u_rotationSpeedMinMax.x, u_rotationSpeedMinMax.y, seed);\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Particle render fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec2 v_texcoord;\nin float v_ageNorm;\n\nuniform sampler2D u_texture;\nuniform vec4 u_ageColour;\nuniform vec4 u_preColour;\n\nout vec4 outColor;\n\nvoid main() {\n vec4 tex = texture(u_texture, v_texcoord);\n tex.r *= u_preColour.r;\n tex.g *= u_preColour.g;\n tex.b *= u_preColour.b;\n tex.a *= u_preColour.a;\n\n tex.a *= 1.0 - v_ageNorm * u_ageColour.a;\n tex.r *= 1.0 - v_ageNorm * u_ageColour.r;\n tex.g *= 1.0 - v_ageNorm * u_ageColour.g;\n tex.b *= 1.0 - v_ageNorm * u_ageColour.b;\n\n outColor = tex;\n}\n","#version 300 es\n\n// ============================================================================\n// Particle render vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position; // Vertex positions of the particle quad\nin vec2 texcoord;\nin vec4 tf_position; // Position of the particle\nin vec2 tf_age;\nin vec4 tf_props;\n\nuniform mat4 u_view;\nuniform mat4 u_proj;\nuniform mat4 u_world;\nuniform float u_agePower;\n\nout vec2 v_texcoord;\nout vec3 v_position;\nout float v_ageNorm;\n\nvoid main() {\n vec3 vert_pos = position.xyz;\n v_ageNorm = clamp(tf_age[0] / tf_age[1], 0.0, 1.0);\n v_ageNorm = pow(v_ageNorm, u_agePower);\n\n // Rotate by tf_position[3] (rotation)\n float s = sin(tf_position[3]);\n float c = cos(tf_position[3]);\n mat2 rot = mat2(c, -s, s, c);\n vert_pos.xy = rot * position.xy;\n\n // Scale by tf_props[0] (size)\n vert_pos = vert_pos.xyz * tf_props[0];\n\n // Move to the world at the particle position\n vec4 world_pos = u_world * vec4(tf_position.xyz, 1.0);\n vec4 view_pos = u_view * world_pos;\n\n // Billboarding magic\n gl_Position = u_proj * (view_pos + vec4(vert_pos.xy, 0.0, 0.0));\n\n v_position = world_pos.xyz;\n v_texcoord = texcoord;\n}\n","// ===== model.ts =============================================================\n// Main model class, holds a list of parts, each with a material\n// Models are parsed from OBJ files\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport log from 'loglevel'\n\nimport { Material } from '../engine/material.ts'\nimport { parseMTL } from '../parsers/mtl-parser.ts'\nimport { parseOBJ } from '../parsers/obj-parser.ts'\nimport { fetchFile } from '../core/files.ts'\nimport { getGl, UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/**\n * Holds a 3D model, as a list of parts, each with a material\n * Plus map of named materials\n */\nexport class Model implements Renderable {\n private programInfo: twgl.ProgramInfo\n private readonly parts = [] as ModelPart[]\n private readonly materials = {} as Record\n private triangles: number\n private _boundingBox: number[]\n\n /** Name of the model, usually the filename without the extension */\n public readonly name: string\n\n /**\n * Constructor is private, use static `parse()` method instead\n */\n private constructor(name: string) {\n this.name = name\n this.triangles = 0\n this.programInfo = ProgramCache.instance.default\n this._boundingBox = [\n Number.MAX_VALUE,\n Number.MAX_VALUE,\n Number.MAX_VALUE,\n Number.MIN_VALUE,\n Number.MIN_VALUE,\n Number.MIN_VALUE,\n ]\n }\n\n /**\n * Render is used draw this model, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ): void {\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n // Render each part of the model\n for (const part of this.parts) {\n const bufferInfo = part.bufferInfo\n\n if (materialOverride === undefined) {\n // Get the named material for this part\n let material = this.materials[part.materialName]\n\n // Fall back to default material if not found\n if (!material) {\n material = this.materials.__default\n }\n\n material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, bufferInfo)\n Stats.drawCallsPerFrame++\n }\n }\n\n /** Simple getter for the number of triangles in the model */\n get triangleCount(): number {\n return this.triangles\n }\n\n /**\n * Parse an OBJ file & MTL material libraries, returns a new Model\n * @param {string} path - The path to the OBJ file\n * @param {string} objFilename - The name of the OBJ file\n * @param {boolean} filterTextures - Apply texture filtering to textures, default: true\n * @param {boolean} flipTextureY - Flip the Y axis of textures as they are loaded, default: false\n * @param {boolean} flipUV - Flip the UV coords of the model in the vertex/mesh data, default: true\n */\n static async parse(path = '.', objFilename: string, filterTextures = true, flipTextureY = false, flipUV = false) {\n const startTime = performance.now()\n\n // Create a new model with the name of the file\n const name = objFilename.split('.')[0]\n const model = new Model(name)\n\n // Load the OBJ file from URL\n let objFile: string\n try {\n objFile = await fetchFile(`${path}/${objFilename}`)\n } catch (err) {\n throw new Error(`💥 Unable to load file '${path}/${objFilename}'`)\n }\n\n // Try to parse the OBJ file\n const objData = parseOBJ(objFile, flipUV)\n\n if (!objData.geometries || objData.geometries.length === 0) {\n throw new Error(`💥 Error parsing '${objFilename}', might not be a OBJ file`)\n }\n\n // We assume that the OBJ file has a SINGLE material library\n // This is a good assumption for nearly all files I've seen\n if (objData.matLibNames && objData.matLibNames.length > 0) {\n try {\n const mtlFile = await fetchFile(`${path}/${objData.matLibNames[0]}`)\n const materialsRawList = parseMTL(mtlFile)\n\n for (const [matName, matRaw] of materialsRawList) {\n model.materials[matName] = Material.fromMtl(matRaw, path, filterTextures, flipTextureY)\n }\n } catch (err) {\n log.warn(`💥 Unable to load material library ${objData.matLibNames[0]}`)\n }\n }\n\n // Fall back default material\n model.materials.__default = new Material()\n model.materials.__default.diffuse = [0.1, 0.6, 0.9]\n\n // This really should already been memoized by the context at this point\n const gl = getGl()\n\n if (!gl) {\n throw new Error('💥 Unable to get WebGL context')\n }\n\n for (const g of objData.geometries) {\n // Calculate bounding box\n for (let i = 0; i < g.data.position.length; i += 3) {\n const x = g.data.position[i]\n const y = g.data.position[i + 1]\n const z = g.data.position[i + 2]\n if (x < model._boundingBox[0]) model._boundingBox[0] = x\n if (y < model._boundingBox[1]) model._boundingBox[1] = y\n if (z < model._boundingBox[2]) model._boundingBox[2] = z\n if (x > model._boundingBox[3]) model._boundingBox[3] = x\n if (y > model._boundingBox[4]) model._boundingBox[4] = y\n if (z > model._boundingBox[5]) model._boundingBox[5] = z\n }\n\n log.info(`♟️ Model '${objFilename}' part '${g.material}'`)\n\n // TODO: One day add tangent generation\n const bufferInfo = twgl.createBufferInfoFromArrays(gl, g.data)\n model.parts.push(new ModelPart(bufferInfo, g.material))\n }\n\n log.debug(\n `♟️ Model '${objFilename}' loaded with ${model.parts.length} parts, ${\n Object.keys(model.materials).length\n } materials in ${((performance.now() - startTime) / 1000).toFixed(2)}s`,\n )\n\n model.triangles = objData.triangles\n return model\n }\n\n /**\n * Get list of all material names in this model used by all parts\n * @returns {string[]} - List of material names\n */\n get materialNames(): string[] {\n return Object.keys(this.materials)\n }\n\n /**\n * Get number of parts in this model\n */\n get partsCount(): number {\n return this.parts.length\n }\n\n /**\n * Get list of parts in this model, names are the material names\n * @returns {string[]} - List of part material names\n */\n get partList(): string[] {\n return this.parts.map((p) => p.materialName)\n }\n\n /**\n * Can modify & override an existing named material\n * @param {string} name - Name of the material to modify\n * @param {Material} material - New material to use\n */\n setNamedMaterial(name: string, material: Material): void {\n this.materials[name] = material\n }\n\n /**\n * Get a named material\n * @param {string} name - Name of the material to get\n */\n getNamedMaterial(name: string): Material {\n return this.materials[name]\n }\n\n public get boundingBox(): number[] {\n return this._boundingBox\n }\n}\n\n/**\n * Holds part of a model, as the WebGL buffers needed to render it\n * Plus the material name associated with this part\n */\nexport class ModelPart {\n public readonly bufferInfo: twgl.BufferInfo\n public readonly materialName: string\n\n /**\n * @param {twgl.BufferInfo} bufferInfo - WebGL buffer info for this model part\n * @param {string} materialName - Name of the material associated with this part\n */\n constructor(bufferInfo: twgl.BufferInfo, materialName: string) {\n this.bufferInfo = bufferInfo\n this.materialName = materialName\n }\n}\n","// ===== mtl-parser.mjs ==========================================================\n// A simple MTL parser\n// Taken from https://webglfundamentals.org/webgl/lessons/webgl-load-obj-w-mtl.html\n// Ben Coleman, 2023\n// ===============================================================================\n\n/**\n * A \"raw\" material fetched from the MTL parser, don't use this directly\n */\nexport type MtlMaterial = {\n illum?: number\n\n ns?: number\n d?: number\n\n ka?: [number, number, number]\n kd?: [number, number, number]\n ks?: [number, number, number]\n ke?: [number, number, number]\n\n texDiffuse?: string\n texSpecular?: string\n texNormal?: string\n}\n\n/**\n * Parse an MTL file returning a map of materials.\n * The returned {@link typescript!MtlMaterial} should be passed to new Material() to create a material\n * @param {string} mtlFile - The MTL file as a string\n * @returns {Map} - A map of materials\n */\nexport function parseMTL(mtlFile: string): Map {\n const materials = new Map()\n let material = {} as MtlMaterial\n\n const keywords = {\n newmtl(_: string[], unparsedArgs: string) {\n material = {} as MtlMaterial\n materials.set(unparsedArgs, material)\n },\n\n Ns(parts: string[]) {\n material.ns = parseFloat(parts[0])\n },\n Ka(parts: string[]) {\n material.ka = <[number, number, number]>parts.map(parseFloat)\n },\n Kd(parts: string[]) {\n material.kd = <[number, number, number]>parts.map(parseFloat)\n },\n Ks(parts: string[]) {\n material.ks = <[number, number, number]>parts.map(parseFloat)\n },\n // This is a non-standard addition, but semi-official\n Ke(parts: string[]) {\n material.ke = <[number, number, number]>parts.map(parseFloat)\n },\n Ni() {\n // Not used\n // Material.ni = parseFloat(parts[0])\n },\n d(parts: string[]) {\n material.d = parseFloat(parts[0])\n },\n illum(parts: string[]) {\n material.illum = parseInt(parts[0])\n },\n map_Kd(_: string[], unparsedArgs: string) {\n material.texDiffuse = unparsedArgs\n },\n map_Ks(_: string[], unparsedArgs: string) {\n material.texSpecular = unparsedArgs\n },\n map_bump(_: string[], unparsedArgs: string) {\n material.texNormal = unparsedArgs\n },\n map_Bump(_: string[], unparsedArgs: string) {\n material.texNormal = unparsedArgs\n },\n } as Record void>\n\n const keywordRE = /(\\w*)(?: )*(.*)/\n const lines = mtlFile.split('\\n')\n\n for (let lineNo = 0; lineNo < lines.length; ++lineNo) {\n const line = lines[lineNo].trim()\n if (line === '' || line.startsWith('#')) {\n continue\n }\n\n const m = keywordRE.exec(line)\n if (!m) {\n continue\n }\n\n const [, keyword, unparsedArgs] = m\n const parts = line.split(/\\s+/).slice(1)\n\n const handler = keywords[keyword]\n if (!handler) {\n // Console.warn('unhandled keyword:', keyword)\n continue\n }\n\n handler(parts, unparsedArgs)\n }\n\n return materials\n}\n","// ===== obj-parser.mjs ==========================================================\n// A simple OBJ parser, works well, but FAR from comprehensive\n// Taken from https://webglfundamentals.org/webgl/lessons/webgl-obj-loader.html\n// Ben Coleman, 2023\n// ===============================================================================\n\nconst keywordRE = /(\\w*)(?: )*(.*)/\n\n/**\n * ParseResult is the result of parsing an OBJ file\n */\nexport type ParseResult = {\n /** List of material libs (MTL files) */\n matLibNames: string[]\n\n /** List of geometries, each with a material name and vertex data */\n geometries: Geometry[]\n\n /** Total number of triangles in the OBJ file */\n triangles: number\n}\n\n/**\n * Each OBJ file is made up of a list of geometries, each with a material name.\n * These can be thought of as parts of the overall model.\n */\nexport type Geometry = {\n /** Name of the material for this geometry part */\n material: string\n\n /** Vertex data for this geometry part, ready for turning into an BufferInfo in twgl.js */\n data: {\n position: number[]\n texcoord?: number[]\n normal: number[]\n tangent?: number[]\n }\n}\n\n/**\n * Parse an OBJ file returning a list of geometries and materials libs\n * @param {string} objFile - The OBJ file as a string\n * @param {boolean} flipUV - Flip the V texcoord axis, for OpenGL\n */\nexport function parseOBJ(objFile: string, flipUV: boolean) {\n const lines = objFile.split('\\n')\n\n const objPositions = [[0, 0, 0]]\n const objTexcoords = [[0, 0]]\n const objNormals = [[0, 0, 0]]\n\n // Same order as `f` indices\n const objVertexData = [objPositions, objTexcoords, objNormals]\n\n let triangles = 0\n\n // Same order as `f` indices\n let webglVertexData = [\n [], // Position\n [], // Texcoord\n [], // Normal\n ] as number[][]\n\n const geometries = Array()\n let geometry = {} as Geometry\n let material = '__default'\n const materialLibs = Array()\n\n const keywords = {\n v(parts: string[]) {\n objPositions.push(parts.map(parseFloat))\n },\n\n vn(parts: string[]) {\n objNormals.push(parts.map(parseFloat))\n },\n\n vt(parts: string[]) {\n // Only 2D texcoords supported, so ignore the 3rd if present\n // Also handle UV flip in the V direction (Y axis) for OpenGL\n if (flipUV) {\n objTexcoords.push([parseFloat(parts[0]), 1.0 - parseFloat(parts[1])])\n } else {\n objTexcoords.push([parseFloat(parts[0]), parseFloat(parts[1])])\n }\n },\n\n f(parts: string[]) {\n triangles++\n setGeometry()\n const numTriangles = parts.length - 2\n for (let tri = 0; tri < numTriangles; ++tri) {\n addVertex(parts[0])\n addVertex(parts[tri + 1])\n addVertex(parts[tri + 2])\n }\n },\n\n usemtl(_: string[], unparsedArgs: string) {\n material = unparsedArgs\n newGeometry()\n },\n\n mtllib(_: string[], unparsedArgs: string) {\n materialLibs.push(unparsedArgs)\n },\n\n // Not used, but suppress warnings\n s() {\n return\n },\n\n o() {\n return\n },\n\n g() {\n return\n },\n\n l() {\n return\n },\n } as Record void>\n\n /**\n * Updates webglVertexData per vertex\n * @param {string} vert - String in the form of \"v/vt/vn\" as per OBJ spec\n */\n function addVertex(vert: string) {\n const ptn = vert.split('/')\n\n ptn.forEach((objIndexStr, i) => {\n if (!objIndexStr) {\n return\n }\n\n const objIndex = parseInt(objIndexStr)\n const index = objIndex + (objIndex >= 0 ? 0 : objVertexData[i].length)\n\n webglVertexData[i].push(...objVertexData[i][index])\n })\n }\n\n /**\n * Start a new geometry object\n */\n function newGeometry() {\n // If there is an existing geometry and it's not empty then start a new one.\n if (geometry.material) {\n geometry = {} as Geometry\n }\n }\n\n /**\n * Set the geometry for the current material/part\n */\n function setGeometry() {\n if (!geometry.material) {\n const position = [] as number[]\n const texcoord = [] as number[]\n const normal = [] as number[]\n\n webglVertexData = [position, texcoord, normal]\n\n /** @type {Geometry} */\n geometry = {\n material,\n data: {\n position,\n texcoord,\n normal,\n },\n }\n\n geometries.push(geometry)\n }\n }\n\n // Parse the OBJ file line by line\n for (let lineNo = 0; lineNo < lines.length; ++lineNo) {\n const line = lines[lineNo].trim()\n if (line === '' || line.startsWith('#')) {\n continue\n }\n\n const m = keywordRE.exec(line)\n if (!m) {\n continue\n }\n\n const [, keyword, unparsedArgs] = m\n const parts = line.split(/\\s+/).slice(1)\n\n const handler = keywords[keyword]\n if (!handler) {\n console.warn('unhandled keyword:', keyword, 'at line', lineNo + 1)\n continue\n }\n\n handler(parts, unparsedArgs)\n }\n\n // FIX: For those OBJ files that don't have texcoord data\n for (const g of geometries) {\n if (g.data.texcoord && g.data.texcoord.length <= 0) {\n delete g.data.texcoord\n }\n }\n\n // Return the list of geometries and material libs, plus triangle count\n return {\n matLibNames: materialLibs,\n geometries,\n triangles,\n } as ParseResult\n}\n","// ===== files.ts =============================================================\n// File loading utilities\n// Ben Coleman, 2023\n// ============================================================================\n\ntype Shader = {\n vertex: string\n fragment: string\n}\n\n/**\n * Fetch a file from the server\n *\n * @param {string} path - URL path to file\n * @returns {Promise} File contents as a string\n */\nexport async function fetchFile(filePath: string) {\n const resp = await fetch(filePath)\n\n if (!resp.ok) {\n throw new Error(`💥 File fetch failed: ${resp.statusText}`)\n }\n\n const text = await resp.text()\n return text\n}\n\n/**\n * Fetch a pair of shaders from the server\n *\n * @param {string} vertPath - URL path to vertex shader\n * @param {string} fragPath - URL path to fragment shader\n * @returns {Promise} Pair of shaders as strings\n */\nexport async function fetchShaders(vertPath: string, fragPath: string) {\n const vsResp = await fetch(vertPath)\n const fsResp = await fetch(fragPath)\n\n if (!vsResp.ok || !fsResp.ok) {\n throw new Error(`💥 Fetch failed - vertex: ${vsResp.statusText}, fragment: ${fsResp.statusText}`)\n }\n\n const vsText = await vsResp.text()\n const fsText = await fsResp.text()\n\n return { vertex: vsText, fragment: fsText } as Shader\n}\n","// ===== hud.ts =========================================================\n// A HTML based HUD for the game, this is a simple div for now\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { Stats } from './stats.ts'\nimport { version } from '../../package.json'\nimport { Camera } from '../engine/camera.ts'\n\nexport class HUD {\n private hud: HTMLDivElement\n private canvas: HTMLCanvasElement\n private debugDiv: HTMLDivElement\n private loadingDiv: HTMLDivElement\n public debug = false\n\n constructor(canvas: HTMLCanvasElement) {\n const parent = canvas.parentElement\n if (!parent) throw new Error('💥 Canvas must have a parent element')\n\n this.canvas = canvas\n\n this.hud = document.createElement('div')\n this.hud.classList.add('gsots3d-hud')\n this.hud.style.pointerEvents = 'none'\n\n this.updateWithCanvas = this.updateWithCanvas.bind(this)\n window.addEventListener('resize', this.updateWithCanvas)\n window.addEventListener('load', this.updateWithCanvas)\n\n this.debugDiv = document.createElement('div')\n this.debugDiv.classList.add('gsots3d-debug')\n this.debugDiv.style.fontSize = 'min(1.5vw, 20px)'\n this.debugDiv.style.fontFamily = 'monospace'\n this.debugDiv.style.color = 'white'\n this.debugDiv.style.padding = '1vw'\n this.addHUDItem(this.debugDiv)\n\n this.loadingDiv = document.createElement('div')\n this.loadingDiv.classList.add('gsots3d-loading')\n this.loadingDiv.innerHTML = `💾 Loading...

GSOTS-3D v${version}
`\n this.loadingDiv.style.font = 'normal 3vw sans-serif'\n this.loadingDiv.style.color = '#ccc'\n this.loadingDiv.style.position = 'absolute'\n this.loadingDiv.style.top = '50%'\n this.loadingDiv.style.left = '50%'\n this.loadingDiv.style.textAlign = 'center'\n this.loadingDiv.style.transform = 'translate(-50%, -50%)'\n this.addHUDItem(this.loadingDiv)\n\n parent.appendChild(this.hud)\n this.updateWithCanvas()\n }\n\n /**\n * Update the HUD position and size to match the canvas\n */\n private updateWithCanvas() {\n const canvasStyles = window.getComputedStyle(this.canvas, null)\n this.hud.style.position = canvasStyles.getPropertyValue('position')\n this.hud.style.top = canvasStyles.getPropertyValue('top')\n this.hud.style.left = canvasStyles.getPropertyValue('left')\n this.hud.style.width = canvasStyles.getPropertyValue('width')\n this.hud.style.height = canvasStyles.getPropertyValue('height')\n this.hud.style.transform = canvasStyles.getPropertyValue('transform')\n }\n\n /**\n * Add a HTML element to the HUD\n * @param item HTML element to add\n */\n addHUDItem(item: HTMLElement) {\n this.hud.appendChild(item)\n }\n\n /**\n * Render the HUD, called once per frame\n */\n render(debug = false, camera: Camera) {\n // Draw the debug HUD\n if (debug) {\n this.debugDiv.innerHTML = `\n GSOTS-3D v${version}

\n Camera: ${camera.toString()}
\n Instances: ${Stats.instances}
\n Draw calls: ${Stats.drawCallsPerFrame}
\n Triangles: ${Stats.triangles}
\n Render: FPS: ${Stats.FPS} / ${Stats.totalTimeRound}s
\n `\n } else {\n this.debugDiv.innerHTML = ''\n }\n }\n\n /**\n * Hide the loading message, this is called by the engine\n */\n hideLoading() {\n this.loadingDiv.style.display = 'none'\n }\n}\n","// ===== post-effects.ts ===============================================================================\n// Full screen effects and post processing\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport * as log from 'loglevel'\nimport * as twgl from 'twgl.js'\nimport { UniformSet } from '../core/gl.ts'\nimport { TextureCache } from '../core/cache.ts'\nimport { Stats } from '../core/stats.ts'\nimport { RGB } from './tuples.ts'\n\n/**\n * PostEffects class, used to render full screen effects via post processing\n * This is a wrapper around a shader program that renders from a framebuffer to the screen\n */\nexport class PostEffects {\n private _frameBuff: twgl.FramebufferInfo\n private buffInfo: twgl.BufferInfo\n private uniforms: UniformSet\n private progInfo: twgl.ProgramInfo\n\n constructor(gl: WebGL2RenderingContext, shaderCode: string) {\n // Create a framebuffer to hold image for this post effects to process\n this._frameBuff = twgl.createFramebufferInfo(gl, undefined, gl.canvas.width, gl.canvas.height)\n\n // Simple 2-triangle quad for a shader to render to the whole screen\n this.buffInfo = twgl.createBufferInfoFromArrays(gl, {\n position: {\n numComponents: 2,\n data: [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1],\n },\n texcoord: {\n numComponents: 2,\n data: [0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],\n },\n })\n\n this.uniforms = {\n image: this._frameBuff.attachments[0],\n width: gl.canvas.width,\n height: gl.canvas.height,\n time: Stats.totalTime,\n delta: Stats.deltaTime,\n randTex: TextureCache.defaultRand,\n }\n\n // Note. We don't follow the naming convention from the other shaders here\n // to allow the user to write their own shaders and keep them simple\n const vertShader = `#version 300 es\n precision highp float;\n in vec4 position;\n in vec2 texcoord;\n out vec2 pos;\n void main() {\n pos = texcoord;\n gl_Position = position;\n }`\n\n const fragShader = `#version 300 es\n precision highp float;\n in vec2 pos;\n uniform sampler2D image;\n uniform float width;\n uniform float height;\n uniform float time;\n uniform float frame;\n uniform float delta;\n uniform sampler2D randTex;\n out vec4 pixel;\n \n vec4 randRGBA(float offset) {\n vec2 uv = vec2(pos.x + offset, pos.y + offset + 0.1);\n return texture(randTex, vec2(uv)).rgba;\n }\n \n float randPhase(vec2 co, float speed)\n {\n float a = 12.9898;\n float b = 78.233;\n float c = 43758.5453;\n float dt = dot(co.xy, vec2(a,b));\n float sn = mod(dt, 3.14159);\n\n return fract((sin(sn) * c) + time * speed);\n }\n\n float randF(vec2 st) {\n return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);\n } \n\n ${shaderCode}\n `\n\n log.debug(`🥽 PostEffects creating shader program\\n${fragShader}`)\n this.progInfo = twgl.createProgramInfo(gl, [vertShader, fragShader])\n }\n\n /**\n * Render the post effects to the screen, called last in the render loop\n * @param gl WebGL2RenderingContext\n */\n renderToScreen(gl: WebGL2RenderingContext) {\n gl.useProgram(this.progInfo.program)\n\n this.uniforms.time = Stats.totalTime\n this.uniforms.delta = Stats.deltaTime\n this.uniforms.frame = Stats.frameCount\n\n twgl.setUniforms(this.progInfo, this.uniforms)\n twgl.setBuffersAndAttributes(gl, this.progInfo, this.buffInfo)\n\n twgl.bindFramebufferInfo(gl, null)\n twgl.drawBufferInfo(gl, this.buffInfo)\n }\n\n /**\n * Get the framebuffer that this post effects is rendering to\n * Used to update the image that the post effects will update\n */\n get frameBuffer() {\n return this._frameBuff\n }\n\n /**\n * Create a simple scanlines effect with noise and flickering\n * Taken from https://www.shadertoy.com/view/3dBSRD\n * @param gl WebGL2RenderingContext\n * @param density Density of scanlines, 0.0 - 1.0\n * @param opacity Opacity of scanlines, 0.0 - 1.0\n * @param noise Amount of noise, 0.0 - 1.0\n * @param flicker Amount of flickering, 0.0 - 1.0\n */\n static scanlines(gl: WebGL2RenderingContext, density: number, opacity: number, noise: number, flicker: number) {\n const shader = `\n float density = ${density.toFixed(3)};\n float opacityScanline = ${opacity.toFixed(3)};\n float opacityNoise = ${noise.toFixed(3)};\n float flickering = ${flicker.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n \n float count = height * density;\n vec2 sl = vec2(sin(pos.y * count), cos(pos.y * count));\n vec3 scanlines = vec3(sl.x, sl.y, sl.x);\n \n col += col * scanlines * opacityScanline;\n col += col * vec3(randF(pos * time)) * opacityNoise;\n col += col * sin(110.0 * time) * flickering;\n \n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a glitch effect with horizontal lines\n * @param gl WebGL2RenderingContext\n * @param amount Amount of glitch, 0.0 - 1.0\n */\n static glitch(gl: WebGL2RenderingContext, amount: number) {\n const shader = `\n float amount = ${amount.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n\n float offset = randF(vec2(time, pos.y)) * amount;\n\n col.r = texture(image, vec2(pos.x + offset, pos.y)).r;\n col.g = texture(image, vec2(pos.x - offset, pos.y)).g;\n col.b = texture(image, vec2(pos.x + offset, pos.y)).b;\n\n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create duotone effect with two colours and contrast\n * @param gl WebGL2RenderingContext\n */\n static duotone(gl: WebGL2RenderingContext, colour1: RGB, colour2: RGB, contrast: number) {\n const shader = ` \n vec3 col1 = vec3(${colour1[0].toFixed(3)}, ${colour1[1].toFixed(3)}, ${colour1[2].toFixed(3)});\n vec3 col2 = vec3(${colour2[0].toFixed(3)}, ${colour2[1].toFixed(3)}, ${colour2[2].toFixed(3)});\n float contrast = ${contrast.toFixed(3)};\n\n void main() {\n vec3 col = texture(image, pos).rgb;\n\n vec3 lumFactor = vec3(0.2126, 0.7152, 0.0722);\n vec3 desat = vec3(dot(col, lumFactor));\n\n // increase contrast\n desat = pow(desat, vec3(contrast));\n desat *= contrast;\n \n pixel = vec4(mix(col1, col2, desat), 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a noise effect\n * @param gl WebGL2RenderingContext\n * @param amount Amount of noise, 0.0 - 1.0\n * @param speed Speed of noise change\n */\n static noise(gl: WebGL2RenderingContext, amount: number, speed: number) {\n const shader = `\n float amount = ${amount.toFixed(3)};\n float speed = ${speed.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n \n col.r += randPhase(pos, speed) * amount;\n col.g += randPhase(pos - 0.1, speed) * amount;\n col.b += randPhase(pos + 0.1, speed) * amount;\n \n //col += rand(8.0 * time).rgb * amount;\n\n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a two colour contrast threshold effect\n * @param gl WebGL2RenderingContext\n * @param threshold Threshold value, 0.0 - 1.0\n * @param colourDark Dark colour\n * @param colourBright Bright colour\n */\n static contrast(gl: WebGL2RenderingContext, threshold: number, colourDark: RGB, colourBright: RGB) {\n const shader = `\n float threshold = ${threshold.toFixed(3)};\n vec3 bright = vec3(${colourBright[0].toFixed(3)}, ${colourBright[1].toFixed(3)}, ${colourBright[2].toFixed(3)});\n vec3 dark = vec3(${colourDark[0].toFixed(3)}, ${colourDark[1].toFixed(3)}, ${colourDark[2].toFixed(3)});\n\n void main() {\n vec3 col = texture(image, pos).rgb;\n\n float brightness = (col.r + col.g + col.b) / 3.0;\n brightness = clamp(brightness, 0.0, 1.0);\n\n if (brightness > threshold) {\n pixel = vec4(bright, 1.0);\n } else {\n pixel = vec4(dark, 1.0);\n }\n }`\n\n return new PostEffects(gl, shader)\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Phong fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// ===== Constants ============================================================\n\nconst int MAX_LIGHTS = 16;\nconst int MAX_SHADOWS = 8;\nconst float MAX_SHAD_A = 0.125;\n\n// Got this from http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/#poisson-sampling\nvec3 poissonDisk[8] = vec3[](\n vec3(-0.94201624, -0.39906216, -0.4684316),\n vec3(0.94558609, -0.76890725, -0.34478877),\n vec3(-0.094184101, -0.9293887, -0.3048823),\n vec3(0.34495938, 0.2938776, -0.001735733),\n vec3(-0.91588581, 0.45771432, -0.087759815),\n vec3(-0.81544232, -0.87912464, -0.03352997),\n vec3(-0.38277543, 0.27676845, -0.9485365),\n vec3(-0.58723171, -0.73007023, -0.22162315)\n);\n\n// ===== Structs ==============================================================\n\nstruct LightDir {\n vec3 direction;\n vec3 colour;\n vec3 ambient;\n};\n\nstruct LightPos {\n vec3 position;\n vec3 colour;\n vec3 ambient;\n float constant;\n float linear;\n float quad;\n bool enabled;\n};\n\nstruct Material {\n vec3 ambient;\n vec3 diffuse;\n vec3 specular;\n vec3 emissive;\n float shininess;\n float opacity;\n float reflectivity;\n sampler2D diffuseTex;\n sampler2D specularTex;\n sampler2D normalTex;\n bool hasNormalTex;\n bool unshaded;\n};\n\n// Inputs from vertex shader\nin vec3 v_normal;\nin vec2 v_texCoord;\nin vec4 v_position;\nin vec4 v_shadowCoord;\n\n// Some global uniforms\nuniform vec3 u_camPos;\nuniform float u_gamma;\nuniform bool u_flipTextureX;\nuniform bool u_flipTextureY;\n\n// Main lights and material uniforms\nuniform Material u_mat;\nuniform LightDir u_lightDirGlobal;\nuniform LightPos u_lightsPos[MAX_LIGHTS];\nuniform int u_lightsPosCount;\n// Reflection map isn't part of the material struct for complex reasons\nuniform samplerCube u_reflectionMap;\n// Shadows\nuniform highp sampler2DShadow u_shadowMap;\n// uniform float u_shadowScatter; // REMOVED FOR NOW\nuniform bool u_receiveShadow;\n\n// Global texture coords shared between functions\nvec2 texCoord;\n\n// Output colour of this pixel/fragment\nout vec4 outColour;\n\n// ===== Helper functions =====================================================\n\n// Simple mixer\nvec4 mix4(vec4 a, vec4 b, float mix) {\n return a * (1.0 - mix) + b * mix;\n}\n\n// Function to help with get values from the shadow map\nfloat shadowMapSample(highp sampler2DShadow map, vec3 coord) {\n // As WebGL 2 does not support GL_CLAMP_TO_BORDER or GL_TEXTURE_BORDER_COLOR, we need to do this :(\n if (coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0) {\n return 1.0;\n }\n\n return texture(map, coord);\n}\n\n// Shade a fragment using a directional light source\nvec4 shadeDirLight(LightDir light, Material mat, vec3 N, vec3 V) {\n vec3 L = normalize(-light.direction);\n vec3 H = normalize(L + V);\n\n vec3 diffuseCol = vec3(texture(mat.diffuseTex, texCoord)) * mat.diffuse;\n vec3 specularCol = vec3(texture(mat.specularTex, texCoord)) * mat.specular;\n\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), mat.shininess) : 0.0;\n\n // Shadow map lookup\n vec3 projCoords = v_shadowCoord.xyz / v_shadowCoord.w * 0.5 + 0.5;\n\n // REMOVED FOR NOW - PCF for shadows using 8 samples of a poisson disk\n // float shadow = u_receiveShadow ? 0.0 : 1.0;\n // float scatter = u_shadowScatter / 100.0;\n // for (int i = u_receiveShadow ? 0 : MAX_SHADOWS; i < MAX_SHADOWS; i++) {\n // vec3 offset = poissonDisk[i] * scatter;\n // shadow += shadowMapSample(u_shadowMap, projCoords + offset) * MAX_SHAD_A;\n // }\n\n float shadow = u_receiveShadow ? shadowMapSample(u_shadowMap, projCoords) : 1.0;\n\n vec3 ambient = light.ambient * mat.ambient * diffuseCol;\n vec3 diffuse = light.colour * max(diff, 0.0) * diffuseCol * shadow;\n vec3 specular = light.colour * spec * specularCol * shadow;\n\n // Return a vec4 to support transparency, note specular is not affected by opacity\n return vec4(ambient + diffuse, mat.opacity / float(u_lightsPosCount + 1)) + vec4(specular, spec);\n}\n\n// Shade a fragment using a positional light source\nvec4 shadePosLight(LightPos light, Material mat, vec3 N, vec3 V) {\n vec3 L = normalize(light.position - v_position.xyz);\n vec3 H = normalize(L + V);\n\n vec3 diffuseCol = vec3(texture(mat.diffuseTex, texCoord)) * mat.diffuse;\n vec3 specularCol = vec3(texture(mat.specularTex, texCoord)) * mat.specular;\n\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), mat.shininess) : 0.0;\n\n // Light attenuation, see: https://learnopengl.com/Lighting/Light-casters\n float dist = length(light.position - v_position.xyz);\n float attenuation = 1.0 / (light.constant + light.linear * dist + light.quad * (dist * dist));\n\n vec3 ambient = light.ambient * mat.ambient * diffuseCol * attenuation;\n vec3 diffuse = light.colour * max(diff, 0.0) * diffuseCol * attenuation;\n vec3 specular = light.colour * spec * specularCol * attenuation;\n\n // Return a vec4 to support transparency, note specular is not affected by opacity\n return vec4(ambient + diffuse, mat.opacity / float(u_lightsPosCount + 1)) + vec4(specular, spec);\n}\n\n// ===== Main shader ==========================================================\n\nvoid main() {\n vec3 V = normalize(u_camPos - v_position.xyz);\n\n // Flip texture coords if needed\n texCoord = u_flipTextureY ? vec2(v_texCoord.x, 1.0 - v_texCoord.y) : v_texCoord;\n texCoord = u_flipTextureX ? vec2(1.0 - texCoord.x, texCoord.y) : texCoord;\n\n vec3 N = normalize(v_normal);\n\n // Normal mapping, this is expensive so only do it if we have a normal map\n if (u_mat.hasNormalTex) {\n vec3 normMap = texture(u_mat.normalTex, texCoord).xyz * 2.0 - 1.0;\n\n vec3 Q1 = dFdx(v_position.xyz);\n vec3 Q2 = dFdy(v_position.xyz);\n vec2 st1 = dFdx(texCoord);\n vec2 st2 = dFdy(texCoord);\n\n vec3 T = -normalize(Q1 * st2.t - Q2 * st1.t);\n vec3 B = normalize(cross(N, T));\n mat3 TBN = mat3(T, B, N);\n\n N = normalize(TBN * normMap);\n }\n\n vec4 outColorPart;\n if (u_mat.unshaded) {\n // Skip lighting/shading and just use the texture if unshaded\n vec3 diffuseTexCol = vec3(texture(u_mat.diffuseTex, texCoord)) * u_mat.diffuse;\n outColorPart = vec4(diffuseTexCol, 1.0);\n } else {\n // Handle the main directional light, only one of these\n outColorPart = shadeDirLight(u_lightDirGlobal, u_mat, N, V);\n\n // Add positional lights\n for (int i = 0; i < u_lightsPosCount; i++) {\n outColorPart += shadePosLight(u_lightsPos[i], u_mat, N, V);\n }\n }\n\n // Add emissive component\n float emissiveAlpha = u_mat.emissive.r + u_mat.emissive.g + u_mat.emissive.b > 0.0 ? 1.0 : 0.0;\n outColorPart += vec4(u_mat.emissive, emissiveAlpha);\n\n // Get reflection vector and sample reflection texture\n vec3 R = reflect(-V, N);\n vec4 reflectCol = vec4(texture(u_reflectionMap, R).rgb, 1.0);\n\n // Add reflection component, not sure if this is correct, looks ok\n outColorPart = mix4(outColorPart, reflectCol, u_mat.reflectivity);\n\n // Gamma correction, as GL_FRAMEBUFFER_SRGB is not supported on WebGL\n outColorPart.rgb = pow(outColorPart.rgb, vec3(1.0 / u_gamma));\n\n outColour = outColorPart;\n}\n","#version 300 es\n\n// ============================================================================\n// Phong vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// Input attributes from buffers\nin vec4 position;\nin vec3 normal;\nin vec2 texcoord;\n\nuniform mat4 u_worldViewProjection;\nuniform mat4 u_worldInverseTranspose;\nuniform mat4 u_world;\nuniform mat4 u_shadowMatrix;\n\n// Output varying's to pass to fragment shader\nout vec2 v_texCoord;\nout vec3 v_normal;\nout vec4 v_position;\nout vec4 v_shadowCoord;\n\nvoid main() {\n v_texCoord = texcoord;\n v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;\n v_position = u_world * position;\n v_shadowCoord = u_shadowMatrix * v_position;\n\n gl_Position = u_worldViewProjection * position;\n}\n","#version 300 es\n\n// ============================================================================\n// Billboard fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nstruct Material {\n vec3 ambient;\n vec3 diffuse;\n vec3 specular;\n vec3 emissive;\n float shininess;\n float opacity;\n float reflectivity;\n sampler2D diffuseTex;\n sampler2D specularTex;\n sampler2D normalTex;\n bool hasNormalTex;\n};\n\n// From vertex shader\nin vec2 v_texCoord;\nin vec3 v_lighting;\n\n// Main lights and material uniforms\nuniform Material u_mat;\nuniform float u_gamma;\n\n// Output colour of this pixel/fragment\nout vec4 outColour;\n\nvoid main() {\n vec4 texel = texture(u_mat.diffuseTex, v_texCoord);\n\n // Magic to make transparent sprites work, without blending\n // Somehow this also works with the shadow map render pass, which is a bonus\n if (texel.a < 0.75) {\n discard;\n }\n\n vec3 colour = texel.rgb * u_mat.diffuse * v_lighting;\n\n // Gamma correction, as GL_FRAMEBUFFER_SRGB is not supported on WebGL\n colour = pow(colour, vec3(1.0 / u_gamma));\n\n outColour = vec4(colour, u_mat.opacity);\n}\n","#version 300 es\n\n// ============================================================================\n// Billboard vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nconst int MAX_LIGHTS = 16;\n\nstruct LightDir {\n vec3 direction;\n vec3 colour;\n vec3 ambient;\n};\n\nstruct LightPos {\n vec3 position;\n vec3 colour;\n vec3 ambient;\n float constant;\n float linear;\n float quad;\n bool enabled;\n};\n\n// Input attributes from buffers\nin vec4 position;\nin vec2 texcoord;\n\nuniform mat4 u_worldViewProjection;\nuniform mat4 u_world;\nuniform int u_lightsPosCount;\nuniform vec3 u_camPos;\nuniform LightDir u_lightDirGlobal;\nuniform LightPos u_lightsPos[MAX_LIGHTS];\n\n// Output varying's to pass to fragment shader\nout vec2 v_texCoord;\nout vec3 v_lighting;\n\n/*\n * Legacy lighting calc\n * Returns vec2(diffuse, specular)\n */\nvec2 lightCalc(vec3 N, vec3 L, vec3 H, float shininess) {\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), shininess) : 0.0;\n return vec2(diff, spec);\n}\n\nvoid main() {\n v_texCoord = texcoord;\n gl_Position = u_worldViewProjection * position;\n vec3 worldPos = (u_world * position).xyz;\n\n // Normal for a billboard always points at camera\n vec3 worldNormal = normalize(u_camPos - worldPos);\n\n vec3 V = normalize(u_camPos - worldPos);\n vec3 N = normalize(worldNormal);\n float fudge = 1.5;\n\n // Add point lights to lighting output\n for (int i = 0; i < u_lightsPosCount; i++) {\n LightPos light = u_lightsPos[i];\n vec3 L = normalize(light.position - worldPos.xyz);\n\n float diffuse = max(dot(N, L), 0.0);\n\n // Distance attenuation\n float distance = length(light.position - worldPos.xyz);\n float attenuation = 1.0 / (light.constant + light.linear * distance + light.quad * (distance * distance));\n\n // Note small hack here to fudge the light intensity\n v_lighting += light.colour * fudge * attenuation * diffuse;\n }\n\n // Add in global directional light\n // Approximate by using a fixed direction for the normal pointing up\n vec3 globalLightL = normalize(-u_lightDirGlobal.direction);\n float globalDiffuse = dot(vec3(0.0, 1.0, 0.0), globalLightL);\n\n v_lighting += u_lightDirGlobal.colour * globalDiffuse;\n v_lighting += u_lightDirGlobal.ambient;\n}\n","// ===== physics.ts ===============================================================================\n// Helper functions for adding physics to instances using CANNON.js\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport * as CANNON from 'cannon-es'\nimport { Instance } from '../renderable/instance.ts'\nimport { PrimitiveCube, PrimitiveSphere } from '../renderable/primitive.ts'\nimport { quat } from 'gl-matrix'\nimport { Model } from '../renderable/model.ts'\nimport { XYZ } from './tuples.ts'\n\n/**\n * Create a new CANNON.Body for a sphere, will link the body to the instance\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n */\nfunction createSphereBody(inst: Instance, mass: number, material?: CANNON.Material, offset = [0, 0, 0] as XYZ) {\n if (inst.renderable === undefined) {\n throw new Error('Cannot create body for instance with no renderable')\n }\n\n let radius = 1\n if (inst.renderable instanceof PrimitiveSphere) {\n radius = (inst.renderable as PrimitiveSphere).radius\n }\n\n if (inst.renderable instanceof PrimitiveCube) {\n radius = (inst.renderable as PrimitiveCube).size / 2\n }\n\n if (inst.renderable instanceof Model) {\n // Base the radius on the bounding box of the model\n const boundBox = (inst.renderable as Model).boundingBox\n\n const x = (boundBox[3] - boundBox[0]) * inst.scale[0]\n const y = (boundBox[4] - boundBox[1]) * inst.scale[1]\n const z = (boundBox[5] - boundBox[2]) * inst.scale[2]\n\n radius = Math.max(x, y, z) / 2\n }\n\n const body = new CANNON.Body({\n mass,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n material,\n })\n\n const offsetVec = new CANNON.Vec3(offset[0], offset[1], offset[2])\n body.addShape(new CANNON.Sphere(radius), offsetVec)\n\n inst.physicsBody = body\n return body\n}\n\n/**\n * Create a new cube/box CANNON.Body enclosing the provided instance. It will attempt fit the box to the\n * instance as best a possible, otherwise will fall back to a 1x1x1 box\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n * @param offset Optional offset to apply to the body, useful when models are not centered on origin\n */\nfunction createBoxBody(inst: Instance, mass: number, material?: CANNON.Material, offset = [0, 0, 0] as XYZ) {\n if (inst.renderable === undefined) {\n throw new Error('Cannot create body for instance with no renderable')\n }\n\n let sizeVec = new CANNON.Vec3(0.5, 0.5, 0.5)\n\n if (inst.renderable instanceof PrimitiveSphere) {\n const size = (inst.renderable as PrimitiveSphere).radius * 2\n sizeVec = new CANNON.Vec3(size / 2, size / 2, size / 2)\n }\n\n if (inst.renderable instanceof PrimitiveCube) {\n const size = (inst.renderable as PrimitiveCube).size\n sizeVec = new CANNON.Vec3((size / 2) * inst.scale[0], (size / 2) * inst.scale[1], (size / 2) * inst.scale[2])\n }\n\n if (inst.renderable instanceof Model) {\n // Base the size on the bounding box of the model\n const boundBox = (inst.renderable as Model).boundingBox\n\n sizeVec = new CANNON.Vec3(\n ((boundBox[3] - boundBox[0]) * inst.scale[0]) / 2,\n ((boundBox[4] - boundBox[1]) * inst.scale[1]) / 2,\n ((boundBox[5] - boundBox[2]) * inst.scale[2]) / 2,\n )\n }\n\n const quat = inst.getQuaternion()\n const body = new CANNON.Body({\n mass,\n material,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n quaternion: new CANNON.Quaternion(quat[0], quat[1], quat[2], quat[3]),\n })\n\n const offsetVec = new CANNON.Vec3(offset[0], offset[1], offset[2])\n body.addShape(new CANNON.Box(sizeVec), offsetVec)\n\n inst.physicsBody = body\n return body\n}\n\n/**\n * Create a new CANNON.Body for a plane, will link the body to the instance\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n */\nfunction createPlaneBody(inst: Instance, mass: number, material?: CANNON.Material) {\n const instQuat = inst.getQuaternion()\n const q = quat.fromValues(instQuat[0], instQuat[1], instQuat[2], instQuat[3])\n\n // Rotate 90 degrees around the X axis, as CANNON.Plane is along the Z axis\n quat.rotateX(q, q, -Math.PI / 2)\n\n const quaternion = new CANNON.Quaternion(q[0], q[1], q[2], q[3])\n\n const body = new CANNON.Body({\n mass,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n shape: new CANNON.Plane(),\n material,\n quaternion,\n })\n\n inst.physicsBody = body\n return body\n}\n\nexport const Physics = {\n createSphereBody,\n createBoxBody,\n createPlaneBody,\n}\n","// ===== builder.ts =========================================================\n// Instance builder for creating custom renderable instances\n// Ben Coleman, 2024\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { vec3 } from 'gl-matrix'\n\nimport { Renderable } from './types.ts'\nimport { ProgramCache } from '../core/cache.ts'\nimport { Stats } from '../core/stats.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { Material } from '../engine/material.ts'\nimport { XYZ } from '../engine/tuples.ts'\nimport { ModelPart } from './model.ts'\n\n// TODO: No support for smooth shading, with shared vertices and normals\n\n/**\n * A builder for creating multi-part custom renderable instances from triangle meshes\n *\n * Example usage:\n * ```typescript\n * const builder = new RenderableBuilder()\n * const part = builder.newPart('foo' Material.RED)\n * builder.addTriangle([1, -1, 1], [1, 1, 1], [-1, 1, 1])\n * const renderable = builder.build(gl)\n */\nexport class RenderableBuilder {\n public readonly parts: Map\n private materials: Map\n\n constructor() {\n this.parts = new Map()\n this.materials = new Map()\n }\n\n /**\n * Create and add a 'part', each part should have a unique name, and material to apply to it\n * Vertex mesh data is then added to the part, with addQuad and addTriangle\n * @param name Name of this part, just a string can be anything\n * @param material Material to attach and apply to all surfaces in this part\n */\n newPart(name: string, material: Material): BuilderPart {\n if (this.parts.has(name)) {\n throw new Error('Builder part name exists!')\n }\n\n const builderPart = new BuilderPart()\n\n this.parts.set(name, builderPart)\n this.materials.set(name, material)\n\n return builderPart\n }\n\n /**\n * Called after all parts are ready, to generate a CustomRenderable\n * @param gl A WebGL2RenderingContext\n */\n build(gl: WebGL2RenderingContext): CustomRenderable {\n const buffers = new Map()\n\n for (const [name, builderPart] of this.parts) {\n const partBuffers = builderPart.build(gl)\n if (!partBuffers) continue\n buffers.set(name, partBuffers)\n }\n\n return new CustomRenderable(buffers, this.materials)\n }\n}\n\n/**\n * Class to manage parts or sections\n */\nexport class BuilderPart {\n private vertexData: number[] = []\n private vertexCount: number = 0\n private indexData: number[] = []\n private indexCount: number = 0\n private normalData: number[] = []\n private texcoordData: number[] = []\n\n private triangleCount: number = 0\n private _customArrayData: twgl.Arrays | undefined\n\n private addVertex(x: number, y: number, z: number): number {\n this.vertexData.push(x, y, z)\n return this.vertexCount++\n }\n\n private addIndex(): number {\n this.indexData.push(this.indexCount)\n return this.indexCount++\n }\n\n private addNormal(n: XYZ) {\n this.normalData.push(n[0], n[1], n[2])\n }\n\n /**\n * Add a triangle to the renderable part\n * Each triangle must be defined by 3 vertices and will get a normal calculated\n * Each triangle will get a unique normal, so no smooth shading\n * @param v1 Vertex one of the triangle\n * @param v2 Vertex two of the triangle\n * @param v3 Vertex three of the triangle\n */\n addTriangle(v1: XYZ, v2: XYZ, v3: XYZ, tc1 = [0, 0], tc2 = [0, 0], tc3 = [0, 0]) {\n this.triangleCount++\n this.addVertex(v1[0], v1[1], v1[2])\n this.addIndex()\n this.addVertex(v2[0], v2[1], v2[2])\n this.addIndex()\n this.addVertex(v3[0], v3[1], v3[2])\n this.addIndex()\n\n // Normal calculation\n const u = vec3.subtract(vec3.create(), v2, v1)\n const v = vec3.subtract(vec3.create(), v3, v1)\n const n = vec3.cross(vec3.create(), u, v)\n vec3.normalize(n, n)\n\n this.addNormal([n[0], n[1], n[2]])\n this.addNormal([n[0], n[1], n[2]])\n this.addNormal([n[0], n[1], n[2]])\n\n this.texcoordData.push(...tc1, ...tc2, ...tc3)\n }\n\n /*\n * Add a two triangle quad to the renderable part\n * Each quad must be defined by 4 vertices and will get a normal calculated\n * Each quad will get a unique normal, so no smooth shading\n * @param v1 Vertex one of the quad\n * @param v2 Vertex two of the quad\n * @param v3 Vertex three of the quad\n * @param v4 Vertex four of the quad\n */\n addQuad(v1: XYZ, v2: XYZ, v3: XYZ, v4: XYZ, tc1 = [0, 0], tc2 = [0, 0], tc3 = [0, 0], tc4 = [0, 0]) {\n // Anti-clockwise winding order\n this.addTriangle(v1, v2, v3, tc1, tc2, tc3)\n this.addTriangle(v1, v3, v4, tc1, tc3, tc4)\n }\n\n /**\n * This is a very advanced feature, and allows you to provide your own twgl.Arrays\n * This is useful for creating custom renderables from existing data\n * @param array The twgl.Arrays to use for the renderable\n */\n set customArrayData(array: twgl.Arrays) {\n this._customArrayData = array\n }\n\n /**\n * Build the renderable from the data added\n * @param gl A WebGL2 rendering context\n * @returns BufferInfo used by twgl\n */\n build(gl: WebGL2RenderingContext): twgl.BufferInfo | null {\n let bufferInfo: twgl.BufferInfo\n if (this._customArrayData) {\n bufferInfo = twgl.createBufferInfoFromArrays(gl, this._customArrayData)\n } else {\n if (this.vertexData.length === 0) {\n return null\n }\n\n if (this.indexData.length === 0) {\n return null\n }\n\n // This is where the magic happens\n bufferInfo = twgl.createBufferInfoFromArrays(gl, {\n position: this.vertexData,\n indices: this.indexData,\n normal: this.normalData,\n texcoord: this.texcoordData,\n })\n }\n\n return bufferInfo\n }\n}\n\n/**\n * A custom renderable instance, created from a RenderableBuilder\n */\nexport class CustomRenderable implements Renderable {\n private programInfo: twgl.ProgramInfo = ProgramCache.instance.default\n private _triangleCount: number = 0\n private modelParts: ModelPart[]\n\n // List of materials mapped by name\n public readonly materials: Map\n\n constructor(bufferInfos: Map, materials: Map) {\n this.modelParts = new Array()\n this.materials = materials\n\n for (const [name, bi] of bufferInfos) {\n const p = new ModelPart(bi, name)\n this.modelParts.push(p)\n }\n }\n\n /**\n * Render is used draw this custom renderable, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ) {\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n // Render all parts\n for (const part of this.modelParts) {\n const bufferInfo = part.bufferInfo\n\n if (materialOverride === undefined) {\n const material = this.materials.get(part.materialName)\n if (!material) continue\n material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, bufferInfo)\n Stats.drawCallsPerFrame++\n }\n }\n\n get triangleCount(): number {\n return this._triangleCount\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAMA,KAAC,SAAU,MAAM,YAAY;AACzB;AACA,UAAI,OAAO,WAAW,cAAc,OAAO,KAAK;AAC5C,eAAO,UAAU;AAAA,MACrB,WAAW,OAAO,WAAW,YAAY,OAAO,SAAS;AACrD,eAAO,UAAU,WAAW;AAAA,MAChC,OAAO;AACH,aAAK,MAAM,WAAW;AAAA,MAC1B;AAAA,IACJ,GAAE,SAAM,WAAY;AAChB;AAGA,UAAIA,QAAO,WAAW;AAAA,MAAC;AACvB,UAAI,gBAAgB;AACpB,UAAI,OAAQ,OAAO,WAAW,iBAAmB,OAAO,OAAO,cAAc,iBACzE,kBAAkB,KAAK,OAAO,UAAU,SAAS;AAGrD,UAAI,aAAa;AAAA,QACb;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACJ;AAEA,UAAI,iBAAiB,CAAC;AACtB,UAAI,gBAAg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IAAI,IAAI;AAChC,WAAK,WAAW,KAAK,CAAC;AAAA,IACxB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OACE,IACA,UACA,kBACA,iBACA;AACA,UAAM,cAAc,mBAAmB,KAAK;AAC5C,OAAG,WAAW,YAAY,OAAO;AAGjC,eAAW,QAAQ,KAAK,YAAY;AAClC,YAAM,aAAa,KAAK;AAExB,UAAI,qBAAqB,QAAW;AAClC,cAAM,WAAW,KAAK,UAAU,IAAI,KAAK,YAAY;AACrD,YAAI,CAAC;AAAU;AACf,iBAAS,MAAM,WAAW;AAAA,MAC5B,OAAO;AACL,yBAAiB,MAAM,WAAW;AAAA,MACpC;AAEA,MAAK,wBAAwB,IAAI,aAAa,UAAU;AACxD,MAAK,YAAY,aAAa,QAAQ;AAEtC,MAAK,eAAe,IAAI,UAAU;AAClC,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,IAAI,gBAAwB;AAC1B,WAAO,KAAK;AAAA,EACd;AACF;","names":["noop","location","log","import_loglevel","a","b","a","b","v0","v1","v2","a","length","length","length","len","tmp","v0","v1","v2","lerp","a","b","angle","c","base","glEnumToString","isArrayBuffer","getShared2DContext","internalFormat","isArrayBuffer","isArrayBuffer","a","b","clearEventHandlers","onError","onLoad","cb","img","location","b","typeInfo","normalize","log","error","gl","program","token","node","program","location","program","errors","gl","programs","add","create","identity","create","a","identity","b","b2","len","c","add","scale","a2","add","clone","copy","create","dot","equals","exactEquals","fromValues","identity","invert","len","length","lerp","mul","multiply","normalize","random","rotateX","rotateY","rotateZ","scale","set","sqrLen","squaredLength","str","add","clone","copy","create","equals","exactEquals","fromValues","inverse","length","mul","multiply","rotateX","rotateY","rotateZ","scale","set","str","sub","subtract","create","clone","a","length","fromValues","copy","set","add","b","subtract","multiply","scale","inverse","len","c","rotateX","rotateY","rotateZ","str","exactEquals","equals","a2","b2","sub","mul","create","clone","a","fromValues","copy","set","add","b","scale","a","b","length","a","squaredLength","normalize","a","len","dot","b","lerp","a","b","exactEquals","a","b","equals","a2","b2","forEach","create","a","create","identity","a","b","dot","multiply","rotateX","rotateY","rotateZ","scale","random","invert","a2","str","clone","fromValues","copy","set","add","mul","lerp","length","len","squaredLength","sqrLen","normalize","exactEquals","equals","c","b","tmp","a","c","angle","a","min","max","va","vb","vc","cb","ab","b","dist","c","localPlaneEq","planeEqWS","add","wc","torque","distance","len","a","b","c","dot","squaredDistance","a","b","b","min","max","min","max","c","dot","dot2","dist","r","v1","v2","j","relpos","worldPillarOffset","min","max","tmp","va","vb","vc","performance","normalize","len","scale","distance","a","b","add","import_loglevel","log","import_loglevel","CameraType","camView","log","glsl_default","glsl_default","import_loglevel","glsl_default","glsl_default","a","b","glsl_default","log","import_loglevel","log","angle","BillboardType","scale","Material","b","Material","import_loglevel","update_default","render_default","update_default","render_default","log","import_loglevel","keywordRE","Material","log","debug","log","glsl_default","glsl_default","glsl_default","glsl_default","log","glsl_default","a","b","v1","v2"]} \ No newline at end of file +{"version":3,"sources":["../node_modules/loglevel/lib/loglevel.js","../src/core/gl.ts","../src/core/context.ts","../node_modules/twgl.js/dist/5.x/twgl-full.module.js","../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat3.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/quat.js","../node_modules/gl-matrix/esm/vec3.js","../node_modules/gl-matrix/esm/vec4.js","../package.json","../node_modules/cannon-es/dist/cannon-es.js","../src/engine/tuples.ts","../src/core/cache.ts","../src/engine/camera.ts","../shaders/shadowmap/glsl.frag","../shaders/shadowmap/glsl.vert","../src/engine/lights.ts","../src/engine/envmap.ts","../shaders/envmap/glsl.frag","../shaders/envmap/glsl.vert","../src/core/stats.ts","../src/engine/node.ts","../src/renderable/instance.ts","../src/renderable/billboard.ts","../src/engine/material.ts","../src/renderable/primitive.ts","../src/renderable/particles.ts","../shaders/particles/update.frag","../shaders/particles/update.vert","../shaders/particles/render.frag","../shaders/particles/render.vert","../src/renderable/model.ts","../src/parsers/mtl-parser.ts","../src/parsers/obj-parser.ts","../src/core/files.ts","../src/core/hud.ts","../src/engine/post-effects.ts","../shaders/phong/glsl.frag","../shaders/phong/glsl.vert","../shaders/billboard/glsl.frag","../shaders/billboard/glsl.vert","../src/engine/physics.ts","../src/renderable/builder.ts"],"sourcesContent":["/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n var _loggersByName = {};\n var defaultLogger = null;\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods() {\n /*jshint validthis:true */\n var level = this.getLevel();\n\n // Replace the actual methods.\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, this.name);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n\n // Return any important warnings.\n if (typeof console === undefinedType && level < this.levels.SILENT) {\n return \"No console available for logging\";\n }\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, _level, _loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, factory) {\n // Private instance variables.\n var self = this;\n /**\n * The level inherited from a parent logger (or a global default). We\n * cache this here rather than delegating to the parent so that it stays\n * in sync with the actual logging methods that we have installed (the\n * parent could change levels but we might not have rebuilt the loggers\n * in this child yet).\n * @type {number}\n */\n var inheritedLevel;\n /**\n * The default level for this logger, if any. If set, this overrides\n * `inheritedLevel`.\n * @type {number|null}\n */\n var defaultLevel;\n /**\n * A user-specific level for this logger. If set, this overrides\n * `defaultLevel`.\n * @type {number|null}\n */\n var userLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var cookieName = encodeURIComponent(storageKey);\n var location = cookie.indexOf(cookieName + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(\n cookie.slice(location + cookieName.length + 1)\n )[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n function normalizeLevel(input) {\n var level = input;\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n return level;\n } else {\n throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n }\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n if (userLevel != null) {\n return userLevel;\n } else if (defaultLevel != null) {\n return defaultLevel;\n } else {\n return inheritedLevel;\n }\n };\n\n self.setLevel = function (level, persist) {\n userLevel = normalizeLevel(level);\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(userLevel);\n }\n\n // NOTE: in v2, this should call rebuild(), which updates children.\n return replaceLoggingMethods.call(self);\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = normalizeLevel(level);\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n userLevel = null;\n clearPersistedLevel();\n replaceLoggingMethods.call(self);\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n self.rebuild = function () {\n if (defaultLogger !== self) {\n inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n }\n replaceLoggingMethods.call(self);\n\n if (defaultLogger === self) {\n for (var childName in _loggersByName) {\n _loggersByName[childName].rebuild();\n }\n }\n };\n\n // Initialize all the internal levels.\n inheritedLevel = normalizeLevel(\n defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n );\n var initialLevel = getPersistedLevel();\n if (initialLevel != null) {\n userLevel = normalizeLevel(initialLevel);\n }\n replaceLoggingMethods.call(self);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n defaultLogger = new Logger();\n\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name,\n defaultLogger.methodFactory\n );\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","// ===== gl.ts ==========================================================\n// Interactions with the GL context, as a global singleton\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport log from 'loglevel'\n\n/** A map of uniforms that can be used when WebGL rendering, typically applied with twlg.setUniforms() */\nexport type UniformSet = { [key: string]: number | number[] | mat4 | WebGLTexture | null }\n\n// Memoized global WebGL2 context\nlet glContext: WebGL2RenderingContext | undefined\n\n/**\n * Get the WebGL2 context, if it doesn't exist it will be created for the provided canvas element, and memoized\n * @returns {WebGL2RenderingContext} - Global WebGL2 context\n * @param {boolean} aa - Enable antialiasing\n * @param {string} selector - CSS selector for locating the canvas element\n */\nexport function getGl(selector = 'canvas', aa = true) {\n if (glContext) {\n return glContext\n }\n\n log.info(`🖌️ Creating new WebGL2 context for: '${selector}'`)\n\n const canvasElement = document.querySelector(selector) as HTMLElement\n if (!canvasElement) {\n log.error(`💥 FATAL! Unable to find element with selector: '${selector}'`)\n return undefined\n }\n\n if (canvasElement && canvasElement.tagName !== 'CANVAS') {\n log.error(`💥 FATAL! Element with selector: '${selector}' is not a canvas element`)\n return undefined\n }\n\n const canvas = canvasElement as HTMLCanvasElement\n if (!canvas) {\n log.error(`💥 FATAL! Unable to find canvas element with selector: '${selector}'`)\n return undefined\n }\n\n glContext = canvas.getContext('webgl2', { antialias: aa }) ?? undefined\n\n if (!glContext) {\n log.error(`💥 Unable to create WebGL2 context, maybe it's not supported on this device`)\n return undefined\n }\n\n log.info(`📐 Internal: ${canvas.width} x ${canvas.height}, display: ${canvas.clientWidth} x ${canvas.clientHeight}`)\n\n return glContext\n}\n","// ===== context.ts ===========================================================\n// Main rendering context, this is the core of the library\n// Ben Coleman, 2023\n// ============================================================================\n\nimport log from 'loglevel'\nimport * as CANNON from 'cannon-es'\nimport * as twgl from 'twgl.js'\nimport { mat4, vec3 } from 'gl-matrix'\n\nimport { version } from '../../package.json'\nimport { getGl, UniformSet } from './gl.ts'\nimport { RGB, XYZ, Tuples } from '../engine/tuples.ts'\nimport { ModelCache, ProgramCache, TextureCache } from './cache.ts'\nimport { LightDirectional, LightPoint } from '../engine/lights.ts'\nimport { Camera, CameraType } from '../engine/camera.ts'\nimport { Material } from '../engine/material.ts'\nimport { DynamicEnvironmentMap, EnvironmentMap } from '../engine/envmap.ts'\nimport { Instance } from '../renderable/instance.ts'\nimport { Billboard, BillboardType } from '../renderable/billboard.ts'\nimport { PrimitiveCube, PrimitivePlane, PrimitiveSphere, PrimitiveCylinder } from '../renderable/primitive.ts'\nimport { ParticleSystem } from '../renderable/particles.ts'\nimport { Model } from '../renderable/model.ts'\nimport { HUD } from './hud.ts'\nimport { Stats } from './stats.ts'\nimport { PostEffects } from '../engine/post-effects.ts'\nimport { RenderableBuilder } from '../renderable/builder.ts'\n\n// Import shaders, tsup will inline these as text strings\nimport fragShaderPhong from '../../shaders/phong/glsl.frag'\nimport vertShaderPhong from '../../shaders/phong/glsl.vert'\nimport fragShaderBill from '../../shaders/billboard/glsl.frag'\nimport vertShaderBill from '../../shaders/billboard/glsl.vert'\n\n/** @ignore Total max dynamic lights */\nconst MAX_LIGHTS = 16\n\n/**\n * The main rendering context. This is the effectively main entry point for the library.\n * Typically you will create a single instance of this class using init() and use it to render your scene.\n */\nexport class Context {\n private gl: WebGL2RenderingContext\n private started: boolean\n private instances: Map // Keyed on instance id\n private instancesTrans: Map\n private instancesParticles: Map\n private cameras: Map\n private activeCameraName: string\n private _envmap?: EnvironmentMap\n private dynamicEnvMap?: DynamicEnvironmentMap\n private renderPass: number\n\n /** Global directional light */\n public globalLight: LightDirectional\n\n /** All the dynamic point lights in the scene */\n public lights: LightPoint[]\n\n /** Main camera for this context */\n private _camera: Camera\n\n /** Show extra debug details on the canvas */\n public debug: boolean\n\n /** Optional post effects filter to apply to the output image */\n private postEffects?: PostEffects\n\n /**\n * The pre-render update function, called every frame.\n * Hook in your custom logic and processing here\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n public update: (delta: number, now?: number) => void = () => {}\n\n /** A HUD you can use to render HTML elements over the canvas */\n public readonly hud: HUD\n\n /** Gamma correction value, default 1.0 */\n public gamma: number\n\n /**\n * Integration with cannon-es for physics, set the CANNON.World you are using here.\n * When set, world stepping will be called for you in the core rendering loop\n */\n public physicsWorld?: CANNON.World\n\n /** Set the fixed time step for physics stepping, only used when physicsWorld is set */\n public physicsTimeStep: number\n\n /** Backface culling */\n public disableCulling = false\n\n // ==== Getters =============================================================\n\n /** Get the active camera */\n get camera() {\n return this._camera\n }\n\n /** Get the name of the active camera */\n get cameraName() {\n return this.activeCameraName\n }\n\n /** Get the current EnvironmentMap for the scene */\n get envmap() {\n return this._envmap\n }\n\n /** Constructor is private, use init() to create a new context */\n private constructor(gl: WebGL2RenderingContext) {\n this.gl = gl\n this.started = false\n this.debug = false\n this.gamma = 1.0\n this.instances = new Map()\n this.instancesTrans = new Map()\n this.instancesParticles = new Map()\n this.cameras = new Map()\n this.lights = []\n this.renderPass = 0\n this.physicsTimeStep = 1 / 60\n\n // Main global light\n this.globalLight = new LightDirectional()\n this.globalLight.setAsPosition(20, 50, 30)\n\n const defaultCamera = new Camera(CameraType.PERSPECTIVE)\n this.cameras.set('default', defaultCamera)\n this._camera = defaultCamera\n this.activeCameraName = 'default'\n\n this.hud = new HUD(gl.canvas)\n\n this.setLogLevel('info')\n\n log.info(`👑 GSOTS-3D context created, v${version}`)\n }\n\n /**\n * Create & initialize a new Context which will render into provided canvas. This is where you start when using the library.\n * @param canvasSelector CSS selector for canvas element, default is 'canvas'\n * @param antiAlias Enable anti-aliasing in the renderer, default is true\n */\n static async init(canvasSelector = 'canvas', antiAlias = true) {\n const gl = getGl(canvasSelector, antiAlias)\n\n if (!gl) {\n log.error('💥 Failed to create WebGL context, this is extremely bad news')\n throw new Error('Failed to get WebGL context')\n }\n\n // Create the context around the WebGL2 context\n const ctx = new Context(gl)\n\n const canvas = gl.canvas\n ctx.camera.aspectRatio = canvas.clientWidth / canvas.clientHeight\n\n // Load shaders and put into global cache\n const phongProgInfo = twgl.createProgramInfo(gl, [vertShaderPhong, fragShaderPhong])\n ProgramCache.init(phongProgInfo)\n ProgramCache.instance.add(ProgramCache.PROG_PHONG, phongProgInfo)\n ProgramCache.instance.add(ProgramCache.PROG_BILLBOARD, twgl.createProgramInfo(gl, [vertShaderBill, fragShaderBill]))\n log.info(`🎨 Loaded all shaders & programs, GL is ready`)\n\n gl.enable(gl.DEPTH_TEST)\n gl.enable(gl.BLEND)\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)\n\n // Bind to the render function\n ctx.render = ctx.render.bind(ctx)\n\n // Global texture cache, needs to be initialized after GL context is ready\n TextureCache.init(gl)\n\n return ctx\n }\n\n /**\n * Main render loop, called every frame by the context when started\n * @param now Current time in milliseconds\n */\n private async render(now: number) {\n if (!this.gl) return\n\n Stats.updateTime(now)\n\n // Move camera before any rendering\n this.camera.update()\n\n // -----------------------------------------------------------------------\n // RENDER CORE - Render into the dynamic environment map(s) if any\n // -----------------------------------------------------------------------\n if (this.dynamicEnvMap) {\n // This is a rare case of passing the context to the object, but it's needed for the dynamic env map\n this.dynamicEnvMap.update(this.gl, this)\n }\n\n // -------------------------------------------------------------\n // RENDER CORE - Render the shadow map from the global light\n // -------------------------------------------------------------\n if (this.globalLight.shadowsEnabled) {\n // Switch to front face culling for shadow map, yeah it's weird but it works!\n this.gl.cullFace(this.gl.FRONT)\n this.gl.enable(this.gl.POLYGON_OFFSET_FILL)\n\n const shadowOpt = this.globalLight.shadowMapOptions\n this.gl.polygonOffset(shadowOpt?.polygonOffset ?? 0, 1)\n\n // Bind the shadow map framebuffer and render the scene from the light's POV\n // Using the special shadow map program as an override for the whole rendering pass\n twgl.bindFramebufferInfo(this.gl, this.globalLight.shadowMapFrameBufffer)\n const shadowCam = this.globalLight.getShadowCamera(this.camera)\n\n if (shadowCam) {\n this.addCamera('__shadow', shadowCam)\n this.renderWithCamera(shadowCam, this.globalLight.shadowMapProgram)\n }\n\n // Switch back to back face culling\n this.gl.cullFace(this.gl.BACK)\n this.gl.disable(this.gl.POLYGON_OFFSET_FILL)\n }\n\n // -------------------------------------------------------------------------------------\n // RENDER CORE - FINAL: Render the scene from active camera into the main framebuffer\n // -------------------------------------------------------------------------------------\n if (this.postEffects) {\n // Render the main camera view into the post effects framebuffer\n twgl.bindFramebufferInfo(this.gl, this.postEffects.frameBuffer)\n this.renderWithCamera(this.camera)\n\n // Then render the post effects to the screen\n this.postEffects.renderToScreen(this.gl)\n } else {\n twgl.bindFramebufferInfo(this.gl, null)\n this.renderWithCamera(this.camera)\n }\n\n // **** FINAL POST RENDER STEPS ****\n\n this.hud.render(this.debug, this.camera)\n\n // Call the external update function\n this.update(Stats.deltaTime, now)\n\n // Advance the physics simulation if configured\n if (this.physicsWorld) {\n this.physicsWorld.step(this.physicsTimeStep, Stats.prevTime)\n }\n\n // Reset stats for next frame\n Stats.resetPerFrame()\n Stats.frameCount++\n this.renderPass = 0\n\n // Loop forever or stop if not started\n if (this.started) requestAnimationFrame(this.render)\n }\n\n /**\n * Render the scene from the given camera, used internally for rendering both the main view,\n * but also shadow maps and dynamic env maps\n * @param camera\n */\n renderWithCamera(camera: Camera, programOverride?: twgl.ProgramInfo) {\n if (!this.gl) return\n this.renderPass++\n\n // Clear the framebuffer and depth buffer\n this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT)\n\n // Do this in every frame since camera can move\n const camMatrix = camera.matrix\n\n // Work out what reflection map to use, if any\n // NOTE: This *not* part of the material because it's too hard to dynamically change\n let reflectMap: WebGLTexture | null = this._envmap?.texture ?? null\n\n // As there is only one dynamic reflection envmap, we can use it across all instances\n // But ONLY set this when the camera is NOT rendering into it!\n if (this.dynamicEnvMap) {\n if (!camera.usedForEnvMap) {\n reflectMap = this.dynamicEnvMap.texture\n }\n }\n\n // The uniforms that are the same for all instances\n const uniforms = {\n u_gamma: this.gamma,\n\n u_worldInverseTranspose: mat4.create(), // Updated per instance\n u_worldViewProjection: mat4.create(), // Updated per instance\n u_view: mat4.invert(mat4.create(), camMatrix),\n u_proj: camera.projectionMatrix,\n u_camPos: camera.position,\n\n u_reflectionMap: reflectMap,\n\n u_shadowMap: this.globalLight.shadowMapTexture,\n u_shadowMatrix: this.globalLight.getShadowMatrix(this.camera) ?? mat4.create(),\n } as UniformSet\n\n // ------------------------------------------------------------------------------\n // RENDER CORE - Draw envmap around the scene first, as a skybox background\n // ------------------------------------------------------------------------------\n if (this._envmap) {\n this._envmap.render(uniforms.u_view, uniforms.u_proj, camera)\n }\n\n // ------------------------------------------------\n // RENDER CORE - Process lighting\n // ------------------------------------------------\n\n // Apply global light to the two programs\n uniforms.u_lightDirGlobal = this.globalLight.uniforms\n\n // Only sort lights if we have more than MAX_LIGHTS, it's expensive!\n if (this.lights.length > MAX_LIGHTS) {\n // Sort lights by distance to camera so we can use the closest ones\n this.lights.sort((lightA, lightB) => {\n const ad = vec3.distance(lightA.position, this.camera.position)\n const bd = vec3.distance(lightB.position, this.camera.position)\n return ad - bd\n })\n }\n\n // Add the point lights into u_lightsPos array up to MAX_LIGHTS\n let lightCount = 0\n for (const light of this.lights) {\n if (lightCount >= MAX_LIGHTS) break\n if (!light.enabled) continue\n\n uniforms[`u_lightsPos[${lightCount++}]`] = light.uniforms\n }\n\n uniforms.u_lightsPosCount = lightCount\n\n // ------------------------------------------------\n // RENDER CORE - Draw all standard opaque instances\n // ------------------------------------------------\n if (this.disableCulling) this.gl.disable(this.gl.CULL_FACE)\n else this.gl.enable(this.gl.CULL_FACE)\n this.gl.enable(this.gl.BLEND)\n this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA)\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [_id, instance] of this.instances) {\n instance.render(this.gl, uniforms, programOverride)\n\n // Update physics body position from instance only on first render pass\n if (this.renderPass == 1) instance.updateFromPhysicsBody()\n }\n\n // ------------------------------------------------\n // RENDER CORE - Draw all transparent instances\n // ------------------------------------------------\n\n // Sort transparent instances by distance to camera\n // TODO: Maybe remove this in scenes with lots of transparent instances?\n const instancesTransArray = Array.from(this.instancesTrans.values())\n instancesTransArray.sort((a, b) => {\n const ad = Tuples.distance(a.position ?? [0, 0, 0], this.camera.position)\n const bd = Tuples.distance(b.position ?? [0, 0, 0], this.camera.position)\n return bd - ad\n })\n\n this.gl.disable(this.gl.CULL_FACE)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const instance of instancesTransArray) {\n instance.render(this.gl, uniforms, programOverride)\n\n // Update physics body position from instance only on first render pass\n if (this.renderPass == 1) instance.updateFromPhysicsBody()\n }\n\n // ------------------------------------------------\n // RENDER CORE - Draw all particle systems\n // ------------------------------------------------\n this.gl.depthMask(false)\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [_id, instance] of this.instancesParticles) {\n instance.render(this.gl, uniforms, programOverride)\n }\n\n this.gl.depthMask(true)\n }\n\n /**\n * Start the rendering loop, without calling this nothing will render\n */\n start() {\n log.info('🚀 Starting main GSOTS render loop!')\n\n this.hud.hideLoading()\n this.started = true\n // Restart the render loop\n requestAnimationFrame(this.render)\n }\n\n /**\n * Stop the rendering loop\n */\n stop() {\n log.info('🛑 Stopping main GSOTS render loop')\n\n this.started = false\n }\n\n /**\n * Set the log level for the library\n * @param level - Log level to set, default is 'info'\n */\n setLogLevel(level: log.LogLevelNames) {\n log.setLevel(level)\n }\n\n /**\n * Resize the canvas & viewport to match the size of the HTML element that contains it\n * @param viewportOnly - Only resize the GL viewport, not the canvas, default false\n */\n resize(viewportOnly = false) {\n const canvas = this.gl.canvas\n\n if (!viewportOnly) twgl.resizeCanvasToDisplaySize(canvas)\n\n this.gl.viewport(0, 0, canvas.width, canvas.height)\n this.camera.aspectRatio = canvas.width / canvas.height\n\n log.info(\n `📐 RESIZE Internal: ${canvas.width} x ${canvas.height}, display: ${canvas.clientWidth} x ${canvas.clientHeight}`,\n )\n }\n\n /**\n * Internal function to add an instance to the scene\n */\n private addInstance(instance: Instance, material: Material) {\n if (material.opacity !== undefined && material.opacity < 1) {\n this.instancesTrans.set(instance.id, instance)\n } else {\n this.instances.set(instance.id, instance)\n }\n }\n\n /**\n * Model loader, loads an OBJ model from a file via URL or path and adds it to the cache\n * This is preferred over calling Model.parse() directly\n * @param path Base path to the model file, e.g. './renderable/'\n * @param fileName Name of the model file, e.g 'teapot.obj'\n * @param filterTextures Apply texture filtering as materials are loaded\n * @param flipTextureY Flip the Y coordinate of the texture\n */\n async loadModel(path: string, fileName: string, filterTextures = true, flipY = false, flipUV = true) {\n const modelName = fileName.split('.')[0]\n\n // Check if model is already loaded\n if (ModelCache.instance.get(modelName, false)) {\n log.warn(`⚠️ Model '${modelName}' already loaded, skipping`)\n return\n }\n\n // Load the model and always flip the UV\n const model = await Model.parse(path, fileName, filterTextures, flipY, flipUV)\n\n ModelCache.instance.add(model)\n }\n\n /**\n * Add or replace a named camera to the scene\n * @param name Name of the camera\n * @param camera Camera instance\n */\n addCamera(name: string, camera: Camera) {\n this.cameras.set(name, camera)\n }\n\n /**\n * Get a camera by name\n * @param name Name of the camera\n */\n getCamera(name: string) {\n return this.cameras.get(name)\n }\n\n /**\n * Set the active camera, rendering will switch to this camera's view\n * @param name Name of the camera to set as active\n */\n setActiveCamera(name: string) {\n if (name == this.activeCameraName) return\n\n const camera = this.cameras.get(name)\n if (!camera) {\n throw new Error(`💥 Unable to set active camera to '${name}', camera not found`)\n }\n\n this.camera.active = false\n this._camera = camera\n this.camera.active = true\n this.activeCameraName = name\n\n log.info(`📷 Active camera switched to '${name}'`)\n }\n\n // ==========================================================================\n // Methods to create new instances of renderable objects & things\n // ==========================================================================\n\n /**\n * Create a new model instance, which should have been previously loaded into the cache\n * @param modelName - Name of the model previously loaded into the cache, don't include the file extension\n */\n createModelInstance(modelName: string) {\n const model = ModelCache.instance.get(modelName)\n if (!model) {\n throw new Error(`💥 Unable to create model instance for ${modelName}`)\n }\n\n const instance = new Instance(model)\n this.instances.set(instance.id, instance)\n Stats.triangles += model.triangleCount\n Stats.instances++\n\n return instance\n }\n\n /**\n * Create an instance of a primitive sphere\n * @param material - Material to apply to the sphere\n * @param radius - Radius of the sphere\n * @param subdivisionsH - Number of subdivisions along the horizontal\n * @param subdivisionsV - Number of subdivisions along the vertical\n */\n createSphereInstance(material: Material, radius = 5, subdivisionsH = 16, subdivisionsV = 8) {\n const sphere = new PrimitiveSphere(this.gl, radius, subdivisionsH, subdivisionsV)\n sphere.material = material\n\n const instance = new Instance(sphere)\n this.addInstance(instance, material)\n Stats.triangles += sphere.triangleCount\n Stats.instances++\n\n log.debug(`🟢 Created sphere instance, r:${radius}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive plane\n * @param material - Material to apply to the plane\n * @param width - Width of the plane\n * @param height - Height of the plane\n * @param subdivisionsW - Number of subdivisions along the width\n * @param subdivisionsH - Number of subdivisions along the height\n * @param tiling - Number of times to tile the texture over the plane\n */\n createPlaneInstance(material: Material, width = 5, height = 5, subdivisionsW = 1, subdivisionsH = 1, tiling = 1) {\n const plane = new PrimitivePlane(this.gl, width, height, subdivisionsW, subdivisionsH, tiling)\n plane.material = material\n\n const instance = new Instance(plane)\n this.addInstance(instance, material)\n Stats.triangles += plane.triangleCount\n Stats.instances++\n\n log.debug(`🟨 Created plane instance, w:${width} h:${height}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive cube\n */\n createCubeInstance(material: Material, size = 5, tilingFactor?: number) {\n const cube = new PrimitiveCube(this.gl, size, tilingFactor)\n cube.material = material\n\n const instance = new Instance(cube)\n this.addInstance(instance, material)\n Stats.triangles += cube.triangleCount\n Stats.instances++\n\n log.debug(`📦 Created cube instance, size:${size}`)\n\n return instance\n }\n\n /**\n * Create an instance of a primitive cylinder\n */\n createCylinderInstance(material: Material, r = 2, h = 5, subdivisionsR = 16, subdivisionsH = 1, caps = true) {\n const cyl = new PrimitiveCylinder(this.gl, r, h, subdivisionsR, subdivisionsH, caps)\n cyl.material = material\n\n const instance = new Instance(cyl)\n this.addInstance(instance, material)\n Stats.triangles += cyl.triangleCount\n Stats.instances++\n\n log.debug(`🛢️ Created cylinder instance, r:${r}`)\n\n return instance\n }\n\n /**\n * Create an instance of a billboard/sprite in the scene\n * @param textureUrl - Path to the texture image file to use for the billboard\n * @param width - Width of the billboard (default: 5)\n * @param height - Height of the billboard (default: 5)\n * @param type - Type of billboard to create (default: CYLINDRICAL)\n */\n createBillboardInstance(material: Material, size = 5, type = BillboardType.CYLINDRICAL) {\n const billboard = new Billboard(this.gl, type, material, size)\n\n const instance = new Instance(billboard)\n\n this.addInstance(instance, material)\n\n Stats.triangles += 2\n Stats.instances++\n\n log.debug(`🚧 Created billboard instance of type: ${type} size: ${size}`)\n\n return instance\n }\n\n /**\n * Create a new point light in the scene\n * @param position - Position of the light\n * @param colour - Colour of the light, defaults to white\n * @param intensity - Intensity of the light\n * @returns The new light object\n */\n createPointLight(position: XYZ, colour: RGB = [1, 1, 1], intensity = 1) {\n const light = new LightPoint(position, colour)\n light.position = position\n light.colour = colour\n\n // A very simple scaling of the light attenuation\n // Users can still set the attenuation manually if they want\n light.constant /= intensity\n light.linear /= intensity\n light.quad /= intensity\n\n this.lights.push(light)\n\n log.debug(`🔆 Created point light, pos:${position} col:${colour} int:${intensity}`)\n\n return light\n }\n\n /**\n * Create a new particle system in the scene\n * @param maxParticles Maximum number of particles to allow in the system\n * @param baseSize Base size of the particles, default 2\n * @returns Both the instance and the particle system\n */\n createParticleSystem(maxParticles = 1000, baseSize = 2) {\n const particleSystem = new ParticleSystem(this.gl, maxParticles, baseSize)\n\n const instance = new Instance(particleSystem)\n instance.castShadow = false\n\n this.instancesParticles.set(instance.id, instance)\n Stats.instances++\n\n log.debug(`✨ Created particle system`)\n\n return { instance, particleSystem }\n }\n\n /**\n * Set the EnvironmentMap for the scene, will overwrite any existing envmap.\n * This will enable static reflections and create a 'skybox' around the scene\n * @param textureURLs - Array of 6 texture URLs to use for the map, in the order: +X, -X, +Y, -Y, +Z, -Z\n */\n setEnvmap(renderAsBackground = false, ...textureURLs: string[]) {\n this._envmap = new EnvironmentMap(this.gl, textureURLs)\n this._envmap.renderAsBackground = renderAsBackground\n }\n\n /**\n * Remove any current EnvironmentMap from the scene\n */\n removeEnvmap() {\n this._envmap = undefined\n }\n\n /**\n * Set and create a dynamic environment map which will enable dynamic/realtime reflections\n * @param position - Position to render reflections from\n * @param size - Size of the map to render, note higher sizes will come with a big performance hit\n */\n setDynamicEnvmap(position: XYZ, size = 256, renderDistance = 500) {\n this.dynamicEnvMap = new DynamicEnvironmentMap(this.gl, size, position, renderDistance)\n }\n\n /**\n * Remove instance from the scene, it will no longer be rendered\n * @param instance - Instance to remove\n */\n removeInstance(instance: Instance) {\n if (!instance) return\n\n if (instance.renderable instanceof ParticleSystem) {\n this.instancesParticles.delete(instance.id)\n return\n }\n\n this.instances.delete(instance.id)\n this.instancesTrans.delete(instance.id)\n }\n\n /**\n * Remove all instances from the scene\n */\n removeAllInstances() {\n this.instances.clear()\n this.instancesTrans.clear()\n this.instancesParticles.clear()\n }\n\n /**\n * Use a custom shader for post effects, user must provide their own shader\n * @param shaderCode - GLSL shader code for the post effect\n */\n setEffectCustom(shaderCode: string) {\n this.postEffects = new PostEffects(this.gl, shaderCode)\n log.info(`🌈 Post effects shader added`)\n }\n\n /**\n * Use bulit-in scanlines post effect shader\n * @param density - Density of the scanlines, default 1.5\n * @param opacity - Opacity of the scanlines, default 0.5\n * @param noise - Noise level, default 0.2\n * @param flicker - Flicker ammount, default 0.015\n */\n setEffectScanlines(density = 1.5, opacity = 0.5, noise = 0.2, flicker = 0.015) {\n this.postEffects = PostEffects.scanlines(this.gl, density, opacity, noise, flicker)\n\n log.info(`🌈 Post effects scanline shader added`)\n }\n\n /**\n * Use bulit-in glitch post effect shader\n * @param amount - Amount of glitch, default 0.01\n */\n setEffectGlitch(amount = 0.01) {\n this.postEffects = PostEffects.glitch(this.gl, amount)\n\n log.info(`🌈 Post effects glitch shader added`)\n }\n\n /**\n * Use bulit-in noise post effect shader\n * @param amount - Amount of noise, default 0.1\n * @param speed - Speed of noise pattern, default 5.0\n */\n setEffectNoise(amount = 0.2, speed = 5.0) {\n this.postEffects = PostEffects.noise(this.gl, amount, speed)\n\n log.info(`🌈 Post effects noise shader added`)\n }\n\n /**\n * Use bulit-in duotone post effect shader for monotone images\n * @param colour1 - First colour, default [0.15, 0.09, 0.309]\n * @param colour2 - Second colour, default [0.96, 0.39, 0.407]\n * @param contrast - Contrast, default 1.5\n */\n setEffectDuotone(colour1: RGB = [0.15, 0.09, 0.309], colour2: RGB = [0.96, 0.39, 0.407], contrast = 1.5) {\n this.postEffects = PostEffects.duotone(this.gl, colour1, colour2, contrast)\n\n log.info(`🌈 Post effects monochrome shader added`)\n }\n\n /**\n * Use bulit-in contrast post effect shader, which reduces the image to two solid colours\n * @param threshold\n * @param darkColour\n * @param lightColour\n */\n setEffectContrast(threshold = 0.2, darkColour: RGB = [0, 0, 0], lightColour: RGB = [1, 1, 1]) {\n this.postEffects = PostEffects.contrast(this.gl, threshold, darkColour, lightColour)\n\n log.info(`🌈 Post effects monochrome shader added`)\n }\n\n /**\n * Remove any post effects shader\n */\n removeEffect() {\n this.postEffects = undefined\n }\n\n /**\n * Build a instance of a custom renderable from a builder and add it to the scene\n * @param builder Builder with\n */\n createCustomInstance(builder: RenderableBuilder) {\n const renderable = builder.build(this.gl)\n const instance = new Instance(renderable)\n\n this.instances.set(instance.id, instance)\n Stats.triangles += renderable.triangleCount\n Stats.instances++\n\n log.debug(`🗿 Created a custom renderable instance`)\n\n return instance\n }\n}\n","/* @license twgl.js 5.5.3 Copyright (c) 2015, Gregg Tavares All Rights Reserved.\nAvailable via the MIT license.\nsee: http://github.com/greggman/twgl.js for details */\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n *\n * Vec3 math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new Vec3. In other words you can do this\n *\n * var v = v3.cross(v1, v2); // Creates a new Vec3 with the cross product of v1 x v2.\n *\n * or\n *\n * var v = v3.create();\n * v3.cross(v1, v2, v); // Puts the cross product of v1 x v2 in v\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any vector as the destination. So for example\n *\n * v3.cross(v1, v2, v1); // Puts the cross product of v1 x v2 in v1\n *\n * @module twgl/v3\n */\n\nlet VecType = Float32Array;\n\n/**\n * A JavaScript array with 3 values or a Float32Array with 3 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/v3.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Vec3\n * @memberOf module:twgl/v3\n */\n\n/**\n * Sets the type this library creates for a Vec3\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Vec3\n * @memberOf module:twgl/v3\n */\nfunction setDefaultType$1(ctor) {\n const oldType = VecType;\n VecType = ctor;\n return oldType;\n}\n\n/**\n * Creates a vec3; may be called with x, y, z to set initial values.\n * @param {number} [x] Initial x value.\n * @param {number} [y] Initial y value.\n * @param {number} [z] Initial z value.\n * @return {module:twgl/v3.Vec3} the created vector\n * @memberOf module:twgl/v3\n */\nfunction create$1(x, y, z) {\n const dst = new VecType(3);\n if (x) {\n dst[0] = x;\n }\n if (y) {\n dst[1] = y;\n }\n if (z) {\n dst[2] = z;\n }\n return dst;\n}\n\n/**\n * Adds two vectors; assumes a and b have the same dimension.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector tha tis the sum of a and b.\n * @memberOf module:twgl/v3\n */\nfunction add(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + b[0];\n dst[1] = a[1] + b[1];\n dst[2] = a[2] + b[2];\n\n return dst;\n}\n\n/**\n * Subtracts two vectors.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A vector that is the difference of a and b.\n * @memberOf module:twgl/v3\n */\nfunction subtract(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] - b[0];\n dst[1] = a[1] - b[1];\n dst[2] = a[2] - b[2];\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {number} t Interpolation coefficient.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerp(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t * (b[0] - a[0]);\n dst[1] = a[1] + t * (b[1] - a[1]);\n dst[2] = a[2] + t * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Performs linear interpolation on two vectors.\n * Given vectors a and b and interpolation coefficient vector t, returns\n * a + t * (b - a).\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} t Interpolation coefficients vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} the linear interpolated result.\n * @memberOf module:twgl/v3\n */\nfunction lerpV(a, b, t, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] + t[0] * (b[0] - a[0]);\n dst[1] = a[1] + t[1] * (b[1] - a[1]);\n dst[2] = a[2] + t[2] * (b[2] - a[2]);\n\n return dst;\n}\n\n/**\n * Return max values of two vectors.\n * Given vectors a and b returns\n * [max(a[0], b[0]), max(a[1], b[1]), max(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The max components vector.\n * @memberOf module:twgl/v3\n */\nfunction max(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.max(a[0], b[0]);\n dst[1] = Math.max(a[1], b[1]);\n dst[2] = Math.max(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Return min values of two vectors.\n * Given vectors a and b returns\n * [min(a[0], b[0]), min(a[1], b[1]), min(a[2], b[2])].\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The min components vector.\n * @memberOf module:twgl/v3\n */\nfunction min(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = Math.min(a[0], b[0]);\n dst[1] = Math.min(a[1], b[1]);\n dst[2] = Math.min(a[2], b[2]);\n\n return dst;\n}\n\n/**\n * Multiplies a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction mulScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] * k;\n dst[1] = v[1] * k;\n dst[2] = v[2] * k;\n\n return dst;\n}\n\n/**\n * Divides a vector by a scalar.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {number} k The scalar.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The scaled vector.\n * @memberOf module:twgl/v3\n */\nfunction divScalar(v, k, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0] / k;\n dst[1] = v[1] / k;\n dst[2] = v[2] / k;\n\n return dst;\n}\n\n/**\n * Computes the cross product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of a cross b.\n * @memberOf module:twgl/v3\n */\nfunction cross(a, b, dst) {\n dst = dst || new VecType(3);\n\n const t1 = a[2] * b[0] - a[0] * b[2];\n const t2 = a[0] * b[1] - a[1] * b[0];\n dst[0] = a[1] * b[2] - a[2] * b[1];\n dst[1] = t1;\n dst[2] = t2;\n\n return dst;\n}\n\n/**\n * Computes the dot product of two vectors; assumes both vectors have\n * three entries.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @return {number} dot product\n * @memberOf module:twgl/v3\n */\nfunction dot(a, b) {\n return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);\n}\n\n/**\n * Computes the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} length of vector.\n * @memberOf module:twgl/v3\n */\nfunction length$1(v) {\n return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n}\n\n/**\n * Computes the square of the length of vector\n * @param {module:twgl/v3.Vec3} v vector.\n * @return {number} square of the length of vector.\n * @memberOf module:twgl/v3\n */\nfunction lengthSq(v) {\n return v[0] * v[0] + v[1] * v[1] + v[2] * v[2];\n}\n\n/**\n * Computes the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distance(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/**\n * Computes the square of the distance between 2 points\n * @param {module:twgl/v3.Vec3} a vector.\n * @param {module:twgl/v3.Vec3} b vector.\n * @return {number} square of the distance between a and b\n * @memberOf module:twgl/v3\n */\nfunction distanceSq(a, b) {\n const dx = a[0] - b[0];\n const dy = a[1] - b[1];\n const dz = a[2] - b[2];\n return dx * dx + dy * dy + dz * dz;\n}\n\n/**\n * Divides a vector by its Euclidean length and returns the quotient.\n * @param {module:twgl/v3.Vec3} a The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The normalized vector.\n * @memberOf module:twgl/v3\n */\nfunction normalize(a, dst) {\n dst = dst || new VecType(3);\n\n const lenSq = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];\n const len = Math.sqrt(lenSq);\n if (len > 0.00001) {\n dst[0] = a[0] / len;\n dst[1] = a[1] / len;\n dst[2] = a[2] / len;\n } else {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = 0;\n }\n\n return dst;\n}\n\n/**\n * Negates a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} -v.\n * @memberOf module:twgl/v3\n */\nfunction negate$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = -v[0];\n dst[1] = -v[1];\n dst[2] = -v[2];\n\n return dst;\n}\n\n/**\n * Copies a vector.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} A copy of v.\n * @memberOf module:twgl/v3\n */\nfunction copy$1(v, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = v[0];\n dst[1] = v[1];\n dst[2] = v[2];\n\n return dst;\n}\n\n/**\n * Multiplies a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of products of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction multiply$1(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] * b[0];\n dst[1] = a[1] * b[1];\n dst[2] = a[2] * b[2];\n\n return dst;\n}\n\n/**\n * Divides a vector by another vector (component-wise); assumes a and\n * b have the same length.\n * @param {module:twgl/v3.Vec3} a Operand vector.\n * @param {module:twgl/v3.Vec3} b Operand vector.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not new one is created.\n * @return {module:twgl/v3.Vec3} The vector of quotients of entries of a and\n * b.\n * @memberOf module:twgl/v3\n */\nfunction divide(a, b, dst) {\n dst = dst || new VecType(3);\n\n dst[0] = a[0] / b[0];\n dst[1] = a[1] / b[1];\n dst[2] = a[2] / b[2];\n\n return dst;\n}\n\nvar v3 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n add: add,\n copy: copy$1,\n create: create$1,\n cross: cross,\n distance: distance,\n distanceSq: distanceSq,\n divide: divide,\n divScalar: divScalar,\n dot: dot,\n lerp: lerp,\n lerpV: lerpV,\n length: length$1,\n lengthSq: lengthSq,\n max: max,\n min: min,\n mulScalar: mulScalar,\n multiply: multiply$1,\n negate: negate$1,\n normalize: normalize,\n setDefaultType: setDefaultType$1,\n subtract: subtract\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * 4x4 Matrix math math functions.\n *\n * Almost all functions take an optional `dst` argument. If it is not passed in the\n * functions will create a new matrix. In other words you can do this\n *\n * const mat = m4.translation([1, 2, 3]); // Creates a new translation matrix\n *\n * or\n *\n * const mat = m4.create();\n * m4.translation([1, 2, 3], mat); // Puts translation matrix in mat.\n *\n * The first style is often easier but depending on where it's used it generates garbage where\n * as there is almost never allocation with the second style.\n *\n * It is always save to pass any matrix as the destination. So for example\n *\n * const mat = m4.identity();\n * const trans = m4.translation([1, 2, 3]);\n * m4.multiply(mat, trans, mat); // Multiplies mat * trans and puts result in mat.\n *\n * @module twgl/m4\n */\nlet MatType = Float32Array;\n\n/**\n * A JavaScript array with 16 values or a Float32Array with 16 values.\n * When created by the library will create the default type which is `Float32Array`\n * but can be set by calling {@link module:twgl/m4.setDefaultType}.\n * @typedef {(number[]|Float32Array)} Mat4\n * @memberOf module:twgl/m4\n */\n\n/**\n * Sets the type this library creates for a Mat4\n * @param {constructor} ctor the constructor for the type. Either `Float32Array` or `Array`\n * @return {constructor} previous constructor for Mat4\n * @memberOf module:twgl/m4\n */\nfunction setDefaultType(ctor) {\n const oldType = MatType;\n MatType = ctor;\n return oldType;\n}\n\n/**\n * Negates a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} -m.\n * @memberOf module:twgl/m4\n */\nfunction negate(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = -m[ 0];\n dst[ 1] = -m[ 1];\n dst[ 2] = -m[ 2];\n dst[ 3] = -m[ 3];\n dst[ 4] = -m[ 4];\n dst[ 5] = -m[ 5];\n dst[ 6] = -m[ 6];\n dst[ 7] = -m[ 7];\n dst[ 8] = -m[ 8];\n dst[ 9] = -m[ 9];\n dst[10] = -m[10];\n dst[11] = -m[11];\n dst[12] = -m[12];\n dst[13] = -m[13];\n dst[14] = -m[14];\n dst[15] = -m[15];\n\n return dst;\n}\n\n/**\n * Creates a matrix.\n * @return {module:twgl/m4.Mat4} A new matrix.\n * @memberOf module:twgl/m4\n */\nfunction create() {\n return new MatType(16).fill(0);\n}\n\n/**\n * Copies a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] The matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A copy of m.\n * @memberOf module:twgl/m4\n */\nfunction copy(m, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n\n return dst;\n}\n\n/**\n * Creates an n-by-n identity matrix.\n *\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} An n-by-n identity matrix.\n * @memberOf module:twgl/m4\n */\nfunction identity(dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Takes the transpose of a matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The transpose of m.\n * @memberOf module:twgl/m4\n */\n function transpose(m, dst) {\n dst = dst || new MatType(16);\n if (dst === m) {\n let t;\n\n t = m[1];\n m[1] = m[4];\n m[4] = t;\n\n t = m[2];\n m[2] = m[8];\n m[8] = t;\n\n t = m[3];\n m[3] = m[12];\n m[12] = t;\n\n t = m[6];\n m[6] = m[9];\n m[9] = t;\n\n t = m[7];\n m[7] = m[13];\n m[13] = t;\n\n t = m[11];\n m[11] = m[14];\n m[14] = t;\n return dst;\n }\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n dst[ 0] = m00;\n dst[ 1] = m10;\n dst[ 2] = m20;\n dst[ 3] = m30;\n dst[ 4] = m01;\n dst[ 5] = m11;\n dst[ 6] = m21;\n dst[ 7] = m31;\n dst[ 8] = m02;\n dst[ 9] = m12;\n dst[10] = m22;\n dst[11] = m32;\n dst[12] = m03;\n dst[13] = m13;\n dst[14] = m23;\n dst[15] = m33;\n\n return dst;\n}\n\n/**\n * Computes the inverse of a 4-by-4 matrix.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The inverse of m.\n * @memberOf module:twgl/m4\n */\nfunction inverse(m, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n const tmp_0 = m22 * m33;\n const tmp_1 = m32 * m23;\n const tmp_2 = m12 * m33;\n const tmp_3 = m32 * m13;\n const tmp_4 = m12 * m23;\n const tmp_5 = m22 * m13;\n const tmp_6 = m02 * m33;\n const tmp_7 = m32 * m03;\n const tmp_8 = m02 * m23;\n const tmp_9 = m22 * m03;\n const tmp_10 = m02 * m13;\n const tmp_11 = m12 * m03;\n const tmp_12 = m20 * m31;\n const tmp_13 = m30 * m21;\n const tmp_14 = m10 * m31;\n const tmp_15 = m30 * m11;\n const tmp_16 = m10 * m21;\n const tmp_17 = m20 * m11;\n const tmp_18 = m00 * m31;\n const tmp_19 = m30 * m01;\n const tmp_20 = m00 * m21;\n const tmp_21 = m20 * m01;\n const tmp_22 = m00 * m11;\n const tmp_23 = m10 * m01;\n\n const t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -\n (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\n const t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -\n (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\n const t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -\n (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\n const t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -\n (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\n\n const d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\n\n dst[ 0] = d * t0;\n dst[ 1] = d * t1;\n dst[ 2] = d * t2;\n dst[ 3] = d * t3;\n dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -\n (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));\n dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -\n (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));\n dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -\n (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));\n dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -\n (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));\n dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -\n (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));\n dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -\n (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));\n dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -\n (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));\n dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -\n (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));\n dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -\n (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));\n dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -\n (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));\n dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -\n (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));\n dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -\n (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));\n\n return dst;\n}\n\n/**\n * Multiplies two 4-by-4 matrices with a on the left and b on the right\n * @param {module:twgl/m4.Mat4} a The matrix on the left.\n * @param {module:twgl/m4.Mat4} b The matrix on the right.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix product of a and b.\n * @memberOf module:twgl/m4\n */\nfunction multiply(a, b, dst) {\n dst = dst || new MatType(16);\n\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[ 4 + 0];\n const a11 = a[ 4 + 1];\n const a12 = a[ 4 + 2];\n const a13 = a[ 4 + 3];\n const a20 = a[ 8 + 0];\n const a21 = a[ 8 + 1];\n const a22 = a[ 8 + 2];\n const a23 = a[ 8 + 3];\n const a30 = a[12 + 0];\n const a31 = a[12 + 1];\n const a32 = a[12 + 2];\n const a33 = a[12 + 3];\n const b00 = b[0];\n const b01 = b[1];\n const b02 = b[2];\n const b03 = b[3];\n const b10 = b[ 4 + 0];\n const b11 = b[ 4 + 1];\n const b12 = b[ 4 + 2];\n const b13 = b[ 4 + 3];\n const b20 = b[ 8 + 0];\n const b21 = b[ 8 + 1];\n const b22 = b[ 8 + 2];\n const b23 = b[ 8 + 3];\n const b30 = b[12 + 0];\n const b31 = b[12 + 1];\n const b32 = b[12 + 2];\n const b33 = b[12 + 3];\n\n dst[ 0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;\n dst[ 1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;\n dst[ 2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;\n dst[ 3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;\n dst[ 4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;\n dst[ 5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;\n dst[ 6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;\n dst[ 7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;\n dst[ 8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;\n dst[ 9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;\n dst[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;\n dst[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;\n dst[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;\n dst[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;\n dst[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;\n dst[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;\n\n return dst;\n}\n\n/**\n * Sets the translation component of a 4-by-4 matrix to the given\n * vector.\n * @param {module:twgl/m4.Mat4} a The matrix.\n * @param {module:twgl/v3.Vec3} v The vector.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with translation set.\n * @memberOf module:twgl/m4\n */\nfunction setTranslation(a, v, dst) {\n dst = dst || identity();\n if (a !== dst) {\n dst[ 0] = a[ 0];\n dst[ 1] = a[ 1];\n dst[ 2] = a[ 2];\n dst[ 3] = a[ 3];\n dst[ 4] = a[ 4];\n dst[ 5] = a[ 5];\n dst[ 6] = a[ 6];\n dst[ 7] = a[ 7];\n dst[ 8] = a[ 8];\n dst[ 9] = a[ 9];\n dst[10] = a[10];\n dst[11] = a[11];\n }\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Returns the translation component of a 4-by-4 matrix as a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} [dst] vector to hold result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The translation component of m.\n * @memberOf module:twgl/m4\n */\nfunction getTranslation(m, dst) {\n dst = dst || create$1();\n dst[0] = m[12];\n dst[1] = m[13];\n dst[2] = m[14];\n return dst;\n}\n\n/**\n * Returns an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @return {module:twgl/v3.Vec3} [dst] vector.\n * @return {module:twgl/v3.Vec3} The axis component of m.\n * @memberOf module:twgl/m4\n */\nfunction getAxis(m, axis, dst) {\n dst = dst || create$1();\n const off = axis * 4;\n dst[0] = m[off + 0];\n dst[1] = m[off + 1];\n dst[2] = m[off + 2];\n return dst;\n}\n\n/**\n * Sets an axis of a 4x4 matrix as a vector with 3 entries\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v the axis vector\n * @param {number} axis The axis 0 = x, 1 = y, 2 = z;\n * @param {module:twgl/m4.Mat4} [dst] The matrix to set. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The matrix with axis set.\n * @memberOf module:twgl/m4\n */\nfunction setAxis(a, v, axis, dst) {\n if (dst !== a) {\n dst = copy(a, dst);\n }\n const off = axis * 4;\n dst[off + 0] = v[0];\n dst[off + 1] = v[1];\n dst[off + 2] = v[2];\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the angular height\n * of the frustum, the aspect ratio, and the near and far clipping planes. The\n * arguments define a frustum extending in the negative z direction. The given\n * angle is the vertical angle of the frustum, and the horizontal angle is\n * determined to produce the given aspect ratio. The arguments near and far are\n * the distances to the near and far clipping planes. Note that near and far\n * are not z coordinates, but rather they are distances along the negative\n * z-axis. The matrix generated sends the viewing frustum to the unit box.\n * We assume a unit box extending from -1 to 1 in the x and y dimensions and\n * from 0 to 1 in the z dimension.\n * @param {number} fieldOfViewYInRadians The camera angle from top to bottom (in radians).\n * @param {number} aspect The aspect ratio width / height.\n * @param {number} zNear The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} zFar The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction perspective(fieldOfViewYInRadians, aspect, zNear, zFar, dst) {\n dst = dst || new MatType(16);\n\n const f = Math.tan(Math.PI * 0.5 - 0.5 * fieldOfViewYInRadians);\n const rangeInv = 1.0 / (zNear - zFar);\n\n dst[0] = f / aspect;\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = f;\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = (zNear + zFar) * rangeInv;\n dst[11] = -1;\n\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = zNear * zFar * rangeInv * 2;\n dst[15] = 0;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 orthogonal transformation matrix given the left, right,\n * bottom, and top dimensions of the near clipping plane as well as the\n * near and far clipping plane distances.\n * @param {number} left Left side of the near clipping plane viewport.\n * @param {number} right Right side of the near clipping plane viewport.\n * @param {number} bottom Bottom of the near clipping plane viewport.\n * @param {number} top Top of the near clipping plane viewport.\n * @param {number} near The depth (negative z coordinate)\n * of the near clipping plane.\n * @param {number} far The depth (negative z coordinate)\n * of the far clipping plane.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective matrix.\n * @memberOf module:twgl/m4\n */\nfunction ortho(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n dst[0] = 2 / (right - left);\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = 2 / (top - bottom);\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = 2 / (near - far);\n dst[11] = 0;\n\n dst[12] = (right + left) / (left - right);\n dst[13] = (top + bottom) / (bottom - top);\n dst[14] = (far + near) / (near - far);\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Computes a 4-by-4 perspective transformation matrix given the left, right,\n * top, bottom, near and far clipping planes. The arguments define a frustum\n * extending in the negative z direction. The arguments near and far are the\n * distances to the near and far clipping planes. Note that near and far are not\n * z coordinates, but rather they are distances along the negative z-axis. The\n * matrix generated sends the viewing frustum to the unit box. We assume a unit\n * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z\n * dimension.\n * @param {number} left The x coordinate of the left plane of the box.\n * @param {number} right The x coordinate of the right plane of the box.\n * @param {number} bottom The y coordinate of the bottom plane of the box.\n * @param {number} top The y coordinate of the right plane of the box.\n * @param {number} near The negative z coordinate of the near plane of the box.\n * @param {number} far The negative z coordinate of the far plane of the box.\n * @param {module:twgl/m4.Mat4} [dst] Output matrix. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The perspective projection matrix.\n * @memberOf module:twgl/m4\n */\nfunction frustum(left, right, bottom, top, near, far, dst) {\n dst = dst || new MatType(16);\n\n const dx = (right - left);\n const dy = (top - bottom);\n const dz = (near - far);\n\n dst[ 0] = 2 * near / dx;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 2 * near / dy;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = (left + right) / dx;\n dst[ 9] = (top + bottom) / dy;\n dst[10] = far / dz;\n dst[11] = -1;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = near * far / dz;\n dst[15] = 0;\n\n return dst;\n}\n\nlet xAxis;\nlet yAxis;\nlet zAxis;\n\n/**\n * Computes a 4-by-4 look-at transformation.\n *\n * This is a matrix which positions the camera itself. If you want\n * a view matrix (a matrix which moves things in front of the camera)\n * take the inverse of this.\n *\n * @param {module:twgl/v3.Vec3} eye The position of the eye.\n * @param {module:twgl/v3.Vec3} target The position meant to be viewed.\n * @param {module:twgl/v3.Vec3} up A vector pointing up.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The look-at matrix.\n * @memberOf module:twgl/m4\n */\nfunction lookAt(eye, target, up, dst) {\n dst = dst || new MatType(16);\n\n xAxis = xAxis || create$1();\n yAxis = yAxis || create$1();\n zAxis = zAxis || create$1();\n\n normalize(\n subtract(eye, target, zAxis), zAxis);\n normalize(cross(up, zAxis, xAxis), xAxis);\n normalize(cross(zAxis, xAxis, yAxis), yAxis);\n\n dst[ 0] = xAxis[0];\n dst[ 1] = xAxis[1];\n dst[ 2] = xAxis[2];\n dst[ 3] = 0;\n dst[ 4] = yAxis[0];\n dst[ 5] = yAxis[1];\n dst[ 6] = yAxis[2];\n dst[ 7] = 0;\n dst[ 8] = zAxis[0];\n dst[ 9] = zAxis[1];\n dst[10] = zAxis[2];\n dst[11] = 0;\n dst[12] = eye[0];\n dst[13] = eye[1];\n dst[14] = eye[2];\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which translates by the given vector v.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translation matrix.\n * @memberOf module:twgl/m4\n */\nfunction translation(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = v[0];\n dst[13] = v[1];\n dst[14] = v[2];\n dst[15] = 1;\n return dst;\n}\n\n/**\n * Translates the given 4-by-4 matrix by the given vector v.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The vector by\n * which to translate.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The translated matrix.\n * @memberOf module:twgl/m4\n */\nfunction translate(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const m30 = m[3 * 4 + 0];\n const m31 = m[3 * 4 + 1];\n const m32 = m[3 * 4 + 2];\n const m33 = m[3 * 4 + 3];\n\n if (m !== dst) {\n dst[ 0] = m00;\n dst[ 1] = m01;\n dst[ 2] = m02;\n dst[ 3] = m03;\n dst[ 4] = m10;\n dst[ 5] = m11;\n dst[ 6] = m12;\n dst[ 7] = m13;\n dst[ 8] = m20;\n dst[ 9] = m21;\n dst[10] = m22;\n dst[11] = m23;\n }\n\n dst[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30;\n dst[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31;\n dst[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32;\n dst[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationX(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = c;\n dst[ 6] = s;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = -s;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the x-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateX(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[4] = c * m10 + s * m20;\n dst[5] = c * m11 + s * m21;\n dst[6] = c * m12 + s * m22;\n dst[7] = c * m13 + s * m23;\n dst[8] = c * m20 - s * m10;\n dst[9] = c * m21 - s * m11;\n dst[10] = c * m22 - s * m12;\n dst[11] = c * m23 - s * m13;\n\n if (m !== dst) {\n dst[ 0] = m[ 0];\n dst[ 1] = m[ 1];\n dst[ 2] = m[ 2];\n dst[ 3] = m[ 3];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationY(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = 0;\n dst[ 2] = -s;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = s;\n dst[ 9] = 0;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the y-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateY(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m20 = m[2 * 4 + 0];\n const m21 = m[2 * 4 + 1];\n const m22 = m[2 * 4 + 2];\n const m23 = m[2 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 - s * m20;\n dst[ 1] = c * m01 - s * m21;\n dst[ 2] = c * m02 - s * m22;\n dst[ 3] = c * m03 - s * m23;\n dst[ 8] = c * m20 + s * m00;\n dst[ 9] = c * m21 + s * m01;\n dst[10] = c * m22 + s * m02;\n dst[11] = c * m23 + s * m03;\n\n if (m !== dst) {\n dst[ 4] = m[ 4];\n dst[ 5] = m[ 5];\n dst[ 6] = m[ 6];\n dst[ 7] = m[ 7];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotation matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotationZ(angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c;\n dst[ 1] = s;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = -s;\n dst[ 5] = c;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the z-axis by the given\n * angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction rotateZ(m, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n const m00 = m[0 * 4 + 0];\n const m01 = m[0 * 4 + 1];\n const m02 = m[0 * 4 + 2];\n const m03 = m[0 * 4 + 3];\n const m10 = m[1 * 4 + 0];\n const m11 = m[1 * 4 + 1];\n const m12 = m[1 * 4 + 2];\n const m13 = m[1 * 4 + 3];\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n\n dst[ 0] = c * m00 + s * m10;\n dst[ 1] = c * m01 + s * m11;\n dst[ 2] = c * m02 + s * m12;\n dst[ 3] = c * m03 + s * m13;\n dst[ 4] = c * m10 - s * m00;\n dst[ 5] = c * m11 - s * m01;\n dst[ 6] = c * m12 - s * m02;\n dst[ 7] = c * m13 - s * m03;\n\n if (m !== dst) {\n dst[ 8] = m[ 8];\n dst[ 9] = m[ 9];\n dst[10] = m[10];\n dst[11] = m[11];\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which rotates around the given axis by the given\n * angle.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} A matrix which rotates angle radians\n * around the axis.\n * @memberOf module:twgl/m4\n */\nfunction axisRotation(axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n dst[ 0] = xx + (1 - xx) * c;\n dst[ 1] = x * y * oneMinusCosine + z * s;\n dst[ 2] = x * z * oneMinusCosine - y * s;\n dst[ 3] = 0;\n dst[ 4] = x * y * oneMinusCosine - z * s;\n dst[ 5] = yy + (1 - yy) * c;\n dst[ 6] = y * z * oneMinusCosine + x * s;\n dst[ 7] = 0;\n dst[ 8] = x * z * oneMinusCosine + y * s;\n dst[ 9] = y * z * oneMinusCosine - x * s;\n dst[10] = zz + (1 - zz) * c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Rotates the given 4-by-4 matrix around the given axis by the\n * given angle.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} axis The axis\n * about which to rotate.\n * @param {number} angleInRadians The angle by which to rotate (in radians).\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The rotated matrix.\n * @memberOf module:twgl/m4\n */\nfunction axisRotate(m, axis, angleInRadians, dst) {\n dst = dst || new MatType(16);\n\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n const n = Math.sqrt(x * x + y * y + z * z);\n x /= n;\n y /= n;\n z /= n;\n const xx = x * x;\n const yy = y * y;\n const zz = z * z;\n const c = Math.cos(angleInRadians);\n const s = Math.sin(angleInRadians);\n const oneMinusCosine = 1 - c;\n\n const r00 = xx + (1 - xx) * c;\n const r01 = x * y * oneMinusCosine + z * s;\n const r02 = x * z * oneMinusCosine - y * s;\n const r10 = x * y * oneMinusCosine - z * s;\n const r11 = yy + (1 - yy) * c;\n const r12 = y * z * oneMinusCosine + x * s;\n const r20 = x * z * oneMinusCosine + y * s;\n const r21 = y * z * oneMinusCosine - x * s;\n const r22 = zz + (1 - zz) * c;\n\n const m00 = m[0];\n const m01 = m[1];\n const m02 = m[2];\n const m03 = m[3];\n const m10 = m[4];\n const m11 = m[5];\n const m12 = m[6];\n const m13 = m[7];\n const m20 = m[8];\n const m21 = m[9];\n const m22 = m[10];\n const m23 = m[11];\n\n dst[ 0] = r00 * m00 + r01 * m10 + r02 * m20;\n dst[ 1] = r00 * m01 + r01 * m11 + r02 * m21;\n dst[ 2] = r00 * m02 + r01 * m12 + r02 * m22;\n dst[ 3] = r00 * m03 + r01 * m13 + r02 * m23;\n dst[ 4] = r10 * m00 + r11 * m10 + r12 * m20;\n dst[ 5] = r10 * m01 + r11 * m11 + r12 * m21;\n dst[ 6] = r10 * m02 + r11 * m12 + r12 * m22;\n dst[ 7] = r10 * m03 + r11 * m13 + r12 * m23;\n dst[ 8] = r20 * m00 + r21 * m10 + r22 * m20;\n dst[ 9] = r20 * m01 + r21 * m11 + r22 * m21;\n dst[10] = r20 * m02 + r21 * m12 + r22 * m22;\n dst[11] = r20 * m03 + r21 * m13 + r22 * m23;\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Creates a 4-by-4 matrix which scales in each dimension by an amount given by\n * the corresponding entry in the given vector; assumes the vector has three\n * entries.\n * @param {module:twgl/v3.Vec3} v A vector of\n * three entries specifying the factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaling matrix.\n * @memberOf module:twgl/m4\n */\nfunction scaling(v, dst) {\n dst = dst || new MatType(16);\n\n dst[ 0] = v[0];\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = v[1];\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = v[2];\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return dst;\n}\n\n/**\n * Scales the given 4-by-4 matrix in each dimension by an amount\n * given by the corresponding entry in the given vector; assumes the vector has\n * three entries.\n * @param {module:twgl/m4.Mat4} m The matrix to be modified.\n * @param {module:twgl/v3.Vec3} v A vector of three entries specifying the\n * factor by which to scale in each dimension.\n * @param {module:twgl/m4.Mat4} [dst] matrix to hold result. If not passed a new one is created.\n * @return {module:twgl/m4.Mat4} The scaled matrix.\n * @memberOf module:twgl/m4\n */\nfunction scale(m, v, dst) {\n dst = dst || new MatType(16);\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[ 0] = v0 * m[0 * 4 + 0];\n dst[ 1] = v0 * m[0 * 4 + 1];\n dst[ 2] = v0 * m[0 * 4 + 2];\n dst[ 3] = v0 * m[0 * 4 + 3];\n dst[ 4] = v1 * m[1 * 4 + 0];\n dst[ 5] = v1 * m[1 * 4 + 1];\n dst[ 6] = v1 * m[1 * 4 + 2];\n dst[ 7] = v1 * m[1 * 4 + 3];\n dst[ 8] = v2 * m[2 * 4 + 0];\n dst[ 9] = v2 * m[2 * 4 + 1];\n dst[10] = v2 * m[2 * 4 + 2];\n dst[11] = v2 * m[2 * 4 + 3];\n\n if (m !== dst) {\n dst[12] = m[12];\n dst[13] = m[13];\n dst[14] = m[14];\n dst[15] = m[15];\n }\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries,\n * interprets the vector as a point, transforms that point by the matrix, and\n * returns the result as a vector with 3 entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The point.\n * @param {module:twgl/v3.Vec3} [dst] optional vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed point.\n * @memberOf module:twgl/m4\n */\nfunction transformPoint(m, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n const d = v0 * m[0 * 4 + 3] + v1 * m[1 * 4 + 3] + v2 * m[2 * 4 + 3] + m[3 * 4 + 3];\n\n dst[0] = (v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0] + m[3 * 4 + 0]) / d;\n dst[1] = (v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1] + m[3 * 4 + 1]) / d;\n dst[2] = (v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2] + m[3 * 4 + 2]) / d;\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a\n * direction, transforms that direction by the matrix, and returns the result;\n * assumes the transformation of 3-dimensional space represented by the matrix\n * is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The direction.\n * @param {module:twgl/v3.Vec3} [dst] optional Vec3 to store result. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed direction.\n * @memberOf module:twgl/m4\n */\nfunction transformDirection(m, v, dst) {\n dst = dst || create$1();\n\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * m[0 * 4 + 0] + v1 * m[1 * 4 + 0] + v2 * m[2 * 4 + 0];\n dst[1] = v0 * m[0 * 4 + 1] + v1 * m[1 * 4 + 1] + v2 * m[2 * 4 + 1];\n dst[2] = v0 * m[0 * 4 + 2] + v1 * m[1 * 4 + 2] + v2 * m[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector\n * as a normal to a surface, and computes a vector which is normal upon\n * transforming that surface by the matrix. The effect of this function is the\n * same as transforming v (as a direction) by the inverse-transpose of m. This\n * function assumes the transformation of 3-dimensional space represented by the\n * matrix is parallel-preserving, i.e. any combination of rotation, scaling and\n * translation, but not a perspective distortion. Returns a vector with 3\n * entries.\n * @param {module:twgl/m4.Mat4} m The matrix.\n * @param {module:twgl/v3.Vec3} v The normal.\n * @param {module:twgl/v3.Vec3} [dst] The direction. If not passed a new one is created.\n * @return {module:twgl/v3.Vec3} The transformed normal.\n * @memberOf module:twgl/m4\n */\nfunction transformNormal$1(m, v, dst) {\n dst = dst || create$1();\n const mi = inverse(m);\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\nvar m4 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n axisRotate: axisRotate,\n axisRotation: axisRotation,\n copy: copy,\n create: create,\n frustum: frustum,\n getAxis: getAxis,\n getTranslation: getTranslation,\n identity: identity,\n inverse: inverse,\n lookAt: lookAt,\n multiply: multiply,\n negate: negate,\n ortho: ortho,\n perspective: perspective,\n rotateX: rotateX,\n rotateY: rotateY,\n rotateZ: rotateZ,\n rotationX: rotationX,\n rotationY: rotationY,\n rotationZ: rotationZ,\n scale: scale,\n scaling: scaling,\n setAxis: setAxis,\n setDefaultType: setDefaultType,\n setTranslation: setTranslation,\n transformDirection: transformDirection,\n transformNormal: transformNormal$1,\n transformPoint: transformPoint,\n translate: translate,\n translation: translation,\n transpose: transpose\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* DataType */\nconst BYTE$2 = 0x1400;\nconst UNSIGNED_BYTE$3 = 0x1401;\nconst SHORT$2 = 0x1402;\nconst UNSIGNED_SHORT$3 = 0x1403;\nconst INT$3 = 0x1404;\nconst UNSIGNED_INT$3 = 0x1405;\nconst FLOAT$3 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4$1 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1$1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5$1 = 0x8363;\nconst HALF_FLOAT$1 = 0x140B;\nconst UNSIGNED_INT_2_10_10_10_REV$1 = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV$1 = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV$1 = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV$1 = 0x8DAD;\nconst UNSIGNED_INT_24_8$1 = 0x84FA;\n\nconst glTypeToTypedArray = {};\n{\n const tt = glTypeToTypedArray;\n tt[BYTE$2] = Int8Array;\n tt[UNSIGNED_BYTE$3] = Uint8Array;\n tt[SHORT$2] = Int16Array;\n tt[UNSIGNED_SHORT$3] = Uint16Array;\n tt[INT$3] = Int32Array;\n tt[UNSIGNED_INT$3] = Uint32Array;\n tt[FLOAT$3] = Float32Array;\n tt[UNSIGNED_SHORT_4_4_4_4$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_5_5_1$1] = Uint16Array;\n tt[UNSIGNED_SHORT_5_6_5$1] = Uint16Array;\n tt[HALF_FLOAT$1] = Uint16Array;\n tt[UNSIGNED_INT_2_10_10_10_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_10F_11F_11F_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_5_9_9_9_REV$1] = Uint32Array;\n tt[FLOAT_32_UNSIGNED_INT_24_8_REV$1] = Uint32Array;\n tt[UNSIGNED_INT_24_8$1] = Uint32Array;\n}\n\n/**\n * Get the GL type for a typedArray\n * @param {ArrayBufferView} typedArray a typedArray\n * @return {number} the GL type for array. For example pass in an `Int8Array` and `gl.BYTE` will\n * be returned. Pass in a `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArray(typedArray) {\n if (typedArray instanceof Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArray instanceof Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArray instanceof Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArray instanceof Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArray instanceof Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArray instanceof Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArray instanceof Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the GL type for a typedArray type\n * @param {ArrayBufferView} typedArrayType a typedArray constructor\n * @return {number} the GL type for type. For example pass in `Int8Array` and `gl.BYTE` will\n * be returned. Pass in `Uint32Array` and `gl.UNSIGNED_INT` will be returned\n * @memberOf module:twgl/typedArray\n */\nfunction getGLTypeForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return BYTE$2; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Uint8ClampedArray) { return UNSIGNED_BYTE$3; } // eslint-disable-line\n if (typedArrayType === Int16Array) { return SHORT$2; } // eslint-disable-line\n if (typedArrayType === Uint16Array) { return UNSIGNED_SHORT$3; } // eslint-disable-line\n if (typedArrayType === Int32Array) { return INT$3; } // eslint-disable-line\n if (typedArrayType === Uint32Array) { return UNSIGNED_INT$3; } // eslint-disable-line\n if (typedArrayType === Float32Array) { return FLOAT$3; } // eslint-disable-line\n throw new Error('unsupported typed array type');\n}\n\n/**\n * Get the typed array constructor for a given GL type\n * @param {number} type the GL type. (eg: `gl.UNSIGNED_INT`)\n * @return {function} the constructor for a the corresponding typed array. (eg. `Uint32Array`).\n * @memberOf module:twgl/typedArray\n */\nfunction getTypedArrayTypeForGLType(type) {\n const CTOR = glTypeToTypedArray[type];\n if (!CTOR) {\n throw new Error('unknown gl type');\n }\n return CTOR;\n}\n\nconst isArrayBuffer$1 = typeof SharedArrayBuffer !== 'undefined'\n ? function isArrayBufferOrSharedArrayBuffer(a) {\n return a && a.buffer && (a.buffer instanceof ArrayBuffer || a.buffer instanceof SharedArrayBuffer);\n }\n : function isArrayBuffer(a) {\n return a && a.buffer && a.buffer instanceof ArrayBuffer;\n };\n\nvar typedarrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n getGLTypeForTypedArray: getGLTypeForTypedArray,\n getGLTypeForTypedArrayType: getGLTypeForTypedArrayType,\n getTypedArrayTypeForGLType: getTypedArrayTypeForGLType,\n isArrayBuffer: isArrayBuffer$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint no-console: \"off\" */\n\n/**\n * Copy named properties\n *\n * @param {string[]} names names of properties to copy\n * @param {object} src object to copy properties from\n * @param {object} dst object to copy properties to\n * @private\n */\nfunction copyNamedProperties(names, src, dst) {\n names.forEach(function(name) {\n const value = src[name];\n if (value !== undefined) {\n dst[name] = value;\n }\n });\n}\n\n/**\n * Copies properties from source to dest only if a matching key is in dest\n *\n * @param {Object.} src the source\n * @param {Object.} dst the dest\n * @private\n */\nfunction copyExistingProperties(src, dst) {\n Object.keys(dst).forEach(function(key) {\n if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) { /* eslint no-prototype-builtins: 0 */\n dst[key] = src[key];\n }\n });\n}\n\nfunction error$1(...args) {\n console.error(...args);\n}\n\nfunction warn$1(...args) {\n console.warn(...args);\n}\n\nconst isTypeWeakMaps = new Map();\n\nfunction isType(object, type) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n let weakMap = isTypeWeakMaps.get(type);\n if (!weakMap) {\n weakMap = new WeakMap();\n isTypeWeakMaps.set(type, weakMap);\n }\n let isOfType = weakMap.get(object);\n if (isOfType === undefined) {\n const s = Object.prototype.toString.call(object);\n isOfType = s.substring(8, s.length - 1) === type;\n weakMap.set(object, isOfType);\n }\n return isOfType;\n}\n\nfunction isBuffer(gl, t) {\n return typeof WebGLBuffer !== 'undefined' && isType(t, 'WebGLBuffer');\n}\n\nfunction isRenderbuffer(gl, t) {\n return typeof WebGLRenderbuffer !== 'undefined' && isType(t, 'WebGLRenderbuffer');\n}\n\nfunction isTexture(gl, t) {\n return typeof WebGLTexture !== 'undefined' && isType(t, 'WebGLTexture');\n}\n\nfunction isSampler(gl, t) {\n return typeof WebGLSampler !== 'undefined' && isType(t, 'WebGLSampler');\n}\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst STATIC_DRAW = 0x88e4;\nconst ARRAY_BUFFER$1 = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$2 = 0x8893;\nconst BUFFER_SIZE = 0x8764;\n\nconst BYTE$1 = 0x1400;\nconst UNSIGNED_BYTE$2 = 0x1401;\nconst SHORT$1 = 0x1402;\nconst UNSIGNED_SHORT$2 = 0x1403;\nconst INT$2 = 0x1404;\nconst UNSIGNED_INT$2 = 0x1405;\nconst FLOAT$2 = 0x1406;\nconst defaults$2 = {\n attribPrefix: \"\",\n};\n\n/**\n * Sets the default attrib prefix\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * var arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * @deprecated see {@link module:twgl.setDefaults}\n * @param {string} prefix prefix for attribs\n * @memberOf module:twgl/attributes\n */\nfunction setAttributePrefix(prefix) {\n defaults$2.attribPrefix = prefix;\n}\n\nfunction setDefaults$2(newDefaults) {\n copyExistingProperties(newDefaults, defaults$2);\n}\n\nfunction setBufferFromTypedArray(gl, type, buffer, array, drawType) {\n gl.bindBuffer(type, buffer);\n gl.bufferData(type, array, drawType || STATIC_DRAW);\n}\n\n/**\n * Given typed array creates a WebGLBuffer and copies the typed array\n * into it.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|WebGLBuffer} typedArray the typed array. Note: If a WebGLBuffer is passed in it will just be returned. No action will be taken\n * @param {number} [type] the GL bind type for the buffer. Default = `gl.ARRAY_BUFFER`.\n * @param {number} [drawType] the GL draw type for the buffer. Default = 'gl.STATIC_DRAW`.\n * @return {WebGLBuffer} the created WebGLBuffer\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromTypedArray(gl, typedArray, type, drawType) {\n if (isBuffer(gl, typedArray)) {\n return typedArray;\n }\n type = type || ARRAY_BUFFER$1;\n const buffer = gl.createBuffer();\n setBufferFromTypedArray(gl, type, buffer, typedArray, drawType);\n return buffer;\n}\n\nfunction isIndices(name) {\n return name === \"indices\";\n}\n\n// This is really just a guess. Though I can't really imagine using\n// anything else? Maybe for some compression?\nfunction getNormalizationForTypedArrayType(typedArrayType) {\n if (typedArrayType === Int8Array) { return true; } // eslint-disable-line\n if (typedArrayType === Uint8Array) { return true; } // eslint-disable-line\n return false;\n}\n\nfunction getArray$1(array) {\n return array.length ? array : array.data;\n}\n\nconst texcoordRE = /coord|texture/i;\nconst colorRE = /color|colour/i;\n\nfunction guessNumComponentsFromName(name, length) {\n let numComponents;\n if (texcoordRE.test(name)) {\n numComponents = 2;\n } else if (colorRE.test(name)) {\n numComponents = 4;\n } else {\n numComponents = 3; // position, normals, indices ...\n }\n\n if (length % numComponents > 0) {\n throw new Error(`Can not guess numComponents for attribute '${name}'. Tried ${numComponents} but ${length} values is not evenly divisible by ${numComponents}. You should specify it.`);\n }\n\n return numComponents;\n}\n\nfunction getNumComponents$1(array, arrayName, numValues) {\n return array.numComponents || array.size || guessNumComponentsFromName(arrayName, numValues || getArray$1(array).length);\n}\n\nfunction makeTypedArray(array, name) {\n if (isArrayBuffer$1(array)) {\n return array;\n }\n\n if (isArrayBuffer$1(array.data)) {\n return array.data;\n }\n\n if (Array.isArray(array)) {\n array = {\n data: array,\n };\n }\n\n let Type = array.type ? typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type) : undefined;\n if (!Type) {\n if (isIndices(name)) {\n Type = Uint16Array;\n } else {\n Type = Float32Array;\n }\n }\n return new Type(array.data);\n}\n\nfunction glTypeFromGLTypeOrTypedArrayType(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? glTypeOrTypedArrayCtor\n : glTypeOrTypedArrayCtor ? getGLTypeForTypedArrayType(glTypeOrTypedArrayCtor) : FLOAT$2;\n}\n\nfunction typedArrayTypeFromGLTypeOrTypedArrayCtor(glTypeOrTypedArrayCtor) {\n return typeof glTypeOrTypedArrayCtor === 'number'\n ? getTypedArrayTypeForGLType(glTypeOrTypedArrayCtor)\n : glTypeOrTypedArrayCtor || Float32Array;\n}\n\nfunction attribBufferFromBuffer(gl, array/*, arrayName */) {\n return {\n buffer: array.buffer,\n numValues: 2 * 3 * 4, // safely divided by 2, 3, 4\n type: glTypeFromGLTypeOrTypedArrayType(array.type),\n arrayType: typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type),\n };\n}\n\nfunction attribBufferFromSize(gl, array/*, arrayName*/) {\n const numValues = array.data || array;\n const arrayType = typedArrayTypeFromGLTypeOrTypedArrayCtor(array.type);\n const numBytes = numValues * arrayType.BYTES_PER_ELEMENT;\n const buffer = gl.createBuffer();\n gl.bindBuffer(ARRAY_BUFFER$1, buffer);\n gl.bufferData(ARRAY_BUFFER$1, numBytes, array.drawType || STATIC_DRAW);\n return {\n buffer,\n numValues,\n type: getGLTypeForTypedArrayType(arrayType),\n arrayType,\n };\n}\n\nfunction attribBufferFromArrayLike(gl, array, arrayName) {\n const typedArray = makeTypedArray(array, arrayName);\n return {\n arrayType: typedArray.constructor,\n buffer: createBufferFromTypedArray(gl, typedArray, undefined, array.drawType),\n type: getGLTypeForTypedArray(typedArray),\n numValues: 0,\n };\n}\n\n/**\n * The info for an attribute. This is effectively just the arguments to `gl.vertexAttribPointer` plus the WebGLBuffer\n * for the attribute.\n *\n * @typedef {Object} AttribInfo\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {number} [numComponents] the number of components for this attribute.\n * @property {number} [size] synonym for `numComponents`.\n * @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`\n * @property {boolean} [normalize] whether or not to normalize the data. Default = false\n * @property {number} [offset] offset into buffer in bytes. Default = 0\n * @property {number} [stride] the stride in bytes per element. Default = 0\n * @property {number} [divisor] the divisor in instances. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you're using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {WebGLBuffer} buffer the buffer that contains the data for this attribute\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {(Int8ArrayConstructor|Uint8ArrayConstructor|Int16ArrayConstructor|Uint16ArrayConstructor|Int32ArrayConstructor|Uint32ArrayConstructor|Float32ArrayConstructor)} TypedArrayConstructor\n */\n\n/**\n * Use this type of array spec when TWGL can't guess the type or number of components of an array\n * @typedef {Object} FullArraySpec\n * @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be\n * disabled and set to this constant value and all other values will be ignored.\n * @property {(number|number[]|ArrayBufferView)} [data] The data of the array. A number alone becomes the number of elements of type.\n * @property {number} [numComponents] number of components for `vertexAttribPointer`. Default is based on the name of the array.\n * If `coord` is in the name assumes `numComponents = 2`.\n * If `color` is in the name assumes `numComponents = 4`.\n * otherwise assumes `numComponents = 3`\n * @property {number|TypedArrayConstructor} [type] type. This is used if `data` is a JavaScript array, or `buffer` is passed in, or `data` is a number.\n * It can either be the constructor for a typedarray. (eg. `Uint8Array`) OR a WebGL type, (eg `gl.UNSIGNED_BYTE`).\n * For example if you want colors in a `Uint8Array` you might have a `FullArraySpec` like `{ type: gl.UNSIGNED_BYTE, data: [255,0,255,255, ...], }`.\n * @property {number} [size] synonym for `numComponents`.\n * @property {boolean} [normalize] normalize for `vertexAttribPointer`. Default is true if type is `Int8Array` or `Uint8Array` otherwise false.\n * @property {number} [stride] stride for `vertexAttribPointer`. Default = 0\n * @property {number} [offset] offset for `vertexAttribPointer`. Default = 0\n * @property {number} [divisor] divisor for `vertexAttribDivisor`. Default = 0.\n * Requires WebGL2 or the ANGLE_instanced_arrays extension.\n * and, if you using WebGL1 you must have called {@link module:twgl.addExtensionsToContext}\n * @property {string} [attrib] name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.\n * @property {string} [name] synonym for `attrib`.\n * @property {string} [attribName] synonym for `attrib`.\n * @property {WebGLBuffer} [buffer] Buffer to use for this attribute. This lets you use your own buffer\n * but you will need to supply `numComponents` and `type`. You can effectively pass an `AttribInfo`\n * to provide this. Example:\n *\n * const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {\n * position: [1, 2, 3, ... ],\n * });\n * const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {\n * position: bufferInfo1.attribs.position, // use the same buffer from bufferInfo1\n * });\n *\n * @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW\n * @memberOf module:twgl\n */\n\n/**\n * An individual array in {@link module:twgl.Arrays}\n *\n * When passed to {@link module:twgl.createBufferInfoFromArrays} if an ArraySpec is `number[]` or `ArrayBufferView`\n * the types will be guessed based on the name. `indices` will be `Uint16Array`, everything else will\n * be `Float32Array`. If an ArraySpec is a number it's the number of floats for an empty (zeroed) buffer.\n *\n * @typedef {(number|number[]|ArrayBufferView|module:twgl.FullArraySpec)} ArraySpec\n * @memberOf module:twgl\n */\n\n/**\n * This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your\n * attributes have a common prefix you can specify it by calling {@link module:twgl.setAttributePrefix}.\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * Objects with various fields. See {@link module:twgl.FullArraySpec}.\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * @typedef {Object.} Arrays\n * @memberOf module:twgl\n */\n\n\n/**\n * Creates a set of attribute data and WebGLBuffers from set of arrays\n *\n * Given\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * returns something like\n *\n * var attribs = {\n * position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },\n * color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, },\n * };\n *\n * notes:\n *\n * * Arrays can take various forms\n *\n * Bare JavaScript Arrays\n *\n * var arrays = {\n * position: [-1, 1, 0],\n * normal: [0, 1, 0],\n * ...\n * }\n *\n * Bare TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([-1, 1, 0]),\n * color: new Uint8Array([255, 128, 64, 255]),\n * ...\n * }\n *\n * * Will guess at `numComponents` if not specified based on name.\n *\n * If `coord` is in the name assumes `numComponents = 2`\n *\n * If `color` is in the name assumes `numComponents = 4`\n *\n * otherwise assumes `numComponents = 3`\n *\n * @param {WebGLRenderingContext} gl The webgl rendering context.\n * @param {module:twgl.Arrays} arrays The arrays\n * @param {module:twgl.BufferInfo} [srcBufferInfo] a BufferInfo to copy from\n * This lets you share buffers. Any arrays you supply will override\n * the buffers from srcBufferInfo.\n * @return {Object.} the attribs\n * @memberOf module:twgl/attributes\n */\nfunction createAttribsFromArrays(gl, arrays) {\n const attribs = {};\n Object.keys(arrays).forEach(function(arrayName) {\n if (!isIndices(arrayName)) {\n const array = arrays[arrayName];\n const attribName = array.attrib || array.name || array.attribName || (defaults$2.attribPrefix + arrayName);\n if (array.value) {\n if (!Array.isArray(array.value) && !isArrayBuffer$1(array.value)) {\n throw new Error('array.value is not array or typedarray');\n }\n attribs[attribName] = {\n value: array.value,\n };\n } else {\n let fn;\n if (array.buffer && array.buffer instanceof WebGLBuffer) {\n fn = attribBufferFromBuffer;\n } else if (typeof array === \"number\" || typeof array.data === \"number\") {\n fn = attribBufferFromSize;\n } else {\n fn = attribBufferFromArrayLike;\n }\n const {buffer, type, numValues, arrayType} = fn(gl, array, arrayName);\n const normalization = array.normalize !== undefined ? array.normalize : getNormalizationForTypedArrayType(arrayType);\n const numComponents = getNumComponents$1(array, arrayName, numValues);\n attribs[attribName] = {\n buffer: buffer,\n numComponents: numComponents,\n type: type,\n normalize: normalization,\n stride: array.stride || 0,\n offset: array.offset || 0,\n divisor: array.divisor === undefined ? undefined : array.divisor,\n drawType: array.drawType,\n };\n }\n }\n });\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n return attribs;\n}\n\n/**\n * Sets the contents of a buffer attached to an attribInfo\n *\n * This is helper function to dynamically update a buffer.\n *\n * Let's say you make a bufferInfo\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n * var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);\n *\n * And you want to dynamically update the positions. You could do this\n *\n * // assuming arrays.position has already been updated with new data.\n * twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);\n *\n * @param {WebGLRenderingContext} gl\n * @param {AttribInfo} attribInfo The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix\n * the name of the attribute will include the prefix.\n * @param {ArraySpec} array Note: it is arguably inefficient to pass in anything but a typed array because anything\n * else will have to be converted to a typed array before it can be used by WebGL. During init time that\n * inefficiency is usually not important but if you're updating data dynamically best to be efficient.\n * @param {number} [offset] an optional offset into the buffer. This is only an offset into the WebGL buffer\n * not the array. To pass in an offset into the array itself use a typed array and create an `ArrayBufferView`\n * for the portion of the array you want to use.\n *\n * var someArray = new Float32Array(1000); // an array with 1000 floats\n * var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray\n *\n * Now you can pass `someSubArray` into setAttribInfoBufferFromArray`\n * @memberOf module:twgl/attributes\n */\nfunction setAttribInfoBufferFromArray(gl, attribInfo, array, offset) {\n array = makeTypedArray(array);\n if (offset !== undefined) {\n gl.bindBuffer(ARRAY_BUFFER$1, attribInfo.buffer);\n gl.bufferSubData(ARRAY_BUFFER$1, offset, array);\n } else {\n setBufferFromTypedArray(gl, ARRAY_BUFFER$1, attribInfo.buffer, array, attribInfo.drawType);\n }\n}\n\nfunction getBytesPerValueForGLType(gl, type) {\n if (type === BYTE$1) return 1; // eslint-disable-line\n if (type === UNSIGNED_BYTE$2) return 1; // eslint-disable-line\n if (type === SHORT$1) return 2; // eslint-disable-line\n if (type === UNSIGNED_SHORT$2) return 2; // eslint-disable-line\n if (type === INT$2) return 4; // eslint-disable-line\n if (type === UNSIGNED_INT$2) return 4; // eslint-disable-line\n if (type === FLOAT$2) return 4; // eslint-disable-line\n return 0;\n}\n\n// Tries to get the number of elements from a set of arrays.\nconst positionKeys = ['position', 'positions', 'a_position'];\nfunction getNumElementsFromNonIndexedArrays(arrays) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in arrays) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(arrays)[0];\n }\n const array = arrays[key];\n const length = getArray$1(array).length;\n if (length === undefined) {\n return 1; // There's no arrays\n }\n const numComponents = getNumComponents$1(array, key);\n const numElements = length / numComponents;\n if (length % numComponents > 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\nfunction getNumElementsFromAttributes(gl, attribs) {\n let key;\n let ii;\n for (ii = 0; ii < positionKeys.length; ++ii) {\n key = positionKeys[ii];\n if (key in attribs) {\n break;\n }\n key = defaults$2.attribPrefix + key;\n if (key in attribs) {\n break;\n }\n }\n if (ii === positionKeys.length) {\n key = Object.keys(attribs)[0];\n }\n const attrib = attribs[key];\n if (!attrib.buffer) {\n return 1; // There's no buffer\n }\n gl.bindBuffer(ARRAY_BUFFER$1, attrib.buffer);\n const numBytes = gl.getBufferParameter(ARRAY_BUFFER$1, BUFFER_SIZE);\n gl.bindBuffer(ARRAY_BUFFER$1, null);\n\n const bytesPerValue = getBytesPerValueForGLType(gl, attrib.type);\n const totalElements = numBytes / bytesPerValue;\n const numComponents = attrib.numComponents || attrib.size;\n // TODO: check stride\n const numElements = totalElements / numComponents;\n if (numElements % 1 !== 0) {\n throw new Error(`numComponents ${numComponents} not correct for length ${length}`);\n }\n return numElements;\n}\n\n/**\n * @typedef {Object} BufferInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.\n * @property {Object.} [attribs] The attribs appropriate to call `setAttributes`\n * @memberOf module:twgl\n */\n\n/**\n * Creates a BufferInfo from an object of arrays.\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * Given an object like\n *\n * var arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },\n * indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },\n * };\n *\n * Creates an BufferInfo like this\n *\n * bufferInfo = {\n * numElements: 4, // or whatever the number of elements is\n * indices: WebGLBuffer, // this property will not exist if there are no indices\n * attribs: {\n * position: { buffer: WebGLBuffer, numComponents: 3, },\n * normal: { buffer: WebGLBuffer, numComponents: 3, },\n * texcoord: { buffer: WebGLBuffer, numComponents: 2, },\n * },\n * };\n *\n * The properties of arrays can be JavaScript arrays in which case the number of components\n * will be guessed.\n *\n * var arrays = {\n * position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],\n * texcoord: [0, 0, 0, 1, 1, 0, 1, 1],\n * normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],\n * indices: [0, 1, 2, 1, 2, 3],\n * };\n *\n * They can also be TypedArrays\n *\n * var arrays = {\n * position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),\n * texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),\n * normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),\n * indices: new Uint16Array([0, 1, 2, 1, 2, 3]),\n * };\n *\n * Or AugmentedTypedArrays\n *\n * var positions = createAugmentedTypedArray(3, 4);\n * var texcoords = createAugmentedTypedArray(2, 4);\n * var normals = createAugmentedTypedArray(3, 4);\n * var indices = createAugmentedTypedArray(3, 2, Uint16Array);\n *\n * positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);\n * texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);\n * normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);\n * indices.push([0, 1, 2, 1, 2, 3]);\n *\n * var arrays = {\n * position: positions,\n * texcoord: texcoords,\n * normal: normals,\n * indices: indices,\n * };\n *\n * For the last example it is equivalent to\n *\n * var bufferInfo = {\n * attribs: {\n * position: { numComponents: 3, buffer: gl.createBuffer(), },\n * texcoord: { numComponents: 2, buffer: gl.createBuffer(), },\n * normal: { numComponents: 3, buffer: gl.createBuffer(), },\n * },\n * indices: gl.createBuffer(),\n * numElements: 6,\n * };\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.position.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.texcoord.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.normal.buffer);\n * gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);\n * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);\n * gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.Arrays} arrays Your data\n * @param {module:twgl.BufferInfo} [srcBufferInfo] An existing\n * buffer info to start from. WebGLBuffers etc specified\n * in the srcBufferInfo will be used in a new BufferInfo\n * with any arrays specified overriding the ones in\n * srcBufferInfo.\n * @return {module:twgl.BufferInfo} A BufferInfo\n * @memberOf module:twgl/attributes\n */\nfunction createBufferInfoFromArrays(gl, arrays, srcBufferInfo) {\n const newAttribs = createAttribsFromArrays(gl, arrays);\n const bufferInfo = Object.assign({}, srcBufferInfo ? srcBufferInfo : {});\n bufferInfo.attribs = Object.assign({}, srcBufferInfo ? srcBufferInfo.attribs : {}, newAttribs);\n const indices = arrays.indices;\n if (indices) {\n const newIndices = makeTypedArray(indices, \"indices\");\n bufferInfo.indices = createBufferFromTypedArray(gl, newIndices, ELEMENT_ARRAY_BUFFER$2);\n bufferInfo.numElements = newIndices.length;\n bufferInfo.elementType = getGLTypeForTypedArray(newIndices);\n } else if (!bufferInfo.numElements) {\n bufferInfo.numElements = getNumElementsFromAttributes(gl, bufferInfo.attribs);\n }\n\n return bufferInfo;\n}\n\n/**\n * Creates a buffer from an array, typed array, or array spec\n *\n * Given something like this\n *\n * [1, 2, 3],\n *\n * or\n *\n * new Uint16Array([1,2,3]);\n *\n * or\n *\n * {\n * data: [1, 2, 3],\n * type: Uint8Array,\n * }\n *\n * returns a WebGLBuffer that contains the given data.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.ArraySpec} array an array, typed array, or array spec.\n * @param {string} arrayName name of array. Used to guess the type if type can not be derived otherwise.\n * @return {WebGLBuffer} a WebGLBuffer containing the data in array.\n * @memberOf module:twgl/attributes\n */\nfunction createBufferFromArray(gl, array, arrayName) {\n const type = arrayName === \"indices\" ? ELEMENT_ARRAY_BUFFER$2 : ARRAY_BUFFER$1;\n const typedArray = makeTypedArray(array, arrayName);\n return createBufferFromTypedArray(gl, typedArray, type);\n}\n\n/**\n * Creates buffers from arrays or typed arrays\n *\n * Given something like this\n *\n * var arrays = {\n * positions: [1, 2, 3],\n * normals: [0, 0, 1],\n * }\n *\n * returns something like\n *\n * buffers = {\n * positions: WebGLBuffer,\n * normals: WebGLBuffer,\n * }\n *\n * If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {module:twgl.Arrays} arrays\n * @return {Object} returns an object with one WebGLBuffer per array\n * @memberOf module:twgl/attributes\n */\nfunction createBuffersFromArrays(gl, arrays) {\n const buffers = { };\n Object.keys(arrays).forEach(function(key) {\n buffers[key] = createBufferFromArray(gl, arrays[key], key);\n });\n\n // Ugh!\n if (arrays.indices) {\n buffers.numElements = arrays.indices.length;\n buffers.elementType = getGLTypeForTypedArray(makeTypedArray(arrays.indices));\n } else {\n buffers.numElements = getNumElementsFromNonIndexedArrays(arrays);\n }\n\n return buffers;\n}\n\nvar attributes = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttribsFromArrays: createAttribsFromArrays,\n createBuffersFromArrays: createBuffersFromArrays,\n createBufferFromArray: createBufferFromArray,\n createBufferFromTypedArray: createBufferFromTypedArray,\n createBufferInfoFromArrays: createBufferInfoFromArrays,\n setAttribInfoBufferFromArray: setAttribInfoBufferFromArray,\n setAttributePrefix: setAttributePrefix,\n setAttributeDefaults_: setDefaults$2,\n getNumComponents_: getNumComponents$1,\n getArray_: getArray$1\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst getArray = getArray$1; // eslint-disable-line\nconst getNumComponents = getNumComponents$1; // eslint-disable-line\n\n/**\n * @typedef {(Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array)} TypedArray\n */\n\n/**\n * Add `push` to a typed array. It just keeps a 'cursor'\n * and allows use to `push` values into the array so we\n * don't have to manually compute offsets\n * @param {TypedArray} typedArray TypedArray to augment\n * @param {number} numComponents number of components.\n * @private\n */\nfunction augmentTypedArray(typedArray, numComponents) {\n let cursor = 0;\n typedArray.push = function() {\n for (let ii = 0; ii < arguments.length; ++ii) {\n const value = arguments[ii];\n if (value instanceof Array || isArrayBuffer$1(value)) {\n for (let jj = 0; jj < value.length; ++jj) {\n typedArray[cursor++] = value[jj];\n }\n } else {\n typedArray[cursor++] = value;\n }\n }\n };\n typedArray.reset = function(opt_index) {\n cursor = opt_index || 0;\n };\n typedArray.numComponents = numComponents;\n Object.defineProperty(typedArray, 'numElements', {\n get: function() {\n return this.length / this.numComponents | 0;\n },\n });\n return typedArray;\n}\n\n/**\n * creates a typed array with a `push` function attached\n * so that you can easily *push* values.\n *\n * `push` can take multiple arguments. If an argument is an array each element\n * of the array will be added to the typed array.\n *\n * Example:\n *\n * const array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values\n * array.push(1, 2, 3);\n * array.push([4, 5, 6]);\n * // array now contains [1, 2, 3, 4, 5, 6]\n *\n * Also has `numComponents` and `numElements` properties.\n *\n * @param {number} numComponents number of components\n * @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`.\n * @param {constructor} opt_type A constructor for the type. Default = `Float32Array`.\n * @return {ArrayBufferView} A typed array.\n * @memberOf module:twgl/primitives\n */\nfunction createAugmentedTypedArray(numComponents, numElements, opt_type) {\n const Type = opt_type || Float32Array;\n return augmentTypedArray(new Type(numComponents * numElements), numComponents);\n}\n\nfunction allButIndices(name) {\n return name !== \"indices\";\n}\n\n/**\n * Given indexed vertices creates a new set of vertices un-indexed by expanding the indexed vertices.\n * @param {Object.} vertices The indexed vertices to deindex\n * @return {Object.} The deindexed vertices\n * @memberOf module:twgl/primitives\n */\nfunction deindexVertices(vertices) {\n const indices = vertices.indices;\n const newVertices = {};\n const numElements = indices.length;\n\n function expandToUnindexed(channel) {\n const srcBuffer = vertices[channel];\n const numComponents = srcBuffer.numComponents;\n const dstBuffer = createAugmentedTypedArray(numComponents, numElements, srcBuffer.constructor);\n for (let ii = 0; ii < numElements; ++ii) {\n const ndx = indices[ii];\n const offset = ndx * numComponents;\n for (let jj = 0; jj < numComponents; ++jj) {\n dstBuffer.push(srcBuffer[offset + jj]);\n }\n }\n newVertices[channel] = dstBuffer;\n }\n\n Object.keys(vertices).filter(allButIndices).forEach(expandToUnindexed);\n\n return newVertices;\n}\n\n/**\n * flattens the normals of deindexed vertices in place.\n * @param {Object.} vertices The deindexed vertices who's normals to flatten\n * @return {Object.} The flattened vertices (same as was passed in)\n * @memberOf module:twgl/primitives\n */\nfunction flattenNormals(vertices) {\n if (vertices.indices) {\n throw new Error('can not flatten normals of indexed vertices. deindex them first');\n }\n\n const normals = vertices.normal;\n const numNormals = normals.length;\n for (let ii = 0; ii < numNormals; ii += 9) {\n // pull out the 3 normals for this triangle\n const nax = normals[ii + 0];\n const nay = normals[ii + 1];\n const naz = normals[ii + 2];\n\n const nbx = normals[ii + 3];\n const nby = normals[ii + 4];\n const nbz = normals[ii + 5];\n\n const ncx = normals[ii + 6];\n const ncy = normals[ii + 7];\n const ncz = normals[ii + 8];\n\n // add them\n let nx = nax + nbx + ncx;\n let ny = nay + nby + ncy;\n let nz = naz + nbz + ncz;\n\n // normalize them\n const length = Math.sqrt(nx * nx + ny * ny + nz * nz);\n\n nx /= length;\n ny /= length;\n nz /= length;\n\n // copy them back in\n normals[ii + 0] = nx;\n normals[ii + 1] = ny;\n normals[ii + 2] = nz;\n\n normals[ii + 3] = nx;\n normals[ii + 4] = ny;\n normals[ii + 5] = nz;\n\n normals[ii + 6] = nx;\n normals[ii + 7] = ny;\n normals[ii + 8] = nz;\n }\n\n return vertices;\n}\n\nfunction applyFuncToV3Array(array, matrix, fn) {\n const len = array.length;\n const tmp = new Float32Array(3);\n for (let ii = 0; ii < len; ii += 3) {\n fn(matrix, [array[ii], array[ii + 1], array[ii + 2]], tmp);\n array[ii ] = tmp[0];\n array[ii + 1] = tmp[1];\n array[ii + 2] = tmp[2];\n }\n}\n\nfunction transformNormal(mi, v, dst) {\n dst = dst || create$1();\n const v0 = v[0];\n const v1 = v[1];\n const v2 = v[2];\n\n dst[0] = v0 * mi[0 * 4 + 0] + v1 * mi[0 * 4 + 1] + v2 * mi[0 * 4 + 2];\n dst[1] = v0 * mi[1 * 4 + 0] + v1 * mi[1 * 4 + 1] + v2 * mi[1 * 4 + 2];\n dst[2] = v0 * mi[2 * 4 + 0] + v1 * mi[2 * 4 + 1] + v2 * mi[2 * 4 + 2];\n\n return dst;\n}\n\n/**\n * Reorients directions by the given matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientDirections(array, matrix) {\n applyFuncToV3Array(array, matrix, transformDirection);\n return array;\n}\n\n/**\n * Reorients normals by the inverse-transpose of the given\n * matrix..\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientNormals(array, matrix) {\n applyFuncToV3Array(array, inverse(matrix), transformNormal);\n return array;\n}\n\n/**\n * Reorients positions by the given matrix. In other words, it\n * multiplies each vertex by the given matrix.\n * @param {(number[]|TypedArray)} array The array. Assumes value floats per element.\n * @param {module:twgl/m4.Mat4} matrix A matrix to multiply by.\n * @return {(number[]|TypedArray)} the same array that was passed in\n * @memberOf module:twgl/primitives\n */\nfunction reorientPositions(array, matrix) {\n applyFuncToV3Array(array, matrix, transformPoint);\n return array;\n}\n\n/**\n * @typedef {(number[]|TypedArray)} NativeArrayOrTypedArray\n */\n\n/**\n * Reorients arrays by the given matrix. Assumes arrays have\n * names that contains 'pos' could be reoriented as positions,\n * 'binorm' or 'tan' as directions, and 'norm' as normals.\n *\n * @param {Object.} arrays The vertices to reorient\n * @param {module:twgl/m4.Mat4} matrix matrix to reorient by.\n * @return {Object.} same arrays that were passed in.\n * @memberOf module:twgl/primitives\n */\nfunction reorientVertices(arrays, matrix) {\n Object.keys(arrays).forEach(function(name) {\n const array = arrays[name];\n if (name.indexOf(\"pos\") >= 0) {\n reorientPositions(array, matrix);\n } else if (name.indexOf(\"tan\") >= 0 || name.indexOf(\"binorm\") >= 0) {\n reorientDirections(array, matrix);\n } else if (name.indexOf(\"norm\") >= 0) {\n reorientNormals(array, matrix);\n }\n });\n return arrays;\n}\n\n/**\n * Creates XY quad BufferInfo\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad BufferInfo\n * @memberOf module:twgl/primitives\n * @function createXYQuadBuffers\n */\n\n/**\n * Creates XY quad Buffers\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadBufferInfo(gl, 1, 0, 0.5);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {module:twgl.BufferInfo} the created XY Quad buffers\n * @memberOf module:twgl/primitives\n * @function createXYQuadBufferInfo\n */\n\n/**\n * Creates XY quad vertices\n *\n * The default with no parameters will return a 2x2 quad with values from -1 to +1.\n * If you want a unit quad with that goes from 0 to 1 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0.5, 0.5);\n *\n * If you want a unit quad centered above 0,0 you'd call it with\n *\n * twgl.primitives.createXYQuadVertices(1, 0, 0.5);\n *\n * @param {number} [size] the size across the quad. Defaults to 2 which means vertices will go from -1 to +1\n * @param {number} [xOffset] the amount to offset the quad in X\n * @param {number} [yOffset] the amount to offset the quad in Y\n * @return {Object.} the created XY Quad vertices\n * @memberOf module:twgl/primitives\n */\nfunction createXYQuadVertices(size, xOffset, yOffset) {\n size = size || 2;\n xOffset = xOffset || 0;\n yOffset = yOffset || 0;\n size *= 0.5;\n return {\n position: {\n numComponents: 2,\n data: [\n xOffset + -1 * size, yOffset + -1 * size,\n xOffset + 1 * size, yOffset + -1 * size,\n xOffset + -1 * size, yOffset + 1 * size,\n xOffset + 1 * size, yOffset + 1 * size,\n ],\n },\n normal: [\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n 0, 0, 1,\n ],\n texcoord: [\n 0, 0,\n 1, 0,\n 0, 1,\n 1, 1,\n ],\n indices: [ 0, 1, 2, 2, 1, 3 ],\n };\n}\n\n/**\n * Creates XZ plane BufferInfo.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {module:twgl.BufferInfo} The created plane BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createPlaneBufferInfo\n */\n\n/**\n * Creates XZ plane buffers.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane buffers.\n * @memberOf module:twgl/primitives\n * @function createPlaneBuffers\n */\n\n/**\n * Creates XZ plane vertices.\n *\n * The created plane has position, normal, and texcoord data\n *\n * @param {number} [width] Width of the plane. Default = 1\n * @param {number} [depth] Depth of the plane. Default = 1\n * @param {number} [subdivisionsWidth] Number of steps across the plane. Default = 1\n * @param {number} [subdivisionsDepth] Number of steps down the plane. Default = 1\n * @param {module:twgl/m4.Mat4} [matrix] A matrix by which to multiply all the vertices.\n * @return {Object.} The created plane vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createPlaneVertices(\n width,\n depth,\n subdivisionsWidth,\n subdivisionsDepth,\n matrix) {\n width = width || 1;\n depth = depth || 1;\n subdivisionsWidth = subdivisionsWidth || 1;\n subdivisionsDepth = subdivisionsDepth || 1;\n matrix = matrix || identity();\n\n const numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n for (let z = 0; z <= subdivisionsDepth; z++) {\n for (let x = 0; x <= subdivisionsWidth; x++) {\n const u = x / subdivisionsWidth;\n const v = z / subdivisionsDepth;\n positions.push(\n width * u - width * 0.5,\n 0,\n depth * v - depth * 0.5);\n normals.push(0, 1, 0);\n texcoords.push(u, v);\n }\n }\n\n const numVertsAcross = subdivisionsWidth + 1;\n const indices = createAugmentedTypedArray(\n 3, subdivisionsWidth * subdivisionsDepth * 2, Uint16Array);\n\n for (let z = 0; z < subdivisionsDepth; z++) { // eslint-disable-line\n for (let x = 0; x < subdivisionsWidth; x++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (z + 0) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x,\n (z + 0) * numVertsAcross + x + 1);\n\n // Make triangle 2 of quad.\n indices.push(\n (z + 1) * numVertsAcross + x,\n (z + 1) * numVertsAcross + x + 1,\n (z + 0) * numVertsAcross + x + 1);\n }\n }\n\n const arrays = reorientVertices({\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n }, matrix);\n return arrays;\n}\n\n/**\n * Creates sphere BufferInfo.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {module:twgl.BufferInfo} The created sphere BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createSphereBufferInfo\n */\n\n/**\n * Creates sphere buffers.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere buffers.\n * @memberOf module:twgl/primitives\n * @function createSphereBuffers\n */\n\n/**\n * Creates sphere vertices.\n *\n * The created sphere has position, normal, and texcoord data\n *\n * @param {number} radius radius of the sphere.\n * @param {number} subdivisionsAxis number of steps around the sphere.\n * @param {number} subdivisionsHeight number of vertically on the sphere.\n * @param {number} [opt_startLatitudeInRadians] where to start the\n * top of the sphere. Default = 0.\n * @param {number} [opt_endLatitudeInRadians] Where to end the\n * bottom of the sphere. Default = Math.PI.\n * @param {number} [opt_startLongitudeInRadians] where to start\n * wrapping the sphere. Default = 0.\n * @param {number} [opt_endLongitudeInRadians] where to end\n * wrapping the sphere. Default = 2 * Math.PI.\n * @return {Object.} The created sphere vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createSphereVertices(\n radius,\n subdivisionsAxis,\n subdivisionsHeight,\n opt_startLatitudeInRadians,\n opt_endLatitudeInRadians,\n opt_startLongitudeInRadians,\n opt_endLongitudeInRadians) {\n if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {\n throw new Error('subdivisionAxis and subdivisionHeight must be > 0');\n }\n\n opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0;\n opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI;\n opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0;\n opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2);\n\n const latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians;\n const longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians;\n\n // We are going to generate our sphere by iterating through its\n // spherical coordinates and generating 2 triangles for each quad on a\n // ring of the sphere.\n const numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n // Generate the individual vertices in our vertex buffer.\n for (let y = 0; y <= subdivisionsHeight; y++) {\n for (let x = 0; x <= subdivisionsAxis; x++) {\n // Generate a vertex based on its spherical coordinates\n const u = x / subdivisionsAxis;\n const v = y / subdivisionsHeight;\n const theta = longRange * u + opt_startLongitudeInRadians;\n const phi = latRange * v + opt_startLatitudeInRadians;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n const ux = cosTheta * sinPhi;\n const uy = cosPhi;\n const uz = sinTheta * sinPhi;\n positions.push(radius * ux, radius * uy, radius * uz);\n normals.push(ux, uy, uz);\n texcoords.push(1 - u, v);\n }\n }\n\n const numVertsAround = subdivisionsAxis + 1;\n const indices = createAugmentedTypedArray(3, subdivisionsAxis * subdivisionsHeight * 2, Uint16Array);\n for (let x = 0; x < subdivisionsAxis; x++) { // eslint-disable-line\n for (let y = 0; y < subdivisionsHeight; y++) { // eslint-disable-line\n // Make triangle 1 of quad.\n indices.push(\n (y + 0) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x);\n\n // Make triangle 2 of quad.\n indices.push(\n (y + 1) * numVertsAround + x,\n (y + 0) * numVertsAround + x + 1,\n (y + 1) * numVertsAround + x + 1);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Array of the indices of corners of each face of a cube.\n * @type {Array.}\n * @private\n */\nconst CUBE_FACE_INDICES = [\n [3, 7, 5, 1], // right\n [6, 2, 0, 4], // left\n [6, 7, 3, 2], // ??\n [0, 1, 5, 4], // ??\n [7, 6, 4, 5], // front\n [2, 3, 1, 0], // back\n];\n\n/**\n * Creates a BufferInfo for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCubeBufferInfo\n */\n\n/**\n * Creates the buffers and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCubeBuffers\n */\n\n/**\n * Creates the vertices and indices for a cube.\n *\n * The cube is created around the origin. (-size / 2, size / 2).\n *\n * @param {number} [size] width, height and depth of the cube.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCubeVertices(size) {\n size = size || 1;\n const k = size / 2;\n\n const cornerVertices = [\n [-k, -k, -k],\n [+k, -k, -k],\n [-k, +k, -k],\n [+k, +k, -k],\n [-k, -k, +k],\n [+k, -k, +k],\n [-k, +k, +k],\n [+k, +k, +k],\n ];\n\n const faceNormals = [\n [+1, +0, +0],\n [-1, +0, +0],\n [+0, +1, +0],\n [+0, -1, +0],\n [+0, +0, +1],\n [+0, +0, -1],\n ];\n\n const uvCoords = [\n [1, 0],\n [0, 0],\n [0, 1],\n [1, 1],\n ];\n\n const numVertices = 6 * 4;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2 , numVertices);\n const indices = createAugmentedTypedArray(3, 6 * 2, Uint16Array);\n\n for (let f = 0; f < 6; ++f) {\n const faceIndices = CUBE_FACE_INDICES[f];\n for (let v = 0; v < 4; ++v) {\n const position = cornerVertices[faceIndices[v]];\n const normal = faceNormals[f];\n const uv = uvCoords[v];\n\n // Each face needs all four vertices because the normals and texture\n // coordinates are not all the same.\n positions.push(position);\n normals.push(normal);\n texcoords.push(uv);\n\n }\n // Two triangles make a square face.\n const offset = 4 * f;\n indices.push(offset + 0, offset + 1, offset + 2);\n indices.push(offset + 0, offset + 2, offset + 3);\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates a BufferInfo for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created cone BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBufferInfo\n */\n\n/**\n * Creates buffers for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone buffers.\n * @memberOf module:twgl/primitives\n * @function createTruncatedConeBuffers\n */\n\n/**\n * Creates vertices for a truncated cone, which is like a cylinder\n * except that it has different top and bottom radii. A truncated cone\n * can also be used to create cylinders and regular cones. The\n * truncated cone will be created centered about the origin, with the\n * y axis as its vertical axis. .\n *\n * @param {number} bottomRadius Bottom radius of truncated cone.\n * @param {number} topRadius Top radius of truncated cone.\n * @param {number} height Height of truncated cone.\n * @param {number} radialSubdivisions The number of subdivisions around the\n * truncated cone.\n * @param {number} verticalSubdivisions The number of subdivisions down the\n * truncated cone.\n * @param {boolean} [opt_topCap] Create top cap. Default = true.\n * @param {boolean} [opt_bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created cone vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTruncatedConeVertices(\n bottomRadius,\n topRadius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n opt_topCap,\n opt_bottomCap) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (verticalSubdivisions < 1) {\n throw new Error('verticalSubdivisions must be 1 or greater');\n }\n\n const topCap = (opt_topCap === undefined) ? true : opt_topCap;\n const bottomCap = (opt_bottomCap === undefined) ? true : opt_bottomCap;\n\n const extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0);\n\n const numVertices = (radialSubdivisions + 1) * (verticalSubdivisions + 1 + extra);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, radialSubdivisions * (verticalSubdivisions + extra / 2) * 2, Uint16Array);\n\n const vertsAroundEdge = radialSubdivisions + 1;\n\n // The slant of the cone is constant across its surface\n const slant = Math.atan2(bottomRadius - topRadius, height);\n const cosSlant = Math.cos(slant);\n const sinSlant = Math.sin(slant);\n\n const start = topCap ? -2 : 0;\n const end = verticalSubdivisions + (bottomCap ? 2 : 0);\n\n for (let yy = start; yy <= end; ++yy) {\n let v = yy / verticalSubdivisions;\n let y = height * v;\n let ringRadius;\n if (yy < 0) {\n y = 0;\n v = 1;\n ringRadius = bottomRadius;\n } else if (yy > verticalSubdivisions) {\n y = height;\n v = 1;\n ringRadius = topRadius;\n } else {\n ringRadius = bottomRadius +\n (topRadius - bottomRadius) * (yy / verticalSubdivisions);\n }\n if (yy === -2 || yy === verticalSubdivisions + 2) {\n ringRadius = 0;\n v = 0;\n }\n y -= height / 2;\n for (let ii = 0; ii < vertsAroundEdge; ++ii) {\n const sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions);\n const cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions);\n positions.push(sin * ringRadius, y, cos * ringRadius);\n if (yy < 0) {\n normals.push(0, -1, 0);\n } else if (yy > verticalSubdivisions) {\n normals.push(0, 1, 0);\n } else if (ringRadius === 0.0) {\n normals.push(0, 0, 0);\n } else {\n normals.push(sin * cosSlant, sinSlant, cos * cosSlant);\n }\n texcoords.push((ii / radialSubdivisions), 1 - v);\n }\n }\n\n for (let yy = 0; yy < verticalSubdivisions + extra; ++yy) { // eslint-disable-line\n if (yy === 1 && topCap || yy === verticalSubdivisions + extra - 2 && bottomCap) {\n continue;\n }\n for (let ii = 0; ii < radialSubdivisions; ++ii) { // eslint-disable-line\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 0) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii);\n indices.push(vertsAroundEdge * (yy + 0) + 0 + ii,\n vertsAroundEdge * (yy + 1) + 1 + ii,\n vertsAroundEdge * (yy + 1) + 0 + ii);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Expands RLE data\n * @param {number[]} rleData data in format of run-length, x, y, z, run-length, x, y, z\n * @param {number[]} [padding] value to add each entry with.\n * @return {number[]} the expanded rleData\n * @private\n */\nfunction expandRLEData(rleData, padding) {\n padding = padding || [];\n const data = [];\n for (let ii = 0; ii < rleData.length; ii += 4) {\n const runLength = rleData[ii];\n const element = rleData.slice(ii + 1, ii + 4);\n element.push.apply(element, padding);\n for (let jj = 0; jj < runLength; ++jj) {\n data.push.apply(data, element);\n }\n }\n return data;\n}\n\n/**\n * Creates 3D 'F' BufferInfo.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function create3DFBufferInfo\n */\n\n/**\n * Creates 3D 'F' buffers.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function create3DFBuffers\n */\n\n/**\n * Creates 3D 'F' vertices.\n * An 'F' is useful because you can easily tell which way it is oriented.\n * The created 'F' has position, normal, texcoord, and color arrays.\n *\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction create3DFVertices() {\n\n const positions = [\n // left column front\n 0, 0, 0,\n 0, 150, 0,\n 30, 0, 0,\n 0, 150, 0,\n 30, 150, 0,\n 30, 0, 0,\n\n // top rung front\n 30, 0, 0,\n 30, 30, 0,\n 100, 0, 0,\n 30, 30, 0,\n 100, 30, 0,\n 100, 0, 0,\n\n // middle rung front\n 30, 60, 0,\n 30, 90, 0,\n 67, 60, 0,\n 30, 90, 0,\n 67, 90, 0,\n 67, 60, 0,\n\n // left column back\n 0, 0, 30,\n 30, 0, 30,\n 0, 150, 30,\n 0, 150, 30,\n 30, 0, 30,\n 30, 150, 30,\n\n // top rung back\n 30, 0, 30,\n 100, 0, 30,\n 30, 30, 30,\n 30, 30, 30,\n 100, 0, 30,\n 100, 30, 30,\n\n // middle rung back\n 30, 60, 30,\n 67, 60, 30,\n 30, 90, 30,\n 30, 90, 30,\n 67, 60, 30,\n 67, 90, 30,\n\n // top\n 0, 0, 0,\n 100, 0, 0,\n 100, 0, 30,\n 0, 0, 0,\n 100, 0, 30,\n 0, 0, 30,\n\n // top rung front\n 100, 0, 0,\n 100, 30, 0,\n 100, 30, 30,\n 100, 0, 0,\n 100, 30, 30,\n 100, 0, 30,\n\n // under top rung\n 30, 30, 0,\n 30, 30, 30,\n 100, 30, 30,\n 30, 30, 0,\n 100, 30, 30,\n 100, 30, 0,\n\n // between top rung and middle\n 30, 30, 0,\n 30, 60, 30,\n 30, 30, 30,\n 30, 30, 0,\n 30, 60, 0,\n 30, 60, 30,\n\n // top of middle rung\n 30, 60, 0,\n 67, 60, 30,\n 30, 60, 30,\n 30, 60, 0,\n 67, 60, 0,\n 67, 60, 30,\n\n // front of middle rung\n 67, 60, 0,\n 67, 90, 30,\n 67, 60, 30,\n 67, 60, 0,\n 67, 90, 0,\n 67, 90, 30,\n\n // bottom of middle rung.\n 30, 90, 0,\n 30, 90, 30,\n 67, 90, 30,\n 30, 90, 0,\n 67, 90, 30,\n 67, 90, 0,\n\n // front of bottom\n 30, 90, 0,\n 30, 150, 30,\n 30, 90, 30,\n 30, 90, 0,\n 30, 150, 0,\n 30, 150, 30,\n\n // bottom\n 0, 150, 0,\n 0, 150, 30,\n 30, 150, 30,\n 0, 150, 0,\n 30, 150, 30,\n 30, 150, 0,\n\n // left side\n 0, 0, 0,\n 0, 0, 30,\n 0, 150, 30,\n 0, 0, 0,\n 0, 150, 30,\n 0, 150, 0,\n ];\n\n const texcoords = [\n // left column front\n 0.22, 0.19,\n 0.22, 0.79,\n 0.34, 0.19,\n 0.22, 0.79,\n 0.34, 0.79,\n 0.34, 0.19,\n\n // top rung front\n 0.34, 0.19,\n 0.34, 0.31,\n 0.62, 0.19,\n 0.34, 0.31,\n 0.62, 0.31,\n 0.62, 0.19,\n\n // middle rung front\n 0.34, 0.43,\n 0.34, 0.55,\n 0.49, 0.43,\n 0.34, 0.55,\n 0.49, 0.55,\n 0.49, 0.43,\n\n // left column back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // middle rung back\n 0, 0,\n 1, 0,\n 0, 1,\n 0, 1,\n 1, 0,\n 1, 1,\n\n // top\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // top rung front\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 0,\n 1, 1,\n 0, 1,\n\n // under top rung\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // between top rung and middle\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // top of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // front of middle rung\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom of middle rung.\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // front of bottom\n 0, 0,\n 1, 1,\n 0, 1,\n 0, 0,\n 1, 0,\n 1, 1,\n\n // bottom\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n\n // left side\n 0, 0,\n 0, 1,\n 1, 1,\n 0, 0,\n 1, 1,\n 1, 0,\n ];\n\n const normals = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 0, 0, 1,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 0, 0, -1,\n\n // top\n 6, 0, 1, 0,\n\n // top rung front\n 6, 1, 0, 0,\n\n // under top rung\n 6, 0, -1, 0,\n\n // between top rung and middle\n 6, 1, 0, 0,\n\n // top of middle rung\n 6, 0, 1, 0,\n\n // front of middle rung\n 6, 1, 0, 0,\n\n // bottom of middle rung.\n 6, 0, -1, 0,\n\n // front of bottom\n 6, 1, 0, 0,\n\n // bottom\n 6, 0, -1, 0,\n\n // left side\n 6, -1, 0, 0,\n ]);\n\n const colors = expandRLEData([\n // left column front\n // top rung front\n // middle rung front\n 18, 200, 70, 120,\n\n // left column back\n // top rung back\n // middle rung back\n 18, 80, 70, 200,\n\n // top\n 6, 70, 200, 210,\n\n // top rung front\n 6, 200, 200, 70,\n\n // under top rung\n 6, 210, 100, 70,\n\n // between top rung and middle\n 6, 210, 160, 70,\n\n // top of middle rung\n 6, 70, 180, 210,\n\n // front of middle rung\n 6, 100, 70, 210,\n\n // bottom of middle rung.\n 6, 76, 210, 100,\n\n // front of bottom\n 6, 140, 210, 80,\n\n // bottom\n 6, 90, 130, 110,\n\n // left side\n 6, 160, 160, 220,\n ], [255]);\n\n const numVerts = positions.length / 3;\n\n const arrays = {\n position: createAugmentedTypedArray(3, numVerts),\n texcoord: createAugmentedTypedArray(2, numVerts),\n normal: createAugmentedTypedArray(3, numVerts),\n color: createAugmentedTypedArray(4, numVerts, Uint8Array),\n indices: createAugmentedTypedArray(3, numVerts / 3, Uint16Array),\n };\n\n arrays.position.push(positions);\n arrays.texcoord.push(texcoords);\n arrays.normal.push(normals);\n arrays.color.push(colors);\n\n for (let ii = 0; ii < numVerts; ++ii) {\n arrays.indices.push(ii);\n }\n\n return arrays;\n}\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCresentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n * @function createCresentBuffers\n */\n\n/**\n * Creates crescent BufferInfo.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCrescentBufferInfo\n */\n\n/**\n * Creates crescent buffers.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCrescentBuffers\n */\n\n/**\n * Creates crescent vertices.\n *\n * @param {number} verticalRadius The vertical radius of the crescent.\n * @param {number} outerRadius The outer radius of the crescent.\n * @param {number} innerRadius The inner radius of the crescent.\n * @param {number} thickness The thickness of the crescent.\n * @param {number} subdivisionsDown number of steps around the crescent.\n * @param {number} [startOffset] Where to start arc. Default 0.\n * @param {number} [endOffset] Where to end arg. Default 1.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\n function createCrescentVertices(\n verticalRadius,\n outerRadius,\n innerRadius,\n thickness,\n subdivisionsDown,\n startOffset,\n endOffset) {\n if (subdivisionsDown <= 0) {\n throw new Error('subdivisionDown must be > 0');\n }\n\n startOffset = startOffset || 0;\n endOffset = endOffset || 1;\n\n const subdivisionsThick = 2;\n\n const offsetRange = endOffset - startOffset;\n const numVertices = (subdivisionsDown + 1) * 2 * (2 + subdivisionsThick);\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n\n function lerp(a, b, s) {\n return a + (b - a) * s;\n }\n\n function createArc(arcRadius, x, normalMult, normalAdd, uMult, uAdd) {\n for (let z = 0; z <= subdivisionsDown; z++) {\n const uBack = x / (subdivisionsThick - 1);\n const v = z / subdivisionsDown;\n const xBack = (uBack - 0.5) * 2;\n const angle = (startOffset + (v * offsetRange)) * Math.PI;\n const s = Math.sin(angle);\n const c = Math.cos(angle);\n const radius = lerp(verticalRadius, arcRadius, s);\n const px = xBack * thickness;\n const py = c * verticalRadius;\n const pz = s * radius;\n positions.push(px, py, pz);\n const n = add(multiply$1([0, s, c], normalMult), normalAdd);\n normals.push(n);\n texcoords.push(uBack * uMult + uAdd, v);\n }\n }\n\n // Generate the individual vertices in our vertex buffer.\n for (let x = 0; x < subdivisionsThick; x++) {\n const uBack = (x / (subdivisionsThick - 1) - 0.5) * 2;\n createArc(outerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(outerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 0);\n createArc(innerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0);\n createArc(innerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 1);\n }\n\n // Do outer surface.\n const indices = createAugmentedTypedArray(3, (subdivisionsDown * 2) * (2 + subdivisionsThick), Uint16Array);\n\n function createSurface(leftArcOffset, rightArcOffset) {\n for (let z = 0; z < subdivisionsDown; ++z) {\n // Make triangle 1 of quad.\n indices.push(\n leftArcOffset + z + 0,\n leftArcOffset + z + 1,\n rightArcOffset + z + 0);\n\n // Make triangle 2 of quad.\n indices.push(\n leftArcOffset + z + 1,\n rightArcOffset + z + 1,\n rightArcOffset + z + 0);\n }\n }\n\n const numVerticesDown = subdivisionsDown + 1;\n // front\n createSurface(numVerticesDown * 0, numVerticesDown * 4);\n // right\n createSurface(numVerticesDown * 5, numVerticesDown * 7);\n // back\n createSurface(numVerticesDown * 6, numVerticesDown * 2);\n // left\n createSurface(numVerticesDown * 3, numVerticesDown * 1);\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * Creates cylinder BufferInfo. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createCylinderBufferInfo\n */\n\n /**\n * Creates cylinder buffers. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createCylinderBuffers\n */\n\n /**\n * Creates cylinder vertices. The cylinder will be created around the origin\n * along the y-axis.\n *\n * @param {number} radius Radius of cylinder.\n * @param {number} height Height of cylinder.\n * @param {number} radialSubdivisions The number of subdivisions around the cylinder.\n * @param {number} verticalSubdivisions The number of subdivisions down the cylinder.\n * @param {boolean} [topCap] Create top cap. Default = true.\n * @param {boolean} [bottomCap] Create bottom cap. Default = true.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createCylinderVertices(\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap) {\n return createTruncatedConeVertices(\n radius,\n radius,\n height,\n radialSubdivisions,\n verticalSubdivisions,\n topCap,\n bottomCap);\n}\n\n/**\n * Creates BufferInfo for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createTorusBufferInfo\n */\n\n/**\n * Creates buffers for a torus\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createTorusBuffers\n */\n\n/**\n * Creates vertices for a torus\n *\n * @param {number} radius radius of center of torus circle.\n * @param {number} thickness radius of torus ring.\n * @param {number} radialSubdivisions The number of subdivisions around the torus.\n * @param {number} bodySubdivisions The number of subdivisions around the body torus.\n * @param {boolean} [startAngle] start angle in radians. Default = 0.\n * @param {boolean} [endAngle] end angle in radians. Default = Math.PI * 2.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createTorusVertices(\n radius,\n thickness,\n radialSubdivisions,\n bodySubdivisions,\n startAngle,\n endAngle) {\n if (radialSubdivisions < 3) {\n throw new Error('radialSubdivisions must be 3 or greater');\n }\n\n if (bodySubdivisions < 3) {\n throw new Error('verticalSubdivisions must be 3 or greater');\n }\n\n startAngle = startAngle || 0;\n endAngle = endAngle || Math.PI * 2;\n const range = endAngle - startAngle;\n\n const radialParts = radialSubdivisions + 1;\n const bodyParts = bodySubdivisions + 1;\n const numVertices = radialParts * bodyParts;\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, (radialSubdivisions) * (bodySubdivisions) * 2, Uint16Array);\n\n for (let slice = 0; slice < bodyParts; ++slice) {\n const v = slice / bodySubdivisions;\n const sliceAngle = v * Math.PI * 2;\n const sliceSin = Math.sin(sliceAngle);\n const ringRadius = radius + sliceSin * thickness;\n const ny = Math.cos(sliceAngle);\n const y = ny * thickness;\n for (let ring = 0; ring < radialParts; ++ring) {\n const u = ring / radialSubdivisions;\n const ringAngle = startAngle + u * range;\n const xSin = Math.sin(ringAngle);\n const zCos = Math.cos(ringAngle);\n const x = xSin * ringRadius;\n const z = zCos * ringRadius;\n const nx = xSin * sliceSin;\n const nz = zCos * sliceSin;\n positions.push(x, y, z);\n normals.push(nx, ny, nz);\n texcoords.push(u, 1 - v);\n }\n }\n\n for (let slice = 0; slice < bodySubdivisions; ++slice) { // eslint-disable-line\n for (let ring = 0; ring < radialSubdivisions; ++ring) { // eslint-disable-line\n const nextRingIndex = 1 + ring;\n const nextSliceIndex = 1 + slice;\n indices.push(radialParts * slice + ring,\n radialParts * nextSliceIndex + ring,\n radialParts * slice + nextRingIndex);\n indices.push(radialParts * nextSliceIndex + ring,\n radialParts * nextSliceIndex + nextRingIndex,\n radialParts * slice + nextRingIndex);\n }\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n\n/**\n * Creates a disc BufferInfo. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {module:twgl.BufferInfo} The created BufferInfo.\n * @memberOf module:twgl/primitives\n * @function createDiscBufferInfo\n */\n\n/**\n * Creates disc buffers. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext.\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created buffers.\n * @memberOf module:twgl/primitives\n * @function createDiscBuffers\n */\n\n/**\n * Creates disc vertices. The disc will be in the xz plane, centered at\n * the origin. When creating, at least 3 divisions, or pie\n * pieces, need to be specified, otherwise the triangles making\n * up the disc will be degenerate. You can also specify the\n * number of radial pieces `stacks`. A value of 1 for\n * stacks will give you a simple disc of pie pieces. If you\n * want to create an annulus you can set `innerRadius` to a\n * value > 0. Finally, `stackPower` allows you to have the widths\n * increase or decrease as you move away from the center. This\n * is particularly useful when using the disc as a ground plane\n * with a fixed camera such that you don't need the resolution\n * of small triangles near the perimeter. For example, a value\n * of 2 will produce stacks whose outside radius increases with\n * the square of the stack index. A value of 1 will give uniform\n * stacks.\n *\n * @param {number} radius Radius of the ground plane.\n * @param {number} divisions Number of triangles in the ground plane (at least 3).\n * @param {number} [stacks] Number of radial divisions (default=1).\n * @param {number} [innerRadius] Default 0.\n * @param {number} [stackPower] Power to raise stack size to for decreasing width.\n * @return {Object.} The created vertices.\n * @memberOf module:twgl/primitives\n */\nfunction createDiscVertices(\n radius,\n divisions,\n stacks,\n innerRadius,\n stackPower) {\n if (divisions < 3) {\n throw new Error('divisions must be at least 3');\n }\n\n stacks = stacks ? stacks : 1;\n stackPower = stackPower ? stackPower : 1;\n innerRadius = innerRadius ? innerRadius : 0;\n\n // Note: We don't share the center vertex because that would\n // mess up texture coordinates.\n const numVertices = (divisions + 1) * (stacks + 1);\n\n const positions = createAugmentedTypedArray(3, numVertices);\n const normals = createAugmentedTypedArray(3, numVertices);\n const texcoords = createAugmentedTypedArray(2, numVertices);\n const indices = createAugmentedTypedArray(3, stacks * divisions * 2, Uint16Array);\n\n let firstIndex = 0;\n const radiusSpan = radius - innerRadius;\n const pointsPerStack = divisions + 1;\n\n // Build the disk one stack at a time.\n for (let stack = 0; stack <= stacks; ++stack) {\n const stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower);\n\n for (let i = 0; i <= divisions; ++i) {\n const theta = 2.0 * Math.PI * i / divisions;\n const x = stackRadius * Math.cos(theta);\n const z = stackRadius * Math.sin(theta);\n\n positions.push(x, 0, z);\n normals.push(0, 1, 0);\n texcoords.push(1 - (i / divisions), stack / stacks);\n if (stack > 0 && i !== divisions) {\n // a, b, c and d are the indices of the vertices of a quad. unless\n // the current stack is the one closest to the center, in which case\n // the vertices a and b connect to the center vertex.\n const a = firstIndex + (i + 1);\n const b = firstIndex + i;\n const c = firstIndex + i - pointsPerStack;\n const d = firstIndex + (i + 1) - pointsPerStack;\n\n // Make a quad of the vertices a, b, c, d.\n indices.push(a, b, c);\n indices.push(a, c, d);\n }\n }\n\n firstIndex += divisions + 1;\n }\n\n return {\n position: positions,\n normal: normals,\n texcoord: texcoords,\n indices: indices,\n };\n}\n\n/**\n * creates a random integer between 0 and range - 1 inclusive.\n * @param {number} range\n * @return {number} random value between 0 and range - 1 inclusive.\n * @private\n */\nfunction randInt(range) {\n return Math.random() * range | 0;\n}\n\n/**\n * Used to supply random colors\n * @callback RandomColorFunc\n * @param {number} ndx index of triangle/quad if unindexed or index of vertex if indexed\n * @param {number} channel 0 = red, 1 = green, 2 = blue, 3 = alpha\n * @return {number} a number from 0 to 255\n * @memberOf module:twgl/primitives\n */\n\n/**\n * @typedef {Object} RandomVerticesOptions\n * @property {number} [vertsPerColor] Defaults to 3 for non-indexed vertices\n * @property {module:twgl/primitives.RandomColorFunc} [rand] A function to generate random numbers\n * @memberOf module:twgl/primitives\n */\n\n/**\n * Creates an augmentedTypedArray of random vertex colors.\n * If the vertices are indexed (have an indices array) then will\n * just make random colors. Otherwise assumes they are triangles\n * and makes one random color for every 3 vertices.\n * @param {Object.} vertices Vertices as returned from one of the createXXXVertices functions.\n * @param {module:twgl/primitives.RandomVerticesOptions} [options] options.\n * @return {Object.} same vertices as passed in with `color` added.\n * @memberOf module:twgl/primitives\n */\nfunction makeRandomVertexColors(vertices, options) {\n options = options || {};\n const numElements = vertices.position.numElements;\n const vColors = createAugmentedTypedArray(4, numElements, Uint8Array);\n const rand = options.rand || function(ndx, channel) {\n return channel < 3 ? randInt(256) : 255;\n };\n vertices.color = vColors;\n if (vertices.indices) {\n // just make random colors if index\n for (let ii = 0; ii < numElements; ++ii) {\n vColors.push(rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3));\n }\n } else {\n // make random colors per triangle\n const numVertsPerColor = options.vertsPerColor || 3;\n const numSets = numElements / numVertsPerColor;\n for (let ii = 0; ii < numSets; ++ii) { // eslint-disable-line\n const color = [rand(ii, 0), rand(ii, 1), rand(ii, 2), rand(ii, 3)];\n for (let jj = 0; jj < numVertsPerColor; ++jj) {\n vColors.push(color);\n }\n }\n }\n return vertices;\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a buffers for them\n * @private\n */\nfunction createBufferFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(this, Array.prototype.slice.call(arguments, 1));\n return createBuffersFromArrays(gl, arrays);\n };\n}\n\n/**\n * creates a function that calls fn to create vertices and then\n * creates a bufferInfo object for them\n * @private\n */\nfunction createBufferInfoFunc(fn) {\n return function(gl) {\n const arrays = fn.apply(null, Array.prototype.slice.call(arguments, 1));\n return createBufferInfoFromArrays(gl, arrays);\n };\n}\n\nconst arraySpecPropertyNames = [\n \"numComponents\",\n \"size\",\n \"type\",\n \"normalize\",\n \"stride\",\n \"offset\",\n \"attrib\",\n \"name\",\n \"attribName\",\n];\n\n/**\n * Copy elements from one array to another\n *\n * @param {Array|TypedArray} src source array\n * @param {Array|TypedArray} dst dest array\n * @param {number} dstNdx index in dest to copy src\n * @param {number} [offset] offset to add to copied values\n * @private\n */\nfunction copyElements(src, dst, dstNdx, offset) {\n offset = offset || 0;\n const length = src.length;\n for (let ii = 0; ii < length; ++ii) {\n dst[dstNdx + ii] = src[ii] + offset;\n }\n}\n\n/**\n * Creates an array of the same time\n *\n * @param {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} srcArray array who's type to copy\n * @param {number} length size of new array\n * @return {(number[]|ArrayBufferView|module:twgl.FullArraySpec)} array with same type as srcArray\n * @private\n */\nfunction createArrayOfSameType(srcArray, length) {\n const arraySrc = getArray(srcArray);\n const newArray = new arraySrc.constructor(length);\n let newArraySpec = newArray;\n // If it appears to have been augmented make new one augmented\n if (arraySrc.numComponents && arraySrc.numElements) {\n augmentTypedArray(newArray, arraySrc.numComponents);\n }\n // If it was a full spec make new one a full spec\n if (srcArray.data) {\n newArraySpec = {\n data: newArray,\n };\n copyNamedProperties(arraySpecPropertyNames, srcArray, newArraySpec);\n }\n return newArraySpec;\n}\n\n/**\n * Concatenates sets of vertices\n *\n * Assumes the vertices match in composition. For example\n * if one set of vertices has positions, normals, and indices\n * all sets of vertices must have positions, normals, and indices\n * and of the same type.\n *\n * Example:\n *\n * const cubeVertices = twgl.primitives.createCubeVertices(2);\n * const sphereVertices = twgl.primitives.createSphereVertices(1, 10, 10);\n * // move the sphere 2 units up\n * twgl.primitives.reorientVertices(\n * sphereVertices, twgl.m4.translation([0, 2, 0]));\n * // merge the sphere with the cube\n * const cubeSphereVertices = twgl.primitives.concatVertices(\n * [cubeVertices, sphereVertices]);\n * // turn them into WebGL buffers and attrib data\n * const bufferInfo = twgl.createBufferInfoFromArrays(gl, cubeSphereVertices);\n *\n * @param {module:twgl.Arrays[]} arrays Array of arrays of vertices\n * @return {module:twgl.Arrays} The concatenated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction concatVertices(arrayOfArrays) {\n const names = {};\n let baseName;\n // get names of all arrays.\n // and numElements for each set of vertices\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n Object.keys(arrays).forEach(function(name) { // eslint-disable-line\n if (!names[name]) {\n names[name] = [];\n }\n if (!baseName && name !== 'indices') {\n baseName = name;\n }\n const arrayInfo = arrays[name];\n const numComponents = getNumComponents(arrayInfo, name);\n const array = getArray(arrayInfo);\n const numElements = array.length / numComponents;\n names[name].push(numElements);\n });\n }\n\n // compute length of combined array\n // and return one for reference\n function getLengthOfCombinedArrays(name) {\n let length = 0;\n let arraySpec;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n length += array.length;\n if (!arraySpec || arrayInfo.data) {\n arraySpec = arrayInfo;\n }\n }\n return {\n length: length,\n spec: arraySpec,\n };\n }\n\n function copyArraysToNewArray(name, base, newArray) {\n let baseIndex = 0;\n let offset = 0;\n for (let ii = 0; ii < arrayOfArrays.length; ++ii) {\n const arrays = arrayOfArrays[ii];\n const arrayInfo = arrays[name];\n const array = getArray(arrayInfo);\n if (name === 'indices') {\n copyElements(array, newArray, offset, baseIndex);\n baseIndex += base[ii];\n } else {\n copyElements(array, newArray, offset);\n }\n offset += array.length;\n }\n }\n\n const base = names[baseName];\n\n const newArrays = {};\n Object.keys(names).forEach(function(name) {\n const info = getLengthOfCombinedArrays(name);\n const newArraySpec = createArrayOfSameType(info.spec, info.length);\n copyArraysToNewArray(name, base, getArray(newArraySpec));\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\n/**\n * Creates a duplicate set of vertices\n *\n * This is useful for calling reorientVertices when you\n * also want to keep the original available\n *\n * @param {module:twgl.Arrays} arrays of vertices\n * @return {module:twgl.Arrays} The duplicated vertices.\n * @memberOf module:twgl/primitives\n */\nfunction duplicateVertices(arrays) {\n const newArrays = {};\n Object.keys(arrays).forEach(function(name) {\n const arraySpec = arrays[name];\n const srcArray = getArray(arraySpec);\n const newArraySpec = createArrayOfSameType(arraySpec, srcArray.length);\n copyElements(srcArray, getArray(newArraySpec), 0);\n newArrays[name] = newArraySpec;\n });\n return newArrays;\n}\n\nconst create3DFBufferInfo = createBufferInfoFunc(create3DFVertices);\nconst create3DFBuffers = createBufferFunc(create3DFVertices);\nconst createCubeBufferInfo = createBufferInfoFunc(createCubeVertices);\nconst createCubeBuffers = createBufferFunc(createCubeVertices);\nconst createPlaneBufferInfo = createBufferInfoFunc(createPlaneVertices);\nconst createPlaneBuffers = createBufferFunc(createPlaneVertices);\nconst createSphereBufferInfo = createBufferInfoFunc(createSphereVertices);\nconst createSphereBuffers = createBufferFunc(createSphereVertices);\nconst createTruncatedConeBufferInfo = createBufferInfoFunc(createTruncatedConeVertices);\nconst createTruncatedConeBuffers = createBufferFunc(createTruncatedConeVertices);\nconst createXYQuadBufferInfo = createBufferInfoFunc(createXYQuadVertices);\nconst createXYQuadBuffers = createBufferFunc(createXYQuadVertices);\nconst createCrescentBufferInfo = createBufferInfoFunc(createCrescentVertices);\nconst createCrescentBuffers = createBufferFunc(createCrescentVertices);\nconst createCylinderBufferInfo = createBufferInfoFunc(createCylinderVertices);\nconst createCylinderBuffers = createBufferFunc(createCylinderVertices);\nconst createTorusBufferInfo = createBufferInfoFunc(createTorusVertices);\nconst createTorusBuffers = createBufferFunc(createTorusVertices);\nconst createDiscBufferInfo = createBufferInfoFunc(createDiscVertices);\nconst createDiscBuffers = createBufferFunc(createDiscVertices);\n\n// these were mis-spelled until 4.12\nconst createCresentBufferInfo = createCrescentBufferInfo;\nconst createCresentBuffers = createCrescentBuffers;\nconst createCresentVertices = createCrescentVertices;\n\nvar primitives = /*#__PURE__*/Object.freeze({\n __proto__: null,\n create3DFBufferInfo: create3DFBufferInfo,\n create3DFBuffers: create3DFBuffers,\n create3DFVertices: create3DFVertices,\n createAugmentedTypedArray: createAugmentedTypedArray,\n createCubeBufferInfo: createCubeBufferInfo,\n createCubeBuffers: createCubeBuffers,\n createCubeVertices: createCubeVertices,\n createPlaneBufferInfo: createPlaneBufferInfo,\n createPlaneBuffers: createPlaneBuffers,\n createPlaneVertices: createPlaneVertices,\n createSphereBufferInfo: createSphereBufferInfo,\n createSphereBuffers: createSphereBuffers,\n createSphereVertices: createSphereVertices,\n createTruncatedConeBufferInfo: createTruncatedConeBufferInfo,\n createTruncatedConeBuffers: createTruncatedConeBuffers,\n createTruncatedConeVertices: createTruncatedConeVertices,\n createXYQuadBufferInfo: createXYQuadBufferInfo,\n createXYQuadBuffers: createXYQuadBuffers,\n createXYQuadVertices: createXYQuadVertices,\n createCresentBufferInfo: createCresentBufferInfo,\n createCresentBuffers: createCresentBuffers,\n createCresentVertices: createCresentVertices,\n createCrescentBufferInfo: createCrescentBufferInfo,\n createCrescentBuffers: createCrescentBuffers,\n createCrescentVertices: createCrescentVertices,\n createCylinderBufferInfo: createCylinderBufferInfo,\n createCylinderBuffers: createCylinderBuffers,\n createCylinderVertices: createCylinderVertices,\n createTorusBufferInfo: createTorusBufferInfo,\n createTorusBuffers: createTorusBuffers,\n createTorusVertices: createTorusVertices,\n createDiscBufferInfo: createDiscBufferInfo,\n createDiscBuffers: createDiscBuffers,\n createDiscVertices: createDiscVertices,\n deindexVertices: deindexVertices,\n flattenNormals: flattenNormals,\n makeRandomVertexColors: makeRandomVertexColors,\n reorientDirections: reorientDirections,\n reorientNormals: reorientNormals,\n reorientPositions: reorientPositions,\n reorientVertices: reorientVertices,\n concatVertices: concatVertices,\n duplicateVertices: duplicateVertices\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Gets the gl version as a number\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {number} version of gl\n * @private\n */\n//function getVersionAsNumber(gl) {\n// return parseFloat(gl.getParameter(gl.VERSION).substr(6));\n//}\n\n/**\n * Check if context is WebGL 2.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 2.0\n * @memberOf module:twgl\n */\nfunction isWebGL2(gl) {\n // This is the correct check but it's slow\n // return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0\") === 0;\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGL2RenderingContext;\n return !!gl.texStorage2D;\n}\n\n/**\n * Check if context is WebGL 1.0\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @return {bool} true if it's WebGL 1.0\n * @memberOf module:twgl\n */\nfunction isWebGL1(gl) {\n // This is the correct check but it's slow\n // const version = getVersionAsNumber(gl);\n // return version <= 1.0 && version > 0.0; // because as of 2016/5 Edge returns 0.96\n // This might also be the correct check but I'm assuming it's slow-ish\n // return gl instanceof WebGLRenderingContext;\n return !gl.texStorage2D;\n}\n\n/**\n * Gets a string for WebGL enum\n *\n * Note: Several enums are the same. Without more\n * context (which function) it's impossible to always\n * give the correct enum. As it is, for matching values\n * it gives all enums. Checking the WebGL2RenderingContext\n * that means\n *\n * 0 = ZERO | POINT | NONE | NO_ERROR\n * 1 = ONE | LINES | SYNC_FLUSH_COMMANDS_BIT\n * 32777 = BLEND_EQUATION_RGB | BLEND_EQUATION_RGB\n * 36662 = COPY_READ_BUFFER | COPY_READ_BUFFER_BINDING\n * 36663 = COPY_WRITE_BUFFER | COPY_WRITE_BUFFER_BINDING\n * 36006 = FRAMEBUFFER_BINDING | DRAW_FRAMEBUFFER_BINDING\n *\n * It's also not useful for bits really unless you pass in individual bits.\n * In other words\n *\n * const bits = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;\n * twgl.glEnumToString(gl, bits); // not going to work\n *\n * Note that some enums only exist on extensions. If you\n * want them to show up you need to pass the extension at least\n * once. For example\n *\n * const ext = gl.getExtension('WEBGL_compressed_texture_s3tc');\n * if (ext) {\n * twgl.glEnumToString(ext, 0); // just prime the function\n *\n * ..later..\n *\n * const internalFormat = ext.COMPRESSED_RGB_S3TC_DXT1_EXT;\n * console.log(twgl.glEnumToString(gl, internalFormat));\n *\n * Notice I didn't have to pass the extension the second time. This means\n * you can have place that generically gets an enum for texture formats for example.\n * and as long as you primed the function with the extensions\n *\n * If you're using `twgl.addExtensionsToContext` to enable your extensions\n * then twgl will automatically get the extension's enums.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext or any extension object\n * @param {number} value the value of the enum you want to look up.\n * @return {string} enum string or hex value\n * @memberOf module:twgl\n * @function glEnumToString\n */\nconst glEnumToString = (function() {\n const haveEnumsForType = {};\n const enums = {};\n\n function addEnums(gl) {\n const type = gl.constructor.name;\n if (!haveEnumsForType[type]) {\n for (const key in gl) {\n if (typeof gl[key] === 'number') {\n const existing = enums[gl[key]];\n enums[gl[key]] = existing ? `${existing} | ${key}` : key;\n }\n }\n haveEnumsForType[type] = true;\n }\n }\n\n return function glEnumToString(gl, value) {\n addEnums(gl);\n return enums[value] || (typeof value === 'number' ? `0x${value.toString(16)}` : value);\n };\n}());\n\nvar utils = /*#__PURE__*/Object.freeze({\n __proto__: null,\n glEnumToString: glEnumToString,\n isWebGL1: isWebGL1,\n isWebGL2: isWebGL2\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults$1 = {\n textureColor: new Uint8Array([128, 192, 255, 255]),\n textureOptions: {},\n crossOrigin: undefined,\n};\nconst isArrayBuffer = isArrayBuffer$1;\n\n// Should we make this on demand?\nconst getShared2DContext = function() {\n let s_ctx;\n return function getShared2DContext() {\n s_ctx = s_ctx ||\n ((typeof document !== 'undefined' && document.createElement)\n ? document.createElement(\"canvas\").getContext(\"2d\")\n : null);\n return s_ctx;\n };\n}();\n\n// NOTE: Chrome supports 2D canvas in a Worker (behind flag as of v64 but\n// not only does Firefox NOT support it but Firefox freezes immediately\n// if you try to create one instead of just returning null and continuing.\n// : (global.OffscreenCanvas && (new global.OffscreenCanvas(1, 1)).getContext(\"2d\")); // OffscreenCanvas may not support 2d\n\n// NOTE: We can maybe remove some of the need for the 2d canvas. In WebGL2\n// we can use the various unpack settings. Otherwise we could try using\n// the ability of an ImageBitmap to be cut. Unfortunately cutting an ImageBitmap\n// is async and the current TWGL code expects a non-Async result though that\n// might not be a problem. ImageBitmap though is not available in Edge or Safari\n// as of 2018-01-02\n\n/* PixelFormat */\nconst ALPHA = 0x1906;\nconst RGB = 0x1907;\nconst RGBA$1 = 0x1908;\nconst LUMINANCE = 0x1909;\nconst LUMINANCE_ALPHA = 0x190A;\nconst DEPTH_COMPONENT$1 = 0x1902;\nconst DEPTH_STENCIL$1 = 0x84F9;\n\n/* TextureWrapMode */\n// const REPEAT = 0x2901;\n// const MIRRORED_REPEAT = 0x8370;\nconst CLAMP_TO_EDGE$1 = 0x812f;\n\n/* TextureMagFilter */\nconst NEAREST = 0x2600;\nconst LINEAR$1 = 0x2601;\n\n/* TextureMinFilter */\n// const NEAREST_MIPMAP_NEAREST = 0x2700;\n// const LINEAR_MIPMAP_NEAREST = 0x2701;\n// const NEAREST_MIPMAP_LINEAR = 0x2702;\n// const LINEAR_MIPMAP_LINEAR = 0x2703;\n\n/* Texture Target */\nconst TEXTURE_2D$2 = 0x0de1;\nconst TEXTURE_CUBE_MAP$1 = 0x8513;\nconst TEXTURE_3D$1 = 0x806f;\nconst TEXTURE_2D_ARRAY$1 = 0x8c1a;\n\n/* Cubemap Targets */\nconst TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;\nconst TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;\nconst TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;\nconst TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;\nconst TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a;\n\n/* Texture Parameters */\nconst TEXTURE_MIN_FILTER = 0x2801;\nconst TEXTURE_MAG_FILTER = 0x2800;\nconst TEXTURE_WRAP_S = 0x2802;\nconst TEXTURE_WRAP_T = 0x2803;\nconst TEXTURE_WRAP_R = 0x8072;\nconst TEXTURE_MIN_LOD = 0x813a;\nconst TEXTURE_MAX_LOD = 0x813b;\nconst TEXTURE_BASE_LEVEL = 0x813c;\nconst TEXTURE_MAX_LEVEL = 0x813d;\nconst TEXTURE_COMPARE_MODE = 0x884C;\nconst TEXTURE_COMPARE_FUNC = 0x884D;\n\n/* Pixel store */\nconst UNPACK_ALIGNMENT = 0x0cf5;\nconst UNPACK_ROW_LENGTH = 0x0cf2;\nconst UNPACK_IMAGE_HEIGHT = 0x806e;\nconst UNPACK_SKIP_PIXELS = 0x0cf4;\nconst UNPACK_SKIP_ROWS = 0x0cf3;\nconst UNPACK_SKIP_IMAGES = 0x806d;\nconst UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;\nconst UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;\nconst UNPACK_FLIP_Y_WEBGL = 0x9240;\n\nconst R8 = 0x8229;\nconst R8_SNORM = 0x8F94;\nconst R16F = 0x822D;\nconst R32F = 0x822E;\nconst R8UI = 0x8232;\nconst R8I = 0x8231;\nconst RG16UI = 0x823A;\nconst RG16I = 0x8239;\nconst RG32UI = 0x823C;\nconst RG32I = 0x823B;\nconst RG8 = 0x822B;\nconst RG8_SNORM = 0x8F95;\nconst RG16F = 0x822F;\nconst RG32F = 0x8230;\nconst RG8UI = 0x8238;\nconst RG8I = 0x8237;\nconst R16UI = 0x8234;\nconst R16I = 0x8233;\nconst R32UI = 0x8236;\nconst R32I = 0x8235;\nconst RGB8 = 0x8051;\nconst SRGB8 = 0x8C41;\nconst RGB565$1 = 0x8D62;\nconst RGB8_SNORM = 0x8F96;\nconst R11F_G11F_B10F = 0x8C3A;\nconst RGB9_E5 = 0x8C3D;\nconst RGB16F = 0x881B;\nconst RGB32F = 0x8815;\nconst RGB8UI = 0x8D7D;\nconst RGB8I = 0x8D8F;\nconst RGB16UI = 0x8D77;\nconst RGB16I = 0x8D89;\nconst RGB32UI = 0x8D71;\nconst RGB32I = 0x8D83;\nconst RGBA8 = 0x8058;\nconst SRGB8_ALPHA8 = 0x8C43;\nconst RGBA8_SNORM = 0x8F97;\nconst RGB5_A1$1 = 0x8057;\nconst RGBA4$1 = 0x8056;\nconst RGB10_A2 = 0x8059;\nconst RGBA16F = 0x881A;\nconst RGBA32F = 0x8814;\nconst RGBA8UI = 0x8D7C;\nconst RGBA8I = 0x8D8E;\nconst RGB10_A2UI = 0x906F;\nconst RGBA16UI = 0x8D76;\nconst RGBA16I = 0x8D88;\nconst RGBA32I = 0x8D82;\nconst RGBA32UI = 0x8D70;\n\nconst DEPTH_COMPONENT16$1 = 0x81A5;\nconst DEPTH_COMPONENT24$1 = 0x81A6;\nconst DEPTH_COMPONENT32F$1 = 0x8CAC;\nconst DEPTH32F_STENCIL8$1 = 0x8CAD;\nconst DEPTH24_STENCIL8$1 = 0x88F0;\n\n/* DataType */\nconst BYTE = 0x1400;\nconst UNSIGNED_BYTE$1 = 0x1401;\nconst SHORT = 0x1402;\nconst UNSIGNED_SHORT$1 = 0x1403;\nconst INT$1 = 0x1404;\nconst UNSIGNED_INT$1 = 0x1405;\nconst FLOAT$1 = 0x1406;\nconst UNSIGNED_SHORT_4_4_4_4 = 0x8033;\nconst UNSIGNED_SHORT_5_5_5_1 = 0x8034;\nconst UNSIGNED_SHORT_5_6_5 = 0x8363;\nconst HALF_FLOAT = 0x140B;\nconst HALF_FLOAT_OES = 0x8D61; // Thanks Khronos for making this different >:(\nconst UNSIGNED_INT_2_10_10_10_REV = 0x8368;\nconst UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;\nconst UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;\nconst FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;\nconst UNSIGNED_INT_24_8 = 0x84FA;\n\nconst RG = 0x8227;\nconst RG_INTEGER = 0x8228;\nconst RED = 0x1903;\nconst RED_INTEGER = 0x8D94;\nconst RGB_INTEGER = 0x8D98;\nconst RGBA_INTEGER = 0x8D99;\n\nconst formatInfo = {};\n{\n // NOTE: this is named `numColorComponents` vs `numComponents` so we can let Uglify mangle\n // the name.\n const f = formatInfo;\n f[ALPHA] = { numColorComponents: 1, };\n f[LUMINANCE] = { numColorComponents: 1, };\n f[LUMINANCE_ALPHA] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RED] = { numColorComponents: 1, };\n f[RED_INTEGER] = { numColorComponents: 1, };\n f[RG] = { numColorComponents: 2, };\n f[RG_INTEGER] = { numColorComponents: 2, };\n f[RGB] = { numColorComponents: 3, };\n f[RGB_INTEGER] = { numColorComponents: 3, };\n f[RGBA$1] = { numColorComponents: 4, };\n f[RGBA_INTEGER] = { numColorComponents: 4, };\n f[DEPTH_COMPONENT$1] = { numColorComponents: 1, };\n f[DEPTH_STENCIL$1] = { numColorComponents: 2, };\n}\n\n/**\n * @typedef {Object} TextureFormatDetails\n * @property {number} textureFormat format to pass texImage2D and similar functions.\n * @property {boolean} colorRenderable true if you can render to this format of texture.\n * @property {boolean} textureFilterable true if you can filter the texture, false if you can ony use `NEAREST`.\n * @property {number[]} type Array of possible types you can pass to texImage2D and similar function\n * @property {Object.} bytesPerElementMap A map of types to bytes per element\n * @private\n */\n\nlet s_textureInternalFormatInfo;\nfunction getTextureInternalFormatInfo(internalFormat) {\n if (!s_textureInternalFormatInfo) {\n // NOTE: these properties need unique names so we can let Uglify mangle the name.\n const t = {};\n // unsized formats\n t[ALPHA] = { textureFormat: ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE] = { textureFormat: LUMINANCE, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 2, 4], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[LUMINANCE_ALPHA] = { textureFormat: LUMINANCE_ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [2, 4, 4, 8], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1], };\n t[RGB] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 6, 6, 12, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_5_6_5], };\n t[RGBA$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 8, 8, 16, 2, 2], type: [UNSIGNED_BYTE$1, HALF_FLOAT, HALF_FLOAT_OES, FLOAT$1, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1], };\n t[DEPTH_COMPONENT$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_INT$1, UNSIGNED_SHORT$1], };\n\n // sized formats\n t[R8] = { textureFormat: RED, colorRenderable: true, textureFilterable: true, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8_SNORM] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [1], type: [BYTE], };\n t[R16F] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [4, 2], type: [FLOAT$1, HALF_FLOAT], };\n t[R32F] = { textureFormat: RED, colorRenderable: false, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[R8UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [UNSIGNED_BYTE$1], };\n t[R8I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [1], type: [BYTE], };\n t[R16UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_SHORT$1], };\n t[R16I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [SHORT], };\n t[R32UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[R32I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [INT$1], };\n t[RG8] = { textureFormat: RG, colorRenderable: true, textureFilterable: true, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8_SNORM] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [2], type: [BYTE], };\n t[RG16F] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [8, 4], type: [FLOAT$1, HALF_FLOAT], };\n t[RG32F] = { textureFormat: RG, colorRenderable: false, textureFilterable: false, bytesPerElement: [8], type: [FLOAT$1], };\n t[RG8UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [UNSIGNED_BYTE$1], };\n t[RG8I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [2], type: [BYTE], };\n t[RG16UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_SHORT$1], };\n t[RG16I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [SHORT], };\n t[RG32UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_INT$1], };\n t[RG32I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [INT$1], };\n t[RGB8] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[SRGB8] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB565$1] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_6_5], };\n t[RGB8_SNORM] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [3], type: [BYTE], };\n t[R11F_G11F_B10F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_10F_11F_11F_REV], };\n t[RGB9_E5] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT$1, HALF_FLOAT, UNSIGNED_INT_5_9_9_9_REV], };\n t[RGB16F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6], type: [FLOAT$1, HALF_FLOAT], };\n t[RGB32F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [FLOAT$1], };\n t[RGB8UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [UNSIGNED_BYTE$1], };\n t[RGB8I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [3], type: [BYTE], };\n t[RGB16UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [UNSIGNED_SHORT$1], };\n t[RGB16I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [6], type: [SHORT], };\n t[RGB32UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [UNSIGNED_INT$1], };\n t[RGB32I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: [12], type: [INT$1], };\n t[RGBA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[SRGB8_ALPHA8] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8_SNORM] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [4], type: [BYTE], };\n t[RGB5_A1$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2, 4], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA4$1] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2], type: [UNSIGNED_BYTE$1, UNSIGNED_SHORT_4_4_4_4], };\n t[RGB10_A2] = { textureFormat: RGBA$1, colorRenderable: true, textureFilterable: true, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: true, bytesPerElement: [16, 8], type: [FLOAT$1, HALF_FLOAT], };\n t[RGBA32F] = { textureFormat: RGBA$1, colorRenderable: false, textureFilterable: false, bytesPerElement: [16], type: [FLOAT$1], };\n t[RGBA8UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_BYTE$1], };\n t[RGBA8I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [BYTE], };\n t[RGB10_A2UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_2_10_10_10_REV], };\n t[RGBA16UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [UNSIGNED_SHORT$1], };\n t[RGBA16I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [8], type: [SHORT], };\n t[RGBA32I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [INT$1], };\n t[RGBA32UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: [16], type: [UNSIGNED_INT$1], };\n // Sized Internal\n t[DEPTH_COMPONENT16$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_SHORT$1, UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT24$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT$1], };\n t[DEPTH_COMPONENT32F$1] = { textureFormat: DEPTH_COMPONENT$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT$1], };\n t[DEPTH24_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [UNSIGNED_INT_24_8], };\n t[DEPTH32F_STENCIL8$1] = { textureFormat: DEPTH_STENCIL$1, colorRenderable: true, textureFilterable: false, bytesPerElement: [4], type: [FLOAT_32_UNSIGNED_INT_24_8_REV], };\n\n Object.keys(t).forEach(function(internalFormat) {\n const info = t[internalFormat];\n info.bytesPerElementMap = {};\n info.bytesPerElement.forEach(function(bytesPerElement, ndx) {\n const type = info.type[ndx];\n info.bytesPerElementMap[type] = bytesPerElement;\n });\n });\n s_textureInternalFormatInfo = t;\n }\n return s_textureInternalFormatInfo[internalFormat];\n}\n\n/**\n * Gets the number of bytes per element for a given internalFormat / type\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @param {number} type The type parameter for texImage2D etc..\n * @return {number} the number of bytes per element for the given internalFormat, type combo\n * @memberOf module:twgl/textures\n */\nfunction getBytesPerElementForInternalFormat(internalFormat, type) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n const bytesPerElement = info.bytesPerElementMap[type];\n if (bytesPerElement === undefined) {\n throw \"unknown internal format\";\n }\n return bytesPerElement;\n}\n\n/**\n * Info related to a specific texture internalFormat as returned\n * from {@link module:twgl/textures.getFormatAndTypeForInternalFormat}.\n *\n * @typedef {Object} TextureFormatInfo\n * @property {number} format Format to pass to texImage2D and related functions\n * @property {number} type Type to pass to texImage2D and related functions\n * @memberOf module:twgl/textures\n */\n\n/**\n * Gets the format and type for a given internalFormat\n *\n * @param {number} internalFormat The internal format\n * @return {module:twgl/textures.TextureFormatInfo} the corresponding format and type,\n * @memberOf module:twgl/textures\n */\nfunction getFormatAndTypeForInternalFormat(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return {\n format: info.textureFormat,\n type: info.type[0],\n };\n}\n\n/**\n * Returns true if value is power of 2\n * @param {number} value number to check.\n * @return true if value is power of 2\n * @private\n */\nfunction isPowerOf2(value) {\n return (value & (value - 1)) === 0;\n}\n\n/**\n * Gets whether or not we can generate mips for the given\n * internal format.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number} width The width parameter from texImage2D etc..\n * @param {number} height The height parameter from texImage2D etc..\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canGenerateMipmap(gl, width, height, internalFormat) {\n if (!isWebGL2(gl)) {\n return isPowerOf2(width) && isPowerOf2(height);\n }\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.colorRenderable && info.textureFilterable;\n}\n\n/**\n * Gets whether or not we can generate mips for the given format\n * @param {number} internalFormat The internalFormat parameter from texImage2D etc..\n * @return {boolean} true if we can generate mips\n * @memberOf module:twgl/textures\n */\nfunction canFilter(internalFormat) {\n const info = getTextureInternalFormatInfo(internalFormat);\n if (!info) {\n throw \"unknown internal format\";\n }\n return info.textureFilterable;\n}\n\n/**\n * Gets the number of components for a given image format.\n * @param {number} format the format.\n * @return {number} the number of components for the format.\n * @memberOf module:twgl/textures\n */\nfunction getNumComponentsForFormat(format) {\n const info = formatInfo[format];\n if (!info) {\n throw \"unknown format: \" + format;\n }\n return info.numColorComponents;\n}\n\n/**\n * Gets the texture type for a given array type.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @return {number} the gl texture type\n * @private\n */\nfunction getTextureTypeForArrayType(gl, src, defaultType) {\n if (isArrayBuffer(src)) {\n return getGLTypeForTypedArray(src);\n }\n return defaultType || UNSIGNED_BYTE$1;\n}\n\nfunction guessDimensions(gl, target, width, height, numElements) {\n if (numElements % 1 !== 0) {\n throw \"can't guess dimensions\";\n }\n if (!width && !height) {\n const size = Math.sqrt(numElements / (target === TEXTURE_CUBE_MAP$1 ? 6 : 1));\n if (size % 1 === 0) {\n width = size;\n height = size;\n } else {\n width = numElements;\n height = 1;\n }\n } else if (!height) {\n height = numElements / width;\n if (height % 1) {\n throw \"can't guess dimensions\";\n }\n } else if (!width) {\n width = numElements / height;\n if (width % 1) {\n throw \"can't guess dimensions\";\n }\n }\n return {\n width: width,\n height: height,\n };\n}\n\n/**\n * Sets the default texture color.\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * @param {number[]} color Array of 4 values in the range 0 to 1\n * @deprecated see {@link module:twgl.setDefaults}\n * @memberOf module:twgl/textures\n */\nfunction setDefaultTextureColor(color) {\n defaults$1.textureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\nfunction setDefaults$1(newDefaults) {\n copyExistingProperties(newDefaults, defaults$1);\n if (newDefaults.textureColor) {\n setDefaultTextureColor(newDefaults.textureColor);\n }\n}\n\n/**\n * A function to generate the source for a texture.\n * @callback TextureFunc\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options the texture options\n * @return {*} Returns any of the things documented for `src` for {@link module:twgl.TextureOptions}.\n * @memberOf module:twgl\n */\n\n/**\n * Texture options passed to most texture functions. Each function will use whatever options\n * are appropriate for its needs. This lets you pass the same options to all functions.\n *\n * Note: A `TexImageSource` is defined in the WebGL spec as a `HTMLImageElement`, `HTMLVideoElement`,\n * `HTMLCanvasElement`, `ImageBitmap`, or `ImageData`.\n *\n * @typedef {Object} TextureOptions\n * @property {number} [target] the type of texture `gl.TEXTURE_2D` or `gl.TEXTURE_CUBE_MAP`. Defaults to `gl.TEXTURE_2D`.\n * @property {number} [level] the mip level to affect. Defaults to 0. Note, if set auto will be considered false unless explicitly set to true.\n * @property {number} [width] the width of the texture. Only used if src is an array or typed array or null.\n * @property {number} [height] the height of a texture. Only used if src is an array or typed array or null.\n * @property {number} [depth] the depth of a texture. Only used if src is an array or type array or null and target is `TEXTURE_3D` .\n * @property {number} [min] the min filter setting (eg. `gl.LINEAR`). Defaults to `gl.NEAREST_MIPMAP_LINEAR`\n * or if texture is not a power of 2 on both dimensions then defaults to `gl.LINEAR`.\n * @property {number} [mag] the mag filter setting (eg. `gl.LINEAR`). Defaults to `gl.LINEAR`\n * @property {number} [minMag] both the min and mag filter settings.\n * @property {number} [internalFormat] internal format for texture. Defaults to `gl.RGBA`\n * @property {number} [format] format for texture. Defaults to `gl.RGBA`.\n * @property {number} [type] type for texture. Defaults to `gl.UNSIGNED_BYTE` unless `src` is ArrayBufferView. If `src`\n * is ArrayBufferView defaults to type that matches ArrayBufferView type.\n * @property {number} [wrap] Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to `gl.REPEAT` for 2D unless src is WebGL1 and src not npot and `gl.CLAMP_TO_EDGE` for cube\n * @property {number} [wrapS] Texture wrapping for S. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapT] Texture wrapping for T. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [wrapR] Texture wrapping for R. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.\n * @property {number} [minLod] TEXTURE_MIN_LOD setting\n * @property {number} [maxLod] TEXTURE_MAX_LOD setting\n * @property {number} [baseLevel] TEXTURE_BASE_LEVEL setting\n * @property {number} [maxLevel] TEXTURE_MAX_LEVEL setting\n * @property {number} [compareFunc] TEXTURE_COMPARE_FUNC setting\n * @property {number} [compareMode] TEXTURE_COMPARE_MODE setting\n * @property {number} [unpackAlignment] The `gl.UNPACK_ALIGNMENT` used when uploading an array. Defaults to 1.\n * @property {number[]|ArrayBufferView} [color] Color to initialize this texture with if loading an image asynchronously.\n * The default use a blue 1x1 pixel texture. You can set another default by calling `twgl.setDefaults`\n * or you can set an individual texture's initial color by setting this property. Example: `[1, .5, .5, 1]` = pink\n * @property {number} [premultiplyAlpha] Whether or not to premultiply alpha. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [flipY] Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {number} [colorspaceConversion] Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is.\n * This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override\n * the current setting for specific textures.\n * @property {boolean} [auto] If `undefined` or `true`, in WebGL1, texture filtering is set automatically for non-power of 2 images and\n * mips are generated for power of 2 images. In WebGL2 mips are generated if they can be. Note: if `level` is set above\n * then then `auto` is assumed to be `false` unless explicity set to `true`.\n * @property {number[]} [cubeFaceOrder] The order that cube faces are pulled out of an img or set of images. The default is\n *\n * [gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n * gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n * gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]\n *\n * @property {(number[]|ArrayBufferView|TexImageSource|TexImageSource[]|string|string[]|module:twgl.TextureFunc)} [src] source for texture\n *\n * If `string` then it's assumed to be a URL to an image. The image will be downloaded async. A usable\n * 1x1 pixel texture will be returned immediately. The texture will be updated once the image has downloaded.\n * If `target` is `gl.TEXTURE_CUBE_MAP` will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.\n * The pieces will be uploaded in `cubeFaceOrder`\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_CUBE_MAP` then it must have 6 entries, one for each face of a cube map.\n *\n * If `string[]` or `TexImageSource[]` and target is `gl.TEXTURE_2D_ARRAY` then each entry is a slice of the a 2d array texture\n * and will be scaled to the specified width and height OR to the size of the first image that loads.\n *\n * If `TexImageSource` then it wil be used immediately to create the contents of the texture. Examples `HTMLImageElement`,\n * `HTMLCanvasElement`, `HTMLVideoElement`.\n *\n * If `number[]` or `ArrayBufferView` it's assumed to be data for a texture. If `width` or `height` is\n * not specified it is guessed as follows. First the number of elements is computed by `src.length / numComponents`\n * where `numComponents` is derived from `format`. If `target` is `gl.TEXTURE_CUBE_MAP` then `numElements` is divided\n * by 6. Then\n *\n * * If neither `width` nor `height` are specified and `sqrt(numElements)` is an integer then width and height\n * are set to `sqrt(numElements)`. Otherwise `width = numElements` and `height = 1`.\n *\n * * If only one of `width` or `height` is specified then the other equals `numElements / specifiedDimension`.\n *\n * If `number[]` will be converted to `type`.\n *\n * If `src` is a function it will be called with a `WebGLRenderingContext` and these options.\n * Whatever it returns is subject to these rules. So it can return a string url, an `HTMLElement`\n * an array etc...\n *\n * If `src` is undefined then an empty texture will be created of size `width` by `height`.\n *\n * @property {string} [crossOrigin] What to set the crossOrigin property of images when they are downloaded.\n * default: undefined. Also see {@link module:twgl.setDefaults}.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets any packing state that will be set based on the options.\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setPackState(gl, options) {\n if (options.colorspaceConversion !== undefined) {\n gl.pixelStorei(UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion);\n }\n if (options.premultiplyAlpha !== undefined) {\n gl.pixelStorei(UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha);\n }\n if (options.flipY !== undefined) {\n gl.pixelStorei(UNPACK_FLIP_Y_WEBGL, options.flipY);\n }\n}\n\n/**\n * Set skip state to defaults\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @private\n */\nfunction setSkipStateToDefault(gl) {\n gl.pixelStorei(UNPACK_ALIGNMENT, 4);\n if (isWebGL2(gl)) {\n gl.pixelStorei(UNPACK_ROW_LENGTH, 0);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_PIXELS, 0);\n gl.pixelStorei(UNPACK_SKIP_ROWS, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n }\n}\n\n/**\n * Sets the parameters of a texture or sampler\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {number|WebGLSampler} target texture target or sampler\n * @param {function()} parameteriFn texParameteri or samplerParameteri fn\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @private\n */\nfunction setTextureSamplerParameters(gl, target, parameteriFn, options) {\n if (options.minMag) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.minMag);\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.minMag);\n }\n if (options.min) {\n parameteriFn.call(gl, target, TEXTURE_MIN_FILTER, options.min);\n }\n if (options.mag) {\n parameteriFn.call(gl, target, TEXTURE_MAG_FILTER, options.mag);\n }\n if (options.wrap) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrap);\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrap);\n if (target === TEXTURE_3D$1 || isSampler(gl, target)) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrap);\n }\n }\n if (options.wrapR) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_R, options.wrapR);\n }\n if (options.wrapS) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_S, options.wrapS);\n }\n if (options.wrapT) {\n parameteriFn.call(gl, target, TEXTURE_WRAP_T, options.wrapT);\n }\n if (options.minLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MIN_LOD, options.minLod);\n }\n if (options.maxLod !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LOD, options.maxLod);\n }\n if (options.baseLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_BASE_LEVEL, options.baseLevel);\n }\n if (options.maxLevel !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_MAX_LEVEL, options.maxLevel);\n }\n if (options.compareFunc !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_FUNC, options.compareFunc);\n }\n if (options.compareMode !== undefined) {\n parameteriFn.call(gl, target, TEXTURE_COMPARE_MODE, options.compareMode);\n }\n}\n\n/**\n * Sets the texture parameters of a texture.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureParameters(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n setTextureSamplerParameters(gl, target, gl.texParameteri, options);\n}\n\n/**\n * Sets the sampler parameters of a sampler.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLSampler} sampler the WebGLSampler to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setSamplerParameters(gl, sampler, options) {\n setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);\n}\n\n/**\n * Creates a new sampler object and sets parameters.\n *\n * Example:\n *\n * const sampler = twgl.createSampler(gl, {\n * minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER\n * wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per sampler.\n * @return {Object.} the created samplers by name\n * @private\n */\nfunction createSampler(gl, options) {\n const sampler = gl.createSampler();\n setSamplerParameters(gl, sampler, options);\n return sampler;\n}\n\n/**\n * Creates a multiple sampler objects and sets parameters on each.\n *\n * Example:\n *\n * const samplers = twgl.createSamplers(gl, {\n * nearest: {\n * minMag: gl.NEAREST,\n * },\n * nearestClampS: {\n * minMag: gl.NEAREST,\n * wrapS: gl.CLAMP_TO_NEAREST,\n * },\n * linear: {\n * minMag: gl.LINEAR,\n * },\n * nearestClamp: {\n * minMag: gl.NEAREST,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClamp: {\n * minMag: gl.LINEAR,\n * wrap: gl.CLAMP_TO_EDGE,\n * },\n * linearClampT: {\n * minMag: gl.LINEAR,\n * wrapT: gl.CLAMP_TO_EDGE,\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler\n * @private\n */\nfunction createSamplers(gl, samplerOptions) {\n const samplers = {};\n Object.keys(samplerOptions).forEach(function(name) {\n samplers[name] = createSampler(gl, samplerOptions[name]);\n });\n return samplers;\n}\n\n/**\n * Makes a 1x1 pixel\n * If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`.\n * @param {(number[]|ArrayBufferView)} [color] The color using 0-1 values\n * @return {Uint8Array} Unit8Array with color.\n * @private\n */\nfunction make1Pixel(color) {\n color = color || defaults$1.textureColor;\n if (isArrayBuffer(color)) {\n return color;\n }\n return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);\n}\n\n/**\n * Sets filtering or generates mips for texture based on width or height\n * If width or height is not passed in uses `options.width` and//or `options.height`\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @param {number} [width] width of texture\n * @param {number} [height] height of texture\n * @param {number} [internalFormat] The internalFormat parameter from texImage2D etc..\n * @memberOf module:twgl/textures\n */\nfunction setTextureFilteringForSize(gl, tex, options, width, height, internalFormat) {\n options = options || defaults$1.textureOptions;\n internalFormat = internalFormat || RGBA$1;\n const target = options.target || TEXTURE_2D$2;\n width = width || options.width;\n height = height || options.height;\n gl.bindTexture(target, tex);\n if (canGenerateMipmap(gl, width, height, internalFormat)) {\n gl.generateMipmap(target);\n } else {\n const filtering = canFilter(internalFormat) ? LINEAR$1 : NEAREST;\n gl.texParameteri(target, TEXTURE_MIN_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_MAG_FILTER, filtering);\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n}\n\nfunction shouldAutomaticallySetTextureFilteringForSize(options) {\n return options.auto === true || (options.auto === undefined && options.level === undefined);\n}\n\n/**\n * Gets an array of cubemap face enums\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @return {number[]} cubemap face enums\n * @private\n */\nfunction getCubeFaceOrder(gl, options) {\n options = options || {};\n return options.cubeFaceOrder || [\n TEXTURE_CUBE_MAP_POSITIVE_X,\n TEXTURE_CUBE_MAP_NEGATIVE_X,\n TEXTURE_CUBE_MAP_POSITIVE_Y,\n TEXTURE_CUBE_MAP_NEGATIVE_Y,\n TEXTURE_CUBE_MAP_POSITIVE_Z,\n TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ];\n}\n\n/**\n * @typedef {Object} FaceInfo\n * @property {number} face gl enum for texImage2D\n * @property {number} ndx face index (0 - 5) into source data\n * @ignore\n */\n\n/**\n * Gets an array of FaceInfos\n * There's a bug in some NVidia drivers that will crash the driver if\n * `gl.TEXTURE_CUBE_MAP_POSITIVE_X` is not uploaded first. So, we take\n * the user's desired order from his faces to WebGL and make sure we\n * do the faces in WebGL order\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @return {FaceInfo[]} cubemap face infos. Arguably the `face` property of each element is redundant but\n * it's needed internally to sort the array of `ndx` properties by `face`.\n * @private\n */\nfunction getCubeFacesWithNdx(gl, options) {\n const faces = getCubeFaceOrder(gl, options);\n // work around bug in NVidia drivers. We have to upload the first face first else the driver crashes :(\n const facesWithNdx = faces.map(function(face, ndx) {\n return { face: face, ndx: ndx };\n });\n facesWithNdx.sort(function(a, b) {\n return a.face - b.face;\n });\n return facesWithNdx;\n}\n\n/**\n * Set a texture from the contents of an element. Will also set\n * texture filtering or generate mips based on the dimensions of the element\n * unless `options.auto === false`. If `target === gl.TEXTURE_CUBE_MAP` will\n * attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {HTMLElement} element a canvas, img, or video element.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @kind function\n */\nfunction setTextureFromElement(gl, tex, element, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n const level = options.level || 0;\n let width = element.width;\n let height = element.height;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // guess the parts\n const imgWidth = element.width;\n const imgHeight = element.height;\n let size;\n let slices;\n if (imgWidth / 6 === imgHeight) {\n // It's 6x1\n size = imgHeight;\n slices = [0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0];\n } else if (imgHeight / 6 === imgWidth) {\n // It's 1x6\n size = imgWidth;\n slices = [0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];\n } else if (imgWidth / 3 === imgHeight / 2) {\n // It's 3x2\n size = imgWidth / 3;\n slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];\n } else if (imgWidth / 2 === imgHeight / 3) {\n // It's 2x3\n size = imgWidth / 2;\n slices = [0, 0, 1, 0, 0, 1, 1, 1, 0, 2, 1, 2];\n } else {\n throw \"can't figure out cube map from element: \" + (element.src ? element.src : element.nodeName);\n }\n const ctx = getShared2DContext();\n if (ctx) {\n ctx.canvas.width = size;\n ctx.canvas.height = size;\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n ctx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);\n gl.texImage2D(f.face, level, internalFormat, format, type, ctx.canvas);\n });\n // Free up the canvas memory\n ctx.canvas.width = 1;\n ctx.canvas.height = 1;\n } else if (typeof createImageBitmap !== 'undefined') {\n // NOTE: It seems like we should prefer ImageBitmap because unlike canvas it's\n // note lossy? (alpha is not premultiplied? although I'm not sure what\n width = size;\n height = size;\n getCubeFacesWithNdx(gl, options).forEach(function(f) {\n const xOffset = slices[f.ndx * 2 + 0] * size;\n const yOffset = slices[f.ndx * 2 + 1] * size;\n // We can't easily use a default texture color here as it would have to match\n // the type across all faces where as with a 2D one there's only one face\n // so we're replacing everything all at once. It also has to be the correct size.\n // On the other hand we need all faces to be the same size so as one face loads\n // the rest match else the texture will be un-renderable.\n gl.texImage2D(f.face, level, internalFormat, size, size, 0, format, type, null);\n createImageBitmap(element, xOffset, yOffset, size, size, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n })\n .then(function(imageBitmap) {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n gl.texImage2D(f.face, level, internalFormat, format, type, imageBitmap);\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n });\n });\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n const smallest = Math.min(element.width, element.height);\n const largest = Math.max(element.width, element.height);\n const depth = largest / smallest;\n if (depth % 1 !== 0) {\n throw \"can not compute 3D dimensions of element\";\n }\n const xMult = element.width === largest ? 1 : 0;\n const yMult = element.height === largest ? 1 : 0;\n gl.pixelStorei(UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(UNPACK_ROW_LENGTH, element.width);\n gl.pixelStorei(UNPACK_IMAGE_HEIGHT, 0);\n gl.pixelStorei(UNPACK_SKIP_IMAGES, 0);\n gl.texImage3D(target, level, internalFormat, smallest, smallest, smallest, 0, format, type, null);\n for (let d = 0; d < depth; ++d) {\n const srcX = d * smallest * xMult;\n const srcY = d * smallest * yMult;\n gl.pixelStorei(UNPACK_SKIP_PIXELS, srcX);\n gl.pixelStorei(UNPACK_SKIP_ROWS, srcY);\n gl.texSubImage3D(target, level, 0, 0, d, smallest, smallest, 1, format, type, element);\n }\n setSkipStateToDefault(gl);\n } else {\n gl.texImage2D(target, level, internalFormat, format, type, element);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n}\n\nfunction noop() {\n}\n\n/**\n * Checks whether the url's origin is the same so that we can set the `crossOrigin`\n * @param {string} url url to image\n * @returns {boolean} true if the window's origin is the same as image's url\n * @private\n */\nfunction urlIsSameOrigin(url) {\n if (typeof document !== 'undefined') {\n // for IE really\n const a = document.createElement('a');\n a.href = url;\n return a.hostname === location.hostname &&\n a.port === location.port &&\n a.protocol === location.protocol;\n } else {\n const localOrigin = (new URL(location.href)).origin;\n const urlOrigin = (new URL(url, location.href)).origin;\n return urlOrigin === localOrigin;\n }\n}\n\nfunction setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin) {\n return crossOrigin === undefined && !urlIsSameOrigin(url)\n ? 'anonymous'\n : crossOrigin;\n}\n\n/**\n * Loads an image\n * @param {string} url url to image\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @return {HTMLImageElement} the image being loaded.\n * @private\n */\nfunction loadImage(url, crossOrigin, callback) {\n callback = callback || noop;\n let img;\n crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults$1.crossOrigin;\n crossOrigin = setToAnonymousIfUndefinedAndURLIsNotSameOrigin(url, crossOrigin);\n if (typeof Image !== 'undefined') {\n img = new Image();\n if (crossOrigin !== undefined) {\n img.crossOrigin = crossOrigin;\n }\n\n const clearEventHandlers = function clearEventHandlers() {\n img.removeEventListener('error', onError); // eslint-disable-line\n img.removeEventListener('load', onLoad); // eslint-disable-line\n img = null;\n };\n\n const onError = function onError() {\n const msg = \"couldn't load image: \" + url;\n error$1(msg);\n callback(msg, img);\n clearEventHandlers();\n };\n\n const onLoad = function onLoad() {\n callback(null, img);\n clearEventHandlers();\n };\n\n img.addEventListener('error', onError);\n img.addEventListener('load', onLoad);\n img.src = url;\n return img;\n } else if (typeof ImageBitmap !== 'undefined') {\n let err;\n let bm;\n const cb = function cb() {\n callback(err, bm);\n };\n\n const options = {};\n if (crossOrigin) {\n options.mode = 'cors'; // TODO: not sure how to translate image.crossOrigin\n }\n fetch(url, options).then(function(response) {\n if (!response.ok) {\n throw response;\n }\n return response.blob();\n }).then(function(blob) {\n return createImageBitmap(blob, {\n premultiplyAlpha: 'none',\n colorSpaceConversion: 'none',\n });\n }).then(function(bitmap) {\n // not sure if this works. We don't want\n // to catch the user's error. So, call\n // the callback in a timeout so we're\n // not in this scope inside the promise.\n bm = bitmap;\n setTimeout(cb);\n }).catch(function(e) {\n err = e;\n setTimeout(cb);\n });\n img = null;\n }\n return img;\n}\n\n/**\n * check if object is a TexImageSource\n *\n * @param {Object} obj Object to test\n * @return {boolean} true if object is a TexImageSource\n * @private\n */\nfunction isTexImageSource(obj) {\n return (typeof ImageBitmap !== 'undefined' && obj instanceof ImageBitmap) ||\n (typeof ImageData !== 'undefined' && obj instanceof ImageData) ||\n (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement);\n}\n\n/**\n * if obj is an TexImageSource then just\n * uses it otherwise if obj is a string\n * then load it first.\n *\n * @param {string|TexImageSource} obj\n * @param {string} crossOrigin\n * @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null\n * if there was an error\n * @private\n */\nfunction loadAndUseImage(obj, crossOrigin, callback) {\n if (isTexImageSource(obj)) {\n setTimeout(function() {\n callback(null, obj);\n });\n return obj;\n }\n\n return loadImage(obj, crossOrigin, callback);\n}\n\n/**\n * Sets a texture to a 1x1 pixel color. If `options.color === false` is nothing happens. If it's not set\n * the default texture color is used which can be set by calling `setDefaultTextureColor`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction setTextureTo1PixelColor(gl, tex, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n if (options.color === false) {\n return;\n }\n // Assume it's a URL\n // Put 1x1 pixels in texture. That makes it renderable immediately regardless of filtering.\n const color = make1Pixel(options.color);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, 0, RGBA$1, 1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n } else {\n gl.texImage2D(target, 0, RGBA$1, 1, 1, 0, RGBA$1, UNSIGNED_BYTE$1, color);\n }\n}\n\n/**\n * The src image(s) used to create a texture.\n *\n * When you call {@link module:twgl.createTexture} or {@link module:twgl.createTextures}\n * you can pass in urls for images to load into the textures. If it's a single url\n * then this will be a single HTMLImageElement. If it's an array of urls used for a cubemap\n * this will be a corresponding array of images for the cubemap.\n *\n * @typedef {HTMLImageElement|HTMLImageElement[]} TextureSrc\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback TextureReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} texture the texture.\n * @param {module:twgl.TextureSrc} source image(s) used to as the src for the texture\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when all images have finished downloading and been uploaded into their respective textures\n * @callback TexturesReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {Object.} textures the created textures by name. Same as returned by {@link module:twgl.createTextures}.\n * @param {Object.} sources the image(s) used for the texture by name.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback CubemapReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each face.\n * @memberOf module:twgl\n */\n\n/**\n * A callback for when an image finished downloading and been uploaded into a texture\n * @callback ThreeDReadyCallback\n * @param {*} err If truthy there was an error.\n * @param {WebGLTexture} tex the texture.\n * @param {HTMLImageElement[]} imgs the images for each slice.\n * @memberOf module:twgl\n */\n\n/**\n * Loads a texture from an image from a Url as specified in `options.src`\n * If `options.color !== false` will set the texture to a 1x1 pixel color so that the texture is\n * immediately useable. It will be updated with the contents of the image once the image has finished\n * downloading. Filtering options will be set as appropriate for image unless `options.auto === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A function to be called when the image has finished loading. err will\n * be non null if there was an error.\n * @return {HTMLImageElement} the image being downloaded.\n * @memberOf module:twgl/textures\n */\nfunction loadTextureFromUrl(gl, tex, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n const img = loadAndUseImage(options.src, options.crossOrigin, function(err, img) {\n if (err) {\n callback(err, tex, img);\n } else {\n setTextureFromElement(gl, tex, img, options);\n callback(null, tex, img);\n }\n });\n return img;\n}\n\n/**\n * Loads a cubemap from 6 urls or TexImageSources as specified in `options.src`. Will set the cubemap to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.CubemapReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadCubemapFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n if (urls.length !== 6) {\n throw \"there must be 6 urls for a cubemap\";\n }\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D$2;\n if (target !== TEXTURE_CUBE_MAP$1) {\n throw \"target must be TEXTURE_CUBE_MAP\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = 6;\n const errors = [];\n const faces = getCubeFaceOrder(gl, options);\n let imgs; // eslint-disable-line\n\n function uploadImg(faceTarget) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n if (img.width !== img.height) {\n errors.push(\"cubemap face img is not a square: \" + img.src);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n // So assuming this is the first image we now have one face that's img sized\n // and 5 faces that are 1x1 pixel so size the other faces\n if (numToLoad === 5) {\n // use the default order\n getCubeFaceOrder().forEach(function(otherTarget) {\n // Should we re-use the same face or a color?\n gl.texImage2D(otherTarget, level, internalFormat, format, type, img);\n });\n } else {\n gl.texImage2D(faceTarget, level, internalFormat, format, type, img);\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(faces[ndx]));\n });\n}\n\n/**\n * Loads a 2d array or 3d texture from urls OR TexImageSources as specified in `options.src`.\n * Will set the texture to a 1x1 pixel color\n * so that it is usable immediately unless `option.color === false`.\n *\n * If the width and height is not specified the width and height of the first\n * image loaded will be used. Note that since images are loaded async\n * which image downloads first is unknown.\n *\n * If an image is not the same size as the width and height it will be scaled\n * to that width and height.\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.ThreeDReadyCallback} [callback] A function to be called when all the images have finished loading. err will\n * be non null if there was an error.\n * @memberOf module:twgl/textures\n * @private\n */\nfunction loadSlicesFromUrls(gl, tex, options, callback) {\n callback = callback || noop;\n const urls = options.src;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || UNSIGNED_BYTE$1;\n const target = options.target || TEXTURE_2D_ARRAY$1;\n if (target !== TEXTURE_3D$1 && target !== TEXTURE_2D_ARRAY$1) {\n throw \"target must be TEXTURE_3D or TEXTURE_2D_ARRAY\";\n }\n setTextureTo1PixelColor(gl, tex, options);\n // Because it's async we need to copy the options.\n options = Object.assign({}, options);\n let numToLoad = urls.length;\n const errors = [];\n let imgs; // eslint-disable-line\n const level = options.level || 0;\n let width = options.width;\n let height = options.height;\n const depth = urls.length;\n let firstImage = true;\n\n function uploadImg(slice) {\n return function(err, img) {\n --numToLoad;\n if (err) {\n errors.push(err);\n } else {\n setPackState(gl, options);\n gl.bindTexture(target, tex);\n\n if (firstImage) {\n firstImage = false;\n width = options.width || img.width;\n height = options.height || img.height;\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n\n // put it in every slice otherwise some slices will be 0,0,0,0\n for (let s = 0; s < depth; ++s) {\n gl.texSubImage3D(target, level, 0, 0, s, width, height, 1, format, type, img);\n }\n } else {\n let src = img;\n let ctx;\n if (img.width !== width || img.height !== height) {\n // Size the image to fix\n ctx = getShared2DContext();\n src = ctx.canvas;\n ctx.canvas.width = width;\n ctx.canvas.height = height;\n ctx.drawImage(img, 0, 0, width, height);\n }\n\n gl.texSubImage3D(target, level, 0, 0, slice, width, height, 1, format, type, src);\n\n // free the canvas memory\n if (ctx && src === ctx.canvas) {\n ctx.canvas.width = 0;\n ctx.canvas.height = 0;\n }\n }\n\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n gl.generateMipmap(target);\n }\n }\n\n if (numToLoad === 0) {\n callback(errors.length ? errors : undefined, tex, imgs);\n }\n };\n }\n\n imgs = urls.map(function(url, ndx) {\n return loadAndUseImage(url, options.crossOrigin, uploadImg(ndx));\n });\n}\n\n/**\n * Sets a texture from an array or typed array. If the width or height is not provided will attempt to\n * guess the size. See {@link module:twgl.TextureOptions}.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {(number[]|ArrayBufferView)} src An array or typed arry with texture data.\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * This is often the same options you passed in when you created the texture.\n * @memberOf module:twgl/textures\n */\nfunction setTextureFromArray(gl, tex, src, options) {\n options = options || defaults$1.textureOptions;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n let width = options.width;\n let height = options.height;\n let depth = options.depth;\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n if (!isArrayBuffer(src)) {\n const Type = getTypedArrayTypeForGLType(type);\n src = new Type(src);\n } else if (src instanceof Uint8ClampedArray) {\n src = new Uint8Array(src.buffer);\n }\n\n const bytesPerElement = getBytesPerElementForInternalFormat(internalFormat, type);\n const numElements = src.byteLength / bytesPerElement; // TODO: check UNPACK_ALIGNMENT?\n if (numElements % 1) {\n throw \"length wrong size for format: \" + glEnumToString(gl, format);\n }\n let dimensions;\n if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n if (!width && !height && !depth) {\n const size = Math.cbrt(numElements);\n if (size % 1 !== 0) {\n throw \"can't guess cube size of array of numElements: \" + numElements;\n }\n width = size;\n height = size;\n depth = size;\n } else if (width && (!height || !depth)) {\n dimensions = guessDimensions(gl, target, height, depth, numElements / width);\n height = dimensions.width;\n depth = dimensions.height;\n } else if (height && (!width || !depth)) {\n dimensions = guessDimensions(gl, target, width, depth, numElements / height);\n width = dimensions.width;\n depth = dimensions.height;\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements / depth);\n width = dimensions.width;\n height = dimensions.height;\n }\n } else {\n dimensions = guessDimensions(gl, target, width, height, numElements);\n width = dimensions.width;\n height = dimensions.height;\n }\n setSkipStateToDefault(gl);\n gl.pixelStorei(UNPACK_ALIGNMENT, options.unpackAlignment || 1);\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n const elementsPerElement = bytesPerElement / src.BYTES_PER_ELEMENT;\n const faceSize = numElements / 6 * elementsPerElement;\n\n getCubeFacesWithNdx(gl, options).forEach(f => {\n const offset = faceSize * f.ndx;\n const data = src.subarray(offset, offset + faceSize);\n gl.texImage2D(f.face, level, internalFormat, width, height, 0, format, type, data);\n });\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, src);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, src);\n }\n return {\n width: width,\n height: height,\n depth: depth,\n type: type,\n };\n}\n\n/**\n * Sets a texture with no contents of a certain size. In other words calls `gl.texImage2D` with `null`.\n * You must set `options.width` and `options.height`.\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the WebGLTexture to set parameters for\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @memberOf module:twgl/textures\n */\nfunction setEmptyTexture(gl, tex, options) {\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n const type = options.type || formatType.type;\n setPackState(gl, options);\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, options.width, options.height, options.depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, options.width, options.height, 0, format, type, null);\n }\n}\n\n/**\n * Creates a texture based on the options passed in.\n *\n * Note: may reset UNPACK_ALIGNMENT, UNPACK_ROW_LENGTH, UNPACK_IMAGE_HEIGHT, UNPACK_SKIP_IMAGES\n * UNPACK_SKIP_PIXELS, and UNPACK_SKIP_ROWS\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.\n * @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture.\n * @return {WebGLTexture} the created texture.\n * @memberOf module:twgl/textures\n */\nfunction createTexture(gl, options, callback) {\n callback = callback || noop;\n options = options || defaults$1.textureOptions;\n const tex = gl.createTexture();\n const target = options.target || TEXTURE_2D$2;\n let width = options.width || 1;\n let height = options.height || 1;\n const internalFormat = options.internalFormat || RGBA$1;\n gl.bindTexture(target, tex);\n if (target === TEXTURE_CUBE_MAP$1) {\n // this should have been the default for cubemaps :(\n gl.texParameteri(target, TEXTURE_WRAP_S, CLAMP_TO_EDGE$1);\n gl.texParameteri(target, TEXTURE_WRAP_T, CLAMP_TO_EDGE$1);\n }\n let src = options.src;\n if (src) {\n if (typeof src === \"function\") {\n src = src(gl, options);\n }\n if (typeof (src) === \"string\") {\n loadTextureFromUrl(gl, tex, options, callback);\n } else if (isArrayBuffer(src) ||\n (Array.isArray(src) && (\n typeof src[0] === 'number' ||\n Array.isArray(src[0]) ||\n isArrayBuffer(src[0]))\n )\n ) {\n const dimensions = setTextureFromArray(gl, tex, src, options);\n width = dimensions.width;\n height = dimensions.height;\n } else if (Array.isArray(src) && (typeof (src[0]) === 'string' || isTexImageSource(src[0]))) {\n if (target === TEXTURE_CUBE_MAP$1) {\n loadCubemapFromUrls(gl, tex, options, callback);\n } else {\n loadSlicesFromUrls(gl, tex, options, callback);\n }\n } else { // if (isTexImageSource(src))\n setTextureFromElement(gl, tex, src, options);\n width = src.width;\n height = src.height;\n }\n } else {\n setEmptyTexture(gl, tex, options);\n }\n if (shouldAutomaticallySetTextureFilteringForSize(options)) {\n setTextureFilteringForSize(gl, tex, options, width, height, internalFormat);\n }\n setTextureParameters(gl, tex, options);\n return tex;\n}\n\n/**\n * Resizes a texture based on the options passed in.\n *\n * Note: This is not a generic resize anything function.\n * It's mostly used by {@link module:twgl.resizeFramebufferInfo}\n * It will use `options.src` if it exists to try to determine a `type`\n * otherwise it will assume `gl.UNSIGNED_BYTE`. No data is provided\n * for the texture. Texture parameters will be set accordingly\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {WebGLTexture} tex the texture to resize\n * @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.\n * @param {number} [width] the new width. If not passed in will use `options.width`\n * @param {number} [height] the new height. If not passed in will use `options.height`\n * @param {number} [depth] the new depth. If not passed in will use `options.depth`\n * @memberOf module:twgl/textures\n */\nfunction resizeTexture(gl, tex, options, width, height, depth) {\n width = width || options.width;\n height = height || options.height;\n depth = depth || options.depth;\n const target = options.target || TEXTURE_2D$2;\n gl.bindTexture(target, tex);\n const level = options.level || 0;\n const internalFormat = options.internalFormat || options.format || RGBA$1;\n const formatType = getFormatAndTypeForInternalFormat(internalFormat);\n const format = options.format || formatType.format;\n let type;\n const src = options.src;\n if (!src) {\n type = options.type || formatType.type;\n } else if (isArrayBuffer(src) || (Array.isArray(src) && typeof (src[0]) === 'number')) {\n type = options.type || getTextureTypeForArrayType(gl, src, formatType.type);\n } else {\n type = options.type || formatType.type;\n }\n if (target === TEXTURE_CUBE_MAP$1) {\n for (let ii = 0; ii < 6; ++ii) {\n gl.texImage2D(TEXTURE_CUBE_MAP_POSITIVE_X + ii, level, internalFormat, width, height, 0, format, type, null);\n }\n } else if (target === TEXTURE_3D$1 || target === TEXTURE_2D_ARRAY$1) {\n gl.texImage3D(target, level, internalFormat, width, height, depth, 0, format, type, null);\n } else {\n gl.texImage2D(target, level, internalFormat, width, height, 0, format, type, null);\n }\n}\n\n/**\n * Check if a src is an async request.\n * if src is a string we're going to download an image\n * if src is an array of strings we're going to download cubemap images\n * @param {*} src The src from a TextureOptions\n * @returns {bool} true if src is async.\n * @private\n */\nfunction isAsyncSrc(src) {\n return typeof src === 'string' ||\n (Array.isArray(src) && typeof src[0] === 'string');\n}\n\n/**\n * Creates a bunch of textures based on the passed in options.\n *\n * Example:\n *\n * const textures = twgl.createTextures(gl, {\n * // a power of 2 image\n * hftIcon: { src: \"images/hft-icon-16.png\", mag: gl.NEAREST },\n * // a non-power of 2 image\n * clover: { src: \"images/clover.jpg\" },\n * // From a canvas\n * fromCanvas: { src: ctx.canvas },\n * // A cubemap from 6 images\n * yokohama: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: [\n * 'images/yokohama/posx.jpg',\n * 'images/yokohama/negx.jpg',\n * 'images/yokohama/posy.jpg',\n * 'images/yokohama/negy.jpg',\n * 'images/yokohama/posz.jpg',\n * 'images/yokohama/negz.jpg',\n * ],\n * },\n * // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1)\n * goldengate: {\n * target: gl.TEXTURE_CUBE_MAP,\n * src: 'images/goldengate.jpg',\n * },\n * // A 2x2 pixel texture from a JavaScript array\n * checker: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * src: [\n * 255,255,255,255,\n * 192,192,192,255,\n * 192,192,192,255,\n * 255,255,255,255,\n * ],\n * },\n * // a 1x2 pixel texture from a typed array.\n * stripe: {\n * mag: gl.NEAREST,\n * min: gl.LINEAR,\n * format: gl.LUMINANCE,\n * src: new Uint8Array([\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * 255,\n * 128,\n * ]),\n * width: 1,\n * },\n * });\n *\n * Now\n *\n * * `textures.hftIcon` will be a 2d texture\n * * `textures.clover` will be a 2d texture\n * * `textures.fromCanvas` will be a 2d texture\n * * `textures.yohohama` will be a cubemap texture\n * * `textures.goldengate` will be a cubemap texture\n * * `textures.checker` will be a 2d texture\n * * `textures.stripe` will be a 2d texture\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} options A object of TextureOptions one per texture.\n * @param {module:twgl.TexturesReadyCallback} [callback] A callback called when all textures have been downloaded.\n * @return {Object.} the created textures by name\n * @memberOf module:twgl/textures\n */\nfunction createTextures(gl, textureOptions, callback) {\n callback = callback || noop;\n let numDownloading = 0;\n const errors = [];\n const textures = {};\n const images = {};\n\n function callCallbackIfReady() {\n if (numDownloading === 0) {\n setTimeout(function() {\n callback(errors.length ? errors : undefined, textures, images);\n }, 0);\n }\n }\n\n Object.keys(textureOptions).forEach(function(name) {\n const options = textureOptions[name];\n let onLoadFn;\n if (isAsyncSrc(options.src)) {\n onLoadFn = function(err, tex, img) {\n images[name] = img;\n --numDownloading;\n if (err) {\n errors.push(err);\n }\n callCallbackIfReady();\n };\n ++numDownloading;\n }\n textures[name] = createTexture(gl, options, onLoadFn);\n });\n\n // queue the callback if there are no images to download.\n // We do this because if your code is structured to wait for\n // images to download but then you comment out all the async\n // images your code would break.\n callCallbackIfReady();\n\n return textures;\n}\n\nvar textures = /*#__PURE__*/Object.freeze({\n __proto__: null,\n setTextureDefaults_: setDefaults$1,\n createSampler: createSampler,\n createSamplers: createSamplers,\n setSamplerParameters: setSamplerParameters,\n createTexture: createTexture,\n setEmptyTexture: setEmptyTexture,\n setTextureFromArray: setTextureFromArray,\n loadTextureFromUrl: loadTextureFromUrl,\n setTextureFromElement: setTextureFromElement,\n setTextureFilteringForSize: setTextureFilteringForSize,\n setTextureParameters: setTextureParameters,\n setDefaultTextureColor: setDefaultTextureColor,\n createTextures: createTextures,\n resizeTexture: resizeTexture,\n canGenerateMipmap: canGenerateMipmap,\n canFilter: canFilter,\n getNumComponentsForFormat: getNumComponentsForFormat,\n getBytesPerElementForInternalFormat: getBytesPerElementForInternalFormat,\n getFormatAndTypeForInternalFormat: getFormatAndTypeForInternalFormat\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Low level shader program related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.programs` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/programs\n */\n\nconst error = error$1;\nconst warn = warn$1;\nfunction getElementById(id) {\n return (typeof document !== 'undefined' && document.getElementById)\n ? document.getElementById(id)\n : null;\n}\n\nconst TEXTURE0 = 0x84c0;\nconst DYNAMIC_DRAW = 0x88e8;\n\nconst ARRAY_BUFFER = 0x8892;\nconst ELEMENT_ARRAY_BUFFER$1 = 0x8893;\nconst UNIFORM_BUFFER = 0x8a11;\nconst TRANSFORM_FEEDBACK_BUFFER = 0x8c8e;\n\nconst TRANSFORM_FEEDBACK = 0x8e22;\n\nconst COMPILE_STATUS = 0x8b81;\nconst LINK_STATUS = 0x8b82;\nconst FRAGMENT_SHADER = 0x8b30;\nconst VERTEX_SHADER = 0x8b31;\nconst SEPARATE_ATTRIBS = 0x8c8d;\n\nconst ACTIVE_UNIFORMS = 0x8b86;\nconst ACTIVE_ATTRIBUTES = 0x8b89;\nconst TRANSFORM_FEEDBACK_VARYINGS = 0x8c83;\nconst ACTIVE_UNIFORM_BLOCKS = 0x8a36;\nconst UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44;\nconst UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46;\nconst UNIFORM_BLOCK_DATA_SIZE = 0x8a40;\nconst UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43;\n\nconst FLOAT = 0x1406;\nconst FLOAT_VEC2 = 0x8B50;\nconst FLOAT_VEC3 = 0x8B51;\nconst FLOAT_VEC4 = 0x8B52;\nconst INT = 0x1404;\nconst INT_VEC2 = 0x8B53;\nconst INT_VEC3 = 0x8B54;\nconst INT_VEC4 = 0x8B55;\nconst BOOL = 0x8B56;\nconst BOOL_VEC2 = 0x8B57;\nconst BOOL_VEC3 = 0x8B58;\nconst BOOL_VEC4 = 0x8B59;\nconst FLOAT_MAT2 = 0x8B5A;\nconst FLOAT_MAT3 = 0x8B5B;\nconst FLOAT_MAT4 = 0x8B5C;\nconst SAMPLER_2D = 0x8B5E;\nconst SAMPLER_CUBE = 0x8B60;\nconst SAMPLER_3D = 0x8B5F;\nconst SAMPLER_2D_SHADOW = 0x8B62;\nconst FLOAT_MAT2x3 = 0x8B65;\nconst FLOAT_MAT2x4 = 0x8B66;\nconst FLOAT_MAT3x2 = 0x8B67;\nconst FLOAT_MAT3x4 = 0x8B68;\nconst FLOAT_MAT4x2 = 0x8B69;\nconst FLOAT_MAT4x3 = 0x8B6A;\nconst SAMPLER_2D_ARRAY = 0x8DC1;\nconst SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;\nconst SAMPLER_CUBE_SHADOW = 0x8DC5;\nconst UNSIGNED_INT = 0x1405;\nconst UNSIGNED_INT_VEC2 = 0x8DC6;\nconst UNSIGNED_INT_VEC3 = 0x8DC7;\nconst UNSIGNED_INT_VEC4 = 0x8DC8;\nconst INT_SAMPLER_2D = 0x8DCA;\nconst INT_SAMPLER_3D = 0x8DCB;\nconst INT_SAMPLER_CUBE = 0x8DCC;\nconst INT_SAMPLER_2D_ARRAY = 0x8DCF;\nconst UNSIGNED_INT_SAMPLER_2D = 0x8DD2;\nconst UNSIGNED_INT_SAMPLER_3D = 0x8DD3;\nconst UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;\nconst UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;\n\nconst TEXTURE_2D$1 = 0x0DE1;\nconst TEXTURE_CUBE_MAP = 0x8513;\nconst TEXTURE_3D = 0x806F;\nconst TEXTURE_2D_ARRAY = 0x8C1A;\n\nconst typeMap = {};\n\n/**\n * Returns the corresponding bind point for a given sampler type\n * @private\n */\nfunction getBindPointForSamplerType(gl, type) {\n return typeMap[type].bindPoint;\n}\n\n// This kind of sucks! If you could compose functions as in `var fn = gl[name];`\n// this code could be a lot smaller but that is sadly really slow (T_T)\n\nfunction floatSetter(gl, location) {\n return function(v) {\n gl.uniform1f(location, v);\n };\n}\n\nfunction floatArraySetter(gl, location) {\n return function(v) {\n gl.uniform1fv(location, v);\n };\n}\n\nfunction floatVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2fv(location, v);\n };\n}\n\nfunction floatVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3fv(location, v);\n };\n}\n\nfunction floatVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4fv(location, v);\n };\n}\n\nfunction intSetter(gl, location) {\n return function(v) {\n gl.uniform1i(location, v);\n };\n}\n\nfunction intArraySetter(gl, location) {\n return function(v) {\n gl.uniform1iv(location, v);\n };\n}\n\nfunction intVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2iv(location, v);\n };\n}\n\nfunction intVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3iv(location, v);\n };\n}\n\nfunction intVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4iv(location, v);\n };\n}\n\nfunction uintSetter(gl, location) {\n return function(v) {\n gl.uniform1ui(location, v);\n };\n}\n\nfunction uintArraySetter(gl, location) {\n return function(v) {\n gl.uniform1uiv(location, v);\n };\n}\n\nfunction uintVec2Setter(gl, location) {\n return function(v) {\n gl.uniform2uiv(location, v);\n };\n}\n\nfunction uintVec3Setter(gl, location) {\n return function(v) {\n gl.uniform3uiv(location, v);\n };\n}\n\nfunction uintVec4Setter(gl, location) {\n return function(v) {\n gl.uniform4uiv(location, v);\n };\n}\n\nfunction floatMat2Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2fv(location, false, v);\n };\n}\n\nfunction floatMat3Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3fv(location, false, v);\n };\n}\n\nfunction floatMat4Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4fv(location, false, v);\n };\n}\n\nfunction floatMat23Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x3fv(location, false, v);\n };\n}\n\nfunction floatMat32Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x2fv(location, false, v);\n };\n}\n\nfunction floatMat24Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix2x4fv(location, false, v);\n };\n}\n\nfunction floatMat42Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x2fv(location, false, v);\n };\n}\n\nfunction floatMat34Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix3x4fv(location, false, v);\n };\n}\n\nfunction floatMat43Setter(gl, location) {\n return function(v) {\n gl.uniformMatrix4x3fv(location, false, v);\n };\n}\n\nfunction samplerSetter(gl, type, unit, location) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n return isWebGL2(gl) ? function(textureOrPair) {\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n gl.bindSampler(unit, sampler);\n } : function(texture) {\n gl.uniform1i(location, unit);\n gl.activeTexture(TEXTURE0 + unit);\n gl.bindTexture(bindPoint, texture);\n };\n}\n\nfunction samplerArraySetter(gl, type, unit, location, size) {\n const bindPoint = getBindPointForSamplerType(gl, type);\n const units = new Int32Array(size);\n for (let ii = 0; ii < size; ++ii) {\n units[ii] = unit + ii;\n }\n\n return isWebGL2(gl) ? function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(textureOrPair, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n let texture;\n let sampler;\n if (!textureOrPair || isTexture(gl, textureOrPair)) {\n texture = textureOrPair;\n sampler = null;\n } else {\n texture = textureOrPair.texture;\n sampler = textureOrPair.sampler;\n }\n gl.bindSampler(unit, sampler);\n gl.bindTexture(bindPoint, texture);\n });\n } : function(textures) {\n gl.uniform1iv(location, units);\n textures.forEach(function(texture, index) {\n gl.activeTexture(TEXTURE0 + units[index]);\n gl.bindTexture(bindPoint, texture);\n });\n };\n}\n\ntypeMap[FLOAT] = { Type: Float32Array, size: 4, setter: floatSetter, arraySetter: floatArraySetter, };\ntypeMap[FLOAT_VEC2] = { Type: Float32Array, size: 8, setter: floatVec2Setter, cols: 2, };\ntypeMap[FLOAT_VEC3] = { Type: Float32Array, size: 12, setter: floatVec3Setter, cols: 3, };\ntypeMap[FLOAT_VEC4] = { Type: Float32Array, size: 16, setter: floatVec4Setter, cols: 4, };\ntypeMap[INT] = { Type: Int32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[INT_VEC2] = { Type: Int32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[INT_VEC3] = { Type: Int32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[INT_VEC4] = { Type: Int32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[UNSIGNED_INT] = { Type: Uint32Array, size: 4, setter: uintSetter, arraySetter: uintArraySetter, };\ntypeMap[UNSIGNED_INT_VEC2] = { Type: Uint32Array, size: 8, setter: uintVec2Setter, cols: 2, };\ntypeMap[UNSIGNED_INT_VEC3] = { Type: Uint32Array, size: 12, setter: uintVec3Setter, cols: 3, };\ntypeMap[UNSIGNED_INT_VEC4] = { Type: Uint32Array, size: 16, setter: uintVec4Setter, cols: 4, };\ntypeMap[BOOL] = { Type: Uint32Array, size: 4, setter: intSetter, arraySetter: intArraySetter, };\ntypeMap[BOOL_VEC2] = { Type: Uint32Array, size: 8, setter: intVec2Setter, cols: 2, };\ntypeMap[BOOL_VEC3] = { Type: Uint32Array, size: 12, setter: intVec3Setter, cols: 3, };\ntypeMap[BOOL_VEC4] = { Type: Uint32Array, size: 16, setter: intVec4Setter, cols: 4, };\ntypeMap[FLOAT_MAT2] = { Type: Float32Array, size: 32, setter: floatMat2Setter, rows: 2, cols: 2, };\ntypeMap[FLOAT_MAT3] = { Type: Float32Array, size: 48, setter: floatMat3Setter, rows: 3, cols: 3, };\ntypeMap[FLOAT_MAT4] = { Type: Float32Array, size: 64, setter: floatMat4Setter, rows: 4, cols: 4, };\ntypeMap[FLOAT_MAT2x3] = { Type: Float32Array, size: 32, setter: floatMat23Setter, rows: 2, cols: 3, };\ntypeMap[FLOAT_MAT2x4] = { Type: Float32Array, size: 32, setter: floatMat24Setter, rows: 2, cols: 4, };\ntypeMap[FLOAT_MAT3x2] = { Type: Float32Array, size: 48, setter: floatMat32Setter, rows: 3, cols: 2, };\ntypeMap[FLOAT_MAT3x4] = { Type: Float32Array, size: 48, setter: floatMat34Setter, rows: 3, cols: 4, };\ntypeMap[FLOAT_MAT4x2] = { Type: Float32Array, size: 64, setter: floatMat42Setter, rows: 4, cols: 2, };\ntypeMap[FLOAT_MAT4x3] = { Type: Float32Array, size: 64, setter: floatMat43Setter, rows: 4, cols: 3, };\ntypeMap[SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[SAMPLER_2D_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_2D_ARRAY_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[SAMPLER_CUBE_SHADOW] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D$1, };\ntypeMap[UNSIGNED_INT_SAMPLER_3D] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_3D, };\ntypeMap[UNSIGNED_INT_SAMPLER_CUBE] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_CUBE_MAP, };\ntypeMap[UNSIGNED_INT_SAMPLER_2D_ARRAY] = { Type: null, size: 0, setter: samplerSetter, arraySetter: samplerArraySetter, bindPoint: TEXTURE_2D_ARRAY, };\n\nfunction floatAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n switch (b.value.length) {\n case 4:\n gl.vertexAttrib4fv(index, b.value);\n break;\n case 3:\n gl.vertexAttrib3fv(index, b.value);\n break;\n case 2:\n gl.vertexAttrib2fv(index, b.value);\n break;\n case 1:\n gl.vertexAttrib1fv(index, b.value);\n break;\n default:\n throw new Error('the length of a float constant value must be between 1 and 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribPointer(\n index, b.numComponents || b.size, b.type || FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction intAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4iv(index, b.value);\n } else {\n throw new Error('The length of an integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction uintAttribSetter(gl, index) {\n return function(b) {\n if (b.value) {\n gl.disableVertexAttribArray(index);\n if (b.value.length === 4) {\n gl.vertexAttrib4uiv(index, b.value);\n } else {\n throw new Error('The length of an unsigned integer constant value must be 4!');\n }\n } else {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n gl.enableVertexAttribArray(index);\n gl.vertexAttribIPointer(\n index, b.numComponents || b.size, b.type || UNSIGNED_INT, b.stride || 0, b.offset || 0);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index, b.divisor || 0);\n }\n }\n };\n}\n\nfunction matAttribSetter(gl, index, typeInfo) {\n const defaultSize = typeInfo.size;\n const count = typeInfo.count;\n\n return function(b) {\n gl.bindBuffer(ARRAY_BUFFER, b.buffer);\n const numComponents = b.size || b.numComponents || defaultSize;\n const size = numComponents / count;\n const type = b.type || FLOAT;\n const typeInfo = typeMap[type];\n const stride = typeInfo.size * numComponents;\n const normalize = b.normalize || false;\n const offset = b.offset || 0;\n const rowOffset = stride / count;\n for (let i = 0; i < count; ++i) {\n gl.enableVertexAttribArray(index + i);\n gl.vertexAttribPointer(\n index + i, size, type, normalize, stride, offset + rowOffset * i);\n if (gl.vertexAttribDivisor) {\n gl.vertexAttribDivisor(index + i, b.divisor || 0);\n }\n }\n };\n}\n\n\n\nconst attrTypeMap = {};\nattrTypeMap[FLOAT] = { size: 4, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC2] = { size: 8, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC3] = { size: 12, setter: floatAttribSetter, };\nattrTypeMap[FLOAT_VEC4] = { size: 16, setter: floatAttribSetter, };\nattrTypeMap[INT] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[INT_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[INT_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[INT_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[UNSIGNED_INT] = { size: 4, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC2] = { size: 8, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC3] = { size: 12, setter: uintAttribSetter, };\nattrTypeMap[UNSIGNED_INT_VEC4] = { size: 16, setter: uintAttribSetter, };\nattrTypeMap[BOOL] = { size: 4, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC2] = { size: 8, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC3] = { size: 12, setter: intAttribSetter, };\nattrTypeMap[BOOL_VEC4] = { size: 16, setter: intAttribSetter, };\nattrTypeMap[FLOAT_MAT2] = { size: 4, setter: matAttribSetter, count: 2, };\nattrTypeMap[FLOAT_MAT3] = { size: 9, setter: matAttribSetter, count: 3, };\nattrTypeMap[FLOAT_MAT4] = { size: 16, setter: matAttribSetter, count: 4, };\n\nconst errorRE = /ERROR:\\s*\\d+:(\\d+)/gi;\nfunction addLineNumbersWithError(src, log = '', lineOffset = 0) {\n // Note: Error message formats are not defined by any spec so this may or may not work.\n const matches = [...log.matchAll(errorRE)];\n const lineNoToErrorMap = new Map(matches.map((m, ndx) => {\n const lineNo = parseInt(m[1]);\n const next = matches[ndx + 1];\n const end = next ? next.index : log.length;\n const msg = log.substring(m.index, end);\n return [lineNo - 1, msg];\n }));\n return src.split('\\n').map((line, lineNo) => {\n const err = lineNoToErrorMap.get(lineNo);\n return `${lineNo + 1 + lineOffset}: ${line}${err ? `\\n\\n^^^ ${err}` : ''}`;\n }).join('\\n');\n}\n\n/**\n * Error Callback\n * @callback ErrorCallback\n * @param {string} msg error message.\n * @param {number} [lineOffset] amount to add to line number\n * @memberOf module:twgl\n */\n\n/**\n * Program Callback\n * @callback ProgramCallback\n * @param {string} [err] error message, falsy if no error\n * @param {WebGLProgram|module:twgl.ProgramInfo} [result] the program or programInfo\n */\n\nconst spaceRE = /^[ \\t]*\\n/;\n\n/**\n * Remove the first end of line because WebGL 2.0 requires\n * #version 300 es\n * as the first line. No whitespace allowed before that line\n * so\n *\n * \n *\n * Has one line before it which is invalid according to GLSL ES 3.00\n *\n * @param {string} shaderSource The source of the shader\n * @returns {{shaderSource: string, lineOffset: number}}\n * @private\n */\nfunction prepShaderSource(shaderSource) {\n let lineOffset = 0;\n if (spaceRE.test(shaderSource)) {\n lineOffset = 1;\n shaderSource = shaderSource.replace(spaceRE, '');\n }\n return {lineOffset, shaderSource};\n}\n\n/**\n * @param {module:twgl.ProgramOptions} progOptions\n * @param {string} msg\n * @return null\n * @private\n */\nfunction reportError(progOptions, msg) {\n progOptions.errorCallback(msg);\n if (progOptions.callback) {\n setTimeout(() => {\n progOptions.callback(`${msg}\\n${progOptions.errors.join('\\n')}`);\n });\n }\n return null;\n}\n\n/**\n * Check Shader status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {number} shaderType The shader type\n * @param {WebGLShader} shader The shader\n * @param {ErrorCallback} [errFn] function to receive error message.\n * @return {string} errors or empty string\n * @private\n */\nfunction checkShaderStatus(gl, shaderType, shader, errFn) {\n errFn = errFn || error;\n // Check the compile status\n const compiled = gl.getShaderParameter(shader, COMPILE_STATUS);\n if (!compiled) {\n // Something went wrong during compilation; get the error\n const lastError = gl.getShaderInfoLog(shader);\n const {lineOffset, shaderSource} = prepShaderSource(gl.getShaderSource(shader));\n const error = `${addLineNumbersWithError(shaderSource, lastError, lineOffset)}\\nError compiling ${glEnumToString(gl, shaderType)}: ${lastError}`;\n errFn(error);\n return error;\n }\n return '';\n}\n\n/**\n * @typedef {Object} FullProgramSpec\n * @property {string[]} shaders the shader source or element ids.\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {string[]|module:twgl.FullProgramSpec} ProgramSpec\n * @memberOf module:twgl\n */\n\n/**\n * @typedef {Object} ProgramOptions\n * @property {function(string)} [errorCallback] callback for errors\n * @property {Object.|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.\n * @property {(module:twgl.BufferInfo|Object.|string[])} [transformFeedbackVaryings] If passed\n * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise\n * you can pass an array of names.\n * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.\n * @property {ProgramCallback} [callback] callback for async program compilation.\n * @memberOf module:twgl\n */\n\n/**\n * Gets the program options based on all these optional arguments\n * @param {module:twgl.ProgramOptions|string[]} [opt_attribs] Options for the program or an array of attribs names. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramOptions} an instance of ProgramOptions based on the arguments passed in\n * @private\n */\nfunction getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {\n let transformFeedbackVaryings;\n let transformFeedbackMode;\n let callback;\n if (typeof opt_locations === 'function') {\n opt_errorCallback = opt_locations;\n opt_locations = undefined;\n }\n if (typeof opt_attribs === 'function') {\n opt_errorCallback = opt_attribs;\n opt_attribs = undefined;\n } else if (opt_attribs && !Array.isArray(opt_attribs)) {\n const opt = opt_attribs;\n opt_errorCallback = opt.errorCallback;\n opt_attribs = opt.attribLocations;\n transformFeedbackVaryings = opt.transformFeedbackVaryings;\n transformFeedbackMode = opt.transformFeedbackMode;\n callback = opt.callback;\n }\n\n const errorCallback = opt_errorCallback || error;\n const errors = [];\n const options = {\n errorCallback(msg, ...args) {\n errors.push(msg);\n errorCallback(msg, ...args);\n },\n transformFeedbackVaryings,\n transformFeedbackMode,\n callback,\n errors,\n };\n\n {\n let attribLocations = {};\n if (Array.isArray(opt_attribs)) {\n opt_attribs.forEach(function(attrib, ndx) {\n attribLocations[attrib] = opt_locations ? opt_locations[ndx] : ndx;\n });\n } else {\n attribLocations = opt_attribs || {};\n }\n options.attribLocations = attribLocations;\n }\n\n return options;\n}\n\nconst defaultShaderType = [\n \"VERTEX_SHADER\",\n \"FRAGMENT_SHADER\",\n];\n\nfunction getShaderTypeFromScriptType(gl, scriptType) {\n if (scriptType.indexOf(\"frag\") >= 0) {\n return FRAGMENT_SHADER;\n } else if (scriptType.indexOf(\"vert\") >= 0) {\n return VERTEX_SHADER;\n }\n return undefined;\n}\n\nfunction deleteProgramAndShaders(gl, program, notThese) {\n const shaders = gl.getAttachedShaders(program);\n for (const shader of shaders) {\n if (notThese.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n gl.deleteProgram(program);\n}\n\nconst wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));\n\nfunction createProgramNoCheck(gl, shaders, programOptions) {\n const program = gl.createProgram();\n const {\n attribLocations,\n transformFeedbackVaryings,\n transformFeedbackMode,\n } = getProgramOptions(programOptions);\n\n for (let ndx = 0; ndx < shaders.length; ++ndx) {\n let shader = shaders[ndx];\n if (typeof shader === 'string') {\n const elem = getElementById(shader);\n const src = elem ? elem.text : shader;\n let type = gl[defaultShaderType[ndx]];\n if (elem && elem.type) {\n type = getShaderTypeFromScriptType(gl, elem.type) || type;\n }\n shader = gl.createShader(type);\n gl.shaderSource(shader, prepShaderSource(src).shaderSource);\n gl.compileShader(shader);\n gl.attachShader(program, shader);\n }\n }\n\n Object.entries(attribLocations).forEach(([attrib, loc]) => gl.bindAttribLocation(program, loc, attrib));\n\n {\n let varyings = transformFeedbackVaryings;\n if (varyings) {\n if (varyings.attribs) {\n varyings = varyings.attribs;\n }\n if (!Array.isArray(varyings)) {\n varyings = Object.keys(varyings);\n }\n gl.transformFeedbackVaryings(program, varyings, transformFeedbackMode || SEPARATE_ATTRIBS);\n }\n }\n\n gl.linkProgram(program);\n return program;\n}\n\n/**\n * Creates a program, attaches (and/or compiles) shaders, binds attrib locations, links the\n * program.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgram(gl, [vs, fs], options);\n * twgl.createProgram(gl, [vs, fs], opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgram(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error of a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgram(\n gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {\n // This code is really convoluted, because it may or may not be async\n // Maybe it would be better to have a separate function\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaderSet = new Set(shaders);\n const program = createProgramNoCheck(gl, shaders, progOptions);\n\n function hasErrors(gl, program) {\n const errors = getProgramErrors(gl, program, progOptions.errorCallback);\n if (errors) {\n deleteProgramAndShaders(gl, program, shaderSet);\n }\n return errors;\n }\n\n if (progOptions.callback) {\n waitForProgramLinkCompletionAsync(gl, program).then(() => {\n const errors = hasErrors(gl, program);\n progOptions.callback(errors, errors ? undefined : program);\n });\n return undefined;\n }\n\n return hasErrors(gl, program) ? undefined : program;\n}\n\n/**\n * This only works because the functions it wraps the first 2 arguments\n * are gl and any, followed by things that become programOptions\n * @private\n */\nfunction wrapCallbackFnToAsyncFn(fn) {\n return function(gl, arg1, ...args) {\n return new Promise((resolve, reject) => {\n const programOptions = getProgramOptions(...args);\n programOptions.callback = (err, program) => {\n if (err) {\n reject(err);\n } else {\n resolve(program);\n }\n };\n fn(gl, arg1, programOptions);\n });\n };\n}\n\n/**\n * Same as createProgram but returns a promise\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramAsync(gl, [vs, fs], options);\n * twgl.createProgramAsync(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created program\n * @memberOf module:twgl/programs\n */\nconst createProgramAsync = wrapCallbackFnToAsyncFn(createProgram);\n\n/**\n * Same as createProgramInfo but returns a promise\n * @function\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {Promise} The created ProgramInfo\n * @memberOf module:twgl/programs\n */\nconst createProgramInfoAsync = wrapCallbackFnToAsyncFn(createProgramInfo);\n\nasync function waitForProgramLinkCompletionAsync(gl, program) {\n const ext = gl.getExtension('KHR_parallel_shader_compile');\n const checkFn = ext\n ? (gl, program) => gl.getProgramParameter(program, ext.COMPLETION_STATUS_KHR)\n : () => true;\n\n let waitTime = 0;\n do {\n await wait(waitTime); // must wait at least once\n waitTime = 1000 / 60;\n } while (!checkFn(gl, program));\n}\n\nasync function waitForAllProgramsLinkCompletionAsync(gl, programs) {\n for (const program of Object.values(programs)) {\n await waitForProgramLinkCompletionAsync(gl, program);\n }\n}\n\n/**\n * Check a program's link status\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program Program to check\n * @param {ErrorCallback} [errFn] func for errors\n * @return {string?} errors if program is failed, else undefined\n * @private\n */\nfunction getProgramErrors(gl, program, errFn) {\n errFn = errFn || error;\n // Check the link status\n const linked = gl.getProgramParameter(program, LINK_STATUS);\n if (!linked) {\n // something went wrong with the link\n const lastError = gl.getProgramInfoLog(program);\n errFn(`Error in program linking: ${lastError}`);\n // print any errors from these shaders\n const shaders = gl.getAttachedShaders(program);\n const errors = shaders.map(shader => checkShaderStatus(gl, gl.getShaderParameter(shader, gl.SHADER_TYPE), shader, errFn));\n return `${lastError}\\n${errors.filter(_ => _).join('\\n')}`;\n }\n return undefined;\n}\n\n/**\n * Creates a program from 2 script tags.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_options);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromScripts(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderScriptIds Array of ids of the script\n * tags for the shaders. The first is assumed to be the\n * vertex shader, the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromScripts(\n gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const shaders = [];\n for (const scriptId of shaderScriptIds) {\n const shaderScript = getElementById(scriptId);\n if (!shaderScript) {\n return reportError(progOptions, `unknown script element: ${scriptId}`);\n }\n shaders.push(shaderScript.text);\n }\n return createProgram(gl, shaders, progOptions);\n}\n\n/**\n * Creates a program from 2 sources.\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramFromSource(gl, [vs, fs], opt_options);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramFromSource(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {WebGLProgram?} the created program or null if error or a callback was provided.\n * @memberOf module:twgl/programs\n */\nfunction createProgramFromSources(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n return createProgram(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);\n}\n\n/**\n * Returns true if attribute/uniform is a reserved/built in\n *\n * It makes no sense to me why GL returns these because it's\n * illegal to call `gl.getUniformLocation` and `gl.getAttribLocation`\n * with names that start with `gl_` (and `webgl_` in WebGL)\n *\n * I can only assume they are there because they might count\n * when computing the number of uniforms/attributes used when you want to\n * know if you are near the limit. That doesn't really make sense\n * to me but the fact that these get returned are in the spec.\n *\n * @param {WebGLActiveInfo} info As returned from `gl.getActiveUniform` or\n * `gl.getActiveAttrib`.\n * @return {bool} true if it's reserved\n * @private\n */\nfunction isBuiltIn(info) {\n const name = info.name;\n return name.startsWith(\"gl_\") || name.startsWith(\"webgl_\");\n}\n\nconst tokenRE = /(\\.|\\[|]|\\w+)/g;\nconst isDigit = s => s >= '0' && s <= '9';\nfunction addSetterToUniformTree(fullPath, setter, node, uniformSetters) {\n const tokens = fullPath.split(tokenRE).filter(s => s !== '');\n let tokenNdx = 0;\n let path = '';\n\n for (;;) {\n const token = tokens[tokenNdx++]; // has to be name or number\n path += token;\n const isArrayIndex = isDigit(token[0]);\n const accessor = isArrayIndex\n ? parseInt(token)\n : token;\n if (isArrayIndex) {\n path += tokens[tokenNdx++]; // skip ']'\n }\n const isLastToken = tokenNdx === tokens.length;\n if (isLastToken) {\n node[accessor] = setter;\n break;\n } else {\n const token = tokens[tokenNdx++]; // has to be . or [\n const isArray = token === '[';\n const child = node[accessor] || (isArray ? [] : {});\n node[accessor] = child;\n node = child;\n uniformSetters[path] = uniformSetters[path] || function(node) {\n return function(value) {\n setUniformTree(node, value);\n };\n }(child);\n path += token;\n }\n }\n}\n\n/**\n * Creates setter functions for all uniforms of a shader\n * program.\n *\n * @see {@link module:twgl.setUniforms}\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @returns {Object.} an object with a setter by name for each uniform\n * @memberOf module:twgl/programs\n */\nfunction createUniformSetters(gl, program) {\n let textureUnit = 0;\n\n /**\n * Creates a setter for a uniform of the given program with it's\n * location embedded in the setter.\n * @param {WebGLProgram} program\n * @param {WebGLUniformInfo} uniformInfo\n * @returns {function} the created setter.\n */\n function createUniformSetter(program, uniformInfo, location) {\n const isArray = uniformInfo.name.endsWith(\"[0]\");\n const type = uniformInfo.type;\n const typeInfo = typeMap[type];\n if (!typeInfo) {\n throw new Error(`unknown type: 0x${type.toString(16)}`); // we should never get here.\n }\n let setter;\n if (typeInfo.bindPoint) {\n // it's a sampler\n const unit = textureUnit;\n textureUnit += uniformInfo.size;\n if (isArray) {\n setter = typeInfo.arraySetter(gl, type, unit, location, uniformInfo.size);\n } else {\n setter = typeInfo.setter(gl, type, unit, location, uniformInfo.size);\n }\n } else {\n if (typeInfo.arraySetter && isArray) {\n setter = typeInfo.arraySetter(gl, location);\n } else {\n setter = typeInfo.setter(gl, location);\n }\n }\n setter.location = location;\n return setter;\n }\n\n const uniformSetters = {};\n const uniformTree = {};\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n const uniformInfo = gl.getActiveUniform(program, ii);\n if (isBuiltIn(uniformInfo)) {\n continue;\n }\n let name = uniformInfo.name;\n // remove the array suffix.\n if (name.endsWith(\"[0]\")) {\n name = name.substr(0, name.length - 3);\n }\n const location = gl.getUniformLocation(program, uniformInfo.name);\n // the uniform will have no location if it's in a uniform block\n if (location) {\n const setter = createUniformSetter(program, uniformInfo, location);\n uniformSetters[name] = setter;\n addSetterToUniformTree(name, setter, uniformTree, uniformSetters);\n }\n }\n\n return uniformSetters;\n}\n\n/**\n * @typedef {Object} TransformFeedbackInfo\n * @property {number} index index of transform feedback\n * @property {number} type GL type\n * @property {number} size 1 - 4\n * @memberOf module:twgl\n */\n\n/**\n * Create TransformFeedbackInfo for passing to bindTransformFeedbackInfo.\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {Object}\n * @memberOf module:twgl\n */\nfunction createTransformFeedbackInfo(gl, program) {\n const info = {};\n const numVaryings = gl.getProgramParameter(program, TRANSFORM_FEEDBACK_VARYINGS);\n for (let ii = 0; ii < numVaryings; ++ii) {\n const varying = gl.getTransformFeedbackVarying(program, ii);\n info[varying.name] = {\n index: ii,\n type: varying.type,\n size: varying.size,\n };\n }\n return info;\n}\n\n/**\n * Binds buffers for transform feedback.\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {(module:twgl.ProgramInfo|Object)} transformFeedbackInfo A ProgramInfo or TransformFeedbackInfo.\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @memberOf module:twgl\n */\nfunction bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfo) {\n if (transformFeedbackInfo.transformFeedbackInfo) {\n transformFeedbackInfo = transformFeedbackInfo.transformFeedbackInfo;\n }\n if (bufferInfo.attribs) {\n bufferInfo = bufferInfo.attribs;\n }\n for (const name in bufferInfo) {\n const varying = transformFeedbackInfo[name];\n if (varying) {\n const buf = bufferInfo[name];\n if (buf.offset) {\n gl.bindBufferRange(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer, buf.offset, buf.size);\n } else {\n gl.bindBufferBase(TRANSFORM_FEEDBACK_BUFFER, varying.index, buf.buffer);\n }\n }\n }\n}\n\n/**\n * Creates a transform feedback and sets the buffers\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @param {(module:twgl.BufferInfo|Object)} [bufferInfo] A BufferInfo or set of AttribInfos.\n * @return {WebGLTransformFeedback} the created transform feedback\n * @memberOf module:twgl\n */\nfunction createTransformFeedback(gl, programInfo, bufferInfo) {\n const tf = gl.createTransformFeedback();\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, tf);\n gl.useProgram(programInfo.program);\n bindTransformFeedbackInfo(gl, programInfo, bufferInfo);\n gl.bindTransformFeedback(TRANSFORM_FEEDBACK, null);\n return tf;\n}\n\n/**\n * @typedef {Object} UniformData\n * @property {string} name The name of the uniform\n * @property {number} type The WebGL type enum for this uniform\n * @property {number} size The number of elements for this uniform\n * @property {number} blockNdx The block index this uniform appears in\n * @property {number} offset The byte offset in the block for this uniform's value\n * @memberOf module:twgl\n */\n\n/**\n * The specification for one UniformBlockObject\n *\n * @typedef {Object} BlockSpec\n * @property {number} index The index of the block.\n * @property {number} size The size in bytes needed for the block\n * @property {number[]} uniformIndices The indices of the uniforms used by the block. These indices\n * correspond to entries in a UniformData array in the {@link module:twgl.UniformBlockSpec}.\n * @property {bool} usedByVertexShader Self explanatory\n * @property {bool} usedByFragmentShader Self explanatory\n * @property {bool} used Self explanatory\n * @memberOf module:twgl\n */\n\n/**\n * A `UniformBlockSpec` represents the data needed to create and bind\n * UniformBlockObjects for a given program\n *\n * @typedef {Object} UniformBlockSpec\n * @property {Object.} blockSpecs The BlockSpec for each block by block name\n * @property {UniformData[]} uniformData An array of data for each uniform by uniform index.\n * @memberOf module:twgl\n */\n\n/**\n * Creates a UniformBlockSpec for the given program.\n *\n * A UniformBlockSpec represents the data needed to create and bind\n * UniformBlockObjects\n *\n * @param {WebGL2RenderingContext} gl A WebGL2 Rendering Context\n * @param {WebGLProgram} program A WebGLProgram for a successfully linked program\n * @return {module:twgl.UniformBlockSpec} The created UniformBlockSpec\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockSpecFromProgram(gl, program) {\n const numUniforms = gl.getProgramParameter(program, ACTIVE_UNIFORMS);\n const uniformData = [];\n const uniformIndices = [];\n\n for (let ii = 0; ii < numUniforms; ++ii) {\n uniformIndices.push(ii);\n uniformData.push({});\n const uniformInfo = gl.getActiveUniform(program, ii);\n uniformData[ii].name = uniformInfo.name;\n }\n\n [\n [ \"UNIFORM_TYPE\", \"type\" ],\n [ \"UNIFORM_SIZE\", \"size\" ], // num elements\n [ \"UNIFORM_BLOCK_INDEX\", \"blockNdx\" ],\n [ \"UNIFORM_OFFSET\", \"offset\", ],\n ].forEach(function(pair) {\n const pname = pair[0];\n const key = pair[1];\n gl.getActiveUniforms(program, uniformIndices, gl[pname]).forEach(function(value, ndx) {\n uniformData[ndx][key] = value;\n });\n });\n\n const blockSpecs = {};\n\n const numUniformBlocks = gl.getProgramParameter(program, ACTIVE_UNIFORM_BLOCKS);\n for (let ii = 0; ii < numUniformBlocks; ++ii) {\n const name = gl.getActiveUniformBlockName(program, ii);\n const blockSpec = {\n index: gl.getUniformBlockIndex(program, name),\n usedByVertexShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n usedByFragmentShader: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n size: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_DATA_SIZE),\n uniformIndices: gl.getActiveUniformBlockParameter(program, ii, UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),\n };\n blockSpec.used = blockSpec.usedByVertexShader || blockSpec.usedByFragmentShader;\n blockSpecs[name] = blockSpec;\n }\n\n return {\n blockSpecs: blockSpecs,\n uniformData: uniformData,\n };\n}\n\nconst arraySuffixRE = /\\[\\d+\\]\\.$/; // better way to check?\n\nconst pad = (v, padding) => ((v + (padding - 1)) / padding | 0) * padding;\n\nfunction createUniformBlockUniformSetter(view, isArray, rows, cols) {\n if (isArray || rows) {\n cols = cols || 1;\n const numElements = view.length;\n const totalRows = numElements / 4;\n return function(value) {\n let dst = 0;\n let src = 0;\n for (let row = 0; row < totalRows; ++row) {\n for (let col = 0; col < cols; ++col) {\n view[dst++] = value[src++];\n }\n dst += 4 - cols;\n }\n };\n } else {\n return function(value) {\n if (value.length) {\n view.set(value);\n } else {\n view[0] = value;\n }\n };\n }\n}\n\n/**\n * Represents a UniformBlockObject including an ArrayBuffer with all the uniform values\n * and a corresponding WebGLBuffer to hold those values on the GPU\n *\n * @typedef {Object} UniformBlockInfo\n * @property {string} name The name of the block\n * @property {ArrayBuffer} array The array buffer that contains the uniform values\n * @property {Float32Array} asFloat A float view on the array buffer. This is useful\n * inspecting the contents of the buffer in the debugger.\n * @property {WebGLBuffer} buffer A WebGL buffer that will hold a copy of the uniform values for rendering.\n * @property {number} [offset] offset into buffer\n * @property {Object} uniforms A uniform name to ArrayBufferView map.\n * each Uniform has a correctly typed `ArrayBufferView` into array at the correct offset\n * and length of that uniform. So for example a float uniform would have a 1 float `Float32Array`\n * view. A single mat4 would have a 16 element `Float32Array` view. An ivec2 would have an\n * `Int32Array` view, etc.\n * @property {Object} setters A setter for this uniform.\n * The reason to use setters is elements of arrays are padded to vec4 sizes which\n * means if you want to set an array of 4 floats you'd need to set 16 values\n * (or set elements 0, 4, 8, 12). In other words\n * `someBlockInfo.uniforms.some4FloatArrayUniform.set([0, , , , 1, , , , 2, , , , 3])`\n * where as the setter handles just passing in [0, 1, 2, 3] either directly as in\n * `someBlockInfo.setter.some4FloatArrayUniform.set([0, 1, 2, 3])` (not recommended)\n * or via {@link module:twgl.setBlockUniforms}\n * @memberOf module:twgl\n */\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {WebGLProgram} program A WebGLProgram\n * @param {module:twgl.UniformBlockSpec} uniformBlockSpec. A UniformBlockSpec as returned\n * from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfoFromProgram(gl, program, uniformBlockSpec, blockName) {\n const blockSpecs = uniformBlockSpec.blockSpecs;\n const uniformData = uniformBlockSpec.uniformData;\n const blockSpec = blockSpecs[blockName];\n if (!blockSpec) {\n warn(\"no uniform block object named:\", blockName);\n return {\n name: blockName,\n uniforms: {},\n };\n }\n const array = new ArrayBuffer(blockSpec.size);\n const buffer = gl.createBuffer();\n const uniformBufferIndex = blockSpec.index;\n gl.bindBuffer(UNIFORM_BUFFER, buffer);\n gl.uniformBlockBinding(program, blockSpec.index, uniformBufferIndex);\n\n let prefix = blockName + \".\";\n if (arraySuffixRE.test(prefix)) {\n prefix = prefix.replace(arraySuffixRE, \".\");\n }\n const uniforms = {};\n const setters = {};\n const setterTree = {};\n blockSpec.uniformIndices.forEach(function(uniformNdx) {\n const data = uniformData[uniformNdx];\n let name = data.name;\n if (name.startsWith(prefix)) {\n name = name.substr(prefix.length);\n }\n const isArray = name.endsWith('[0]');\n if (isArray) {\n name = name.substr(0, name.length - 3);\n }\n const typeInfo = typeMap[data.type];\n const Type = typeInfo.Type;\n const byteLength = isArray\n ? pad(typeInfo.size, 16) * data.size\n : typeInfo.size * data.size;\n const uniformView = new Type(array, data.offset, byteLength / Type.BYTES_PER_ELEMENT);\n uniforms[name] = uniformView;\n // Note: I'm not sure what to do here. The original\n // idea was to create TypedArray views into each part\n // of the block. This is useful, for example if you have\n // a block with { mat4: model; mat4 view; mat4 projection; }\n // you'll get a Float32Array for each one suitable for\n // passing to most JS math libraries including twgl's and glMatrix.js.\n //\n // But, if you have a an array of structures, especially if that\n // array is large, you get a whole bunch of TypedArray views.\n // Every one of them has overhead and switching between them all\n // is probably a cache miss. In that case it would really be better\n // to just have one view (asFloat) and have all the setters\n // just reference the correct portion. But, then you can't easily\n // treat a matrix, or a vec4, as a standalone thing like you can\n // with all the views.\n //\n // Another problem with the views is they are not shared. With\n // uniforms you have one set of setters. With UniformBlockInfo\n // you have a set of setters *pre block instance*. That's because\n // TypedArray views can't be mapped to different buffers.\n //\n // My gut right now is if you really want the speed and compactness\n // then you should probably roll your own solution. TWGL's goal\n // here is ease of use as AFAICT there is no simple generic efficient\n // solution.\n const setter = createUniformBlockUniformSetter(uniformView, isArray, typeInfo.rows, typeInfo.cols);\n setters[name] = setter;\n addSetterToUniformTree(name, setter, setterTree, setters);\n });\n return {\n name: blockName,\n array,\n asFloat: new Float32Array(array), // for debugging\n buffer,\n uniforms,\n setters,\n };\n}\n\n/**\n * Creates a `UniformBlockInfo` for the specified block\n *\n * Note: **If the blockName matches no existing blocks a warning is printed to the console and a dummy\n * `UniformBlockInfo` is returned**. This is because when debugging GLSL\n * it is common to comment out large portions of a shader or for example set\n * the final output to a constant. When that happens blocks get optimized out.\n * If this function did not create dummy blocks your code would crash when debugging.\n *\n * @param {WebGL2RenderingContext} gl A WebGL2RenderingContext\n * @param {module:twgl.ProgramInfo} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo}\n * @param {string} blockName The name of the block.\n * @return {module:twgl.UniformBlockInfo} The created UniformBlockInfo\n * @memberOf module:twgl/programs\n */\nfunction createUniformBlockInfo(gl, programInfo, blockName) {\n return createUniformBlockInfoFromProgram(gl, programInfo.program, programInfo.uniformBlockSpec, blockName);\n}\n\n/**\n * Binds a uniform block to the matching uniform block point.\n * Matches by blocks by name so blocks must have the same name not just the same\n * structure.\n *\n * If you have changed any values and you upload the values into the corresponding WebGLBuffer\n * call {@link module:twgl.setUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @return {bool} true if buffer was bound. If the programInfo has no block with the same block name\n * no buffer is bound.\n * @memberOf module:twgl/programs\n */\nfunction bindUniformBlock(gl, programInfo, uniformBlockInfo) {\n const uniformBlockSpec = programInfo.uniformBlockSpec || programInfo;\n const blockSpec = uniformBlockSpec.blockSpecs[uniformBlockInfo.name];\n if (blockSpec) {\n const bufferBindIndex = blockSpec.index;\n gl.bindBufferRange(UNIFORM_BUFFER, bufferBindIndex, uniformBlockInfo.buffer, uniformBlockInfo.offset || 0, uniformBlockInfo.array.byteLength);\n return true;\n }\n return false;\n}\n\n/**\n * Uploads the current uniform values to the corresponding WebGLBuffer\n * and binds that buffer to the program's corresponding bind point for the uniform block object.\n *\n * If you haven't changed any values and you only need to bind the uniform block object\n * call {@link module:twgl.bindUniformBlock} instead.\n *\n * @param {WebGL2RenderingContext} gl A WebGL 2 rendering context.\n * @param {(module:twgl.ProgramInfo|module:twgl.UniformBlockSpec)} programInfo a `ProgramInfo`\n * as returned from {@link module:twgl.createProgramInfo} or or `UniformBlockSpec` as\n * returned from {@link module:twgl.createUniformBlockSpecFromProgram}.\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo a `UniformBlockInfo` as returned from\n * {@link module:twgl.createUniformBlockInfo}.\n * @memberOf module:twgl/programs\n */\nfunction setUniformBlock(gl, programInfo, uniformBlockInfo) {\n if (bindUniformBlock(gl, programInfo, uniformBlockInfo)) {\n gl.bufferData(UNIFORM_BUFFER, uniformBlockInfo.array, DYNAMIC_DRAW);\n }\n}\n\n/**\n * Sets values of a uniform block object\n *\n * @param {module:twgl.UniformBlockInfo} uniformBlockInfo A UniformBlockInfo as returned by {@link module:twgl.createUniformBlockInfo}.\n * @param {Object.} values A uniform name to value map where the value is correct for the given\n * type of uniform. So for example given a block like\n *\n * uniform SomeBlock {\n * float someFloat;\n * vec2 someVec2;\n * vec3 someVec3Array[2];\n * int someInt;\n * }\n *\n * You can set the values of the uniform block with\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * someFloat: 12.3,\n * someVec2: [1, 2],\n * someVec3Array: [1, 2, 3, 4, 5, 6],\n * someInt: 5,\n * }\n *\n * Arrays can be JavaScript arrays or typed arrays\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Lights {\n * Light lights[2];\n * };\n *\n * // in JavaScript\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices.\n *\n * twgl.setBlockUniforms(someBlockInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * **IMPORTANT!**, packing in a UniformBlock is unintuitive.\n * For example the actual layout of `someVec3Array` above in memory\n * is `1, 2, 3, unused, 4, 5, 6, unused`. twgl takes in 6 values\n * as shown about and copies them, skipping the padding. This might\n * be confusing if you're already familiar with Uniform blocks.\n *\n * If you want to deal with the padding yourself you can access the array\n * buffer views directly. eg:\n *\n * someBlockInfo.someVec3Array.set([1, 2, 3, 0, 4, 5, 6, 0]);\n *\n * Any name that doesn't match will be ignored\n * @memberOf module:twgl/programs\n */\nfunction setBlockUniforms(uniformBlockInfo, values) {\n const setters = uniformBlockInfo.setters;\n for (const name in values) {\n const setter = setters[name];\n if (setter) {\n const value = values[name];\n setter(value);\n }\n }\n}\n\nfunction setUniformTree(tree, values) {\n for (const name in values) {\n const prop = tree[name];\n if (typeof prop === 'function') {\n prop(values[name]);\n } else {\n setUniformTree(tree[name], values[name]);\n }\n }\n}\n\n/**\n * Set uniforms and binds related textures.\n *\n * example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\"]);\n *\n * const tex1 = gl.createTexture();\n * const tex2 = gl.createTexture();\n *\n * ... assume we setup the textures with data ...\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the textures AND set the\n * uniforms.\n *\n * twgl.setUniforms(programInfo, uniforms);\n *\n * For the example above it is equivalent to\n *\n * let texUnit = 0;\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex1);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.activeTexture(gl.TEXTURE0 + texUnit);\n * gl.bindTexture(gl.TEXTURE_2D, tex2);\n * gl.uniform1i(u_someSamplerLocation, texUnit++);\n * gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);\n * gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);\n * gl.uniformMatrix4fv(u_someMatrix, false, [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ]);\n *\n * Note it is perfectly reasonable to call `setUniforms` multiple times. For example\n *\n * const uniforms = {\n * u_someSampler: tex1,\n * u_someOtherSampler: tex2,\n * };\n *\n * const moreUniforms {\n * u_someColor: [1,0,0,1],\n * u_somePosition: [0,1,1],\n * u_someMatrix: [\n * 1,0,0,0,\n * 0,1,0,0,\n * 0,0,1,0,\n * 0,0,0,0,\n * ],\n * };\n *\n * twgl.setUniforms(programInfo, uniforms);\n * twgl.setUniforms(programInfo, moreUniforms);\n *\n * You can also add WebGLSamplers to uniform samplers as in\n *\n * const uniforms = {\n * u_someSampler: {\n * texture: someWebGLTexture,\n * sampler: someWebGLSampler,\n * },\n * };\n *\n * In which case both the sampler and texture will be bound to the\n * same unit.\n *\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * uniforms.\n * You can pass multiple objects by putting them in an array or by calling with more arguments.For example\n *\n * const sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * const localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * twgl.setUniforms(programInfo, sharedUniforms, localUniforms);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);\n *\n * // is the same as\n *\n * twgl.setUniforms(programInfo, sharedUniforms);\n * twgl.setUniforms(programInfo, localUniforms};\n *\n * You can also fill out structure and array values either via\n * shortcut. Example\n *\n * // -- in shader --\n * struct Light {\n * float intensity;\n * vec4 color;\n * float nearFar[2];\n * };\n * uniform Light lights[2];\n *\n * // in JavaScript\n *\n * twgl.setUniforms(programInfo, {\n * lights: [\n * { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },\n * { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },\n * ],\n * });\n *\n * or the more traditional way\n *\n * twgl.setUniforms(programInfo, {\n * \"lights[0].intensity\": 5.0,\n * \"lights[0].color\": [1, 0, 0, 1],\n * \"lights[0].nearFar\": [0.1, 10],\n * \"lights[1].intensity\": 2.0,\n * \"lights[1].color\": [0, 0, 1, 1],\n * \"lights[1].nearFar\": [0.2, 15],\n * });\n *\n * You can also specify partial paths\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },\n * });\n *\n * But you can not specify leaf array indices\n *\n * twgl.setUniforms(programInfo, {\n * 'lights[1].nearFar[1]': 15, // BAD! nearFar is a leaf\n * 'lights[1].nearFar': [0.2, 15], // GOOD\n * });\n *\n * @memberOf module:twgl/programs\n */\nfunction setUniforms(setters, ...args) { // eslint-disable-line\n const actualSetters = setters.uniformSetters || setters;\n const numArgs = args.length;\n for (let aNdx = 0; aNdx < numArgs; ++aNdx) {\n const values = args[aNdx];\n if (Array.isArray(values)) {\n const numValues = values.length;\n for (let ii = 0; ii < numValues; ++ii) {\n setUniforms(actualSetters, values[ii]);\n }\n } else {\n for (const name in values) {\n const setter = actualSetters[name];\n if (setter) {\n setter(values[name]);\n }\n }\n }\n }\n}\n\n/**\n * Alias for `setUniforms`\n * @function\n * @param {(module:twgl.ProgramInfo|Object.)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from\n * `createUniformSetters`.\n * @param {Object.} values an object with values for the\n * @memberOf module:twgl/programs\n */\nconst setUniformsAndBindTextures = setUniforms;\n\n/**\n * Creates setter functions for all attributes of a shader\n * program. You can pass this to {@link module:twgl.setBuffersAndAttributes} to set all your buffers and attributes.\n *\n * @see {@link module:twgl.setAttributes} for example\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {WebGLProgram} program the program to create setters for.\n * @return {Object.} an object with a setter for each attribute by name.\n * @memberOf module:twgl/programs\n */\nfunction createAttributeSetters(gl, program) {\n const attribSetters = {\n };\n\n const numAttribs = gl.getProgramParameter(program, ACTIVE_ATTRIBUTES);\n for (let ii = 0; ii < numAttribs; ++ii) {\n const attribInfo = gl.getActiveAttrib(program, ii);\n if (isBuiltIn(attribInfo)) {\n continue;\n }\n const index = gl.getAttribLocation(program, attribInfo.name);\n const typeInfo = attrTypeMap[attribInfo.type];\n const setter = typeInfo.setter(gl, index, typeInfo);\n setter.location = index;\n attribSetters[attribInfo.name] = setter;\n }\n\n return attribSetters;\n}\n\n/**\n * Sets attributes and binds buffers (deprecated... use {@link module:twgl.setBuffersAndAttributes})\n *\n * Example:\n *\n * const program = createProgramFromScripts(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const attribSetters = createAttributeSetters(program);\n *\n * const positionBuffer = gl.createBuffer();\n * const texcoordBuffer = gl.createBuffer();\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * };\n *\n * gl.useProgram(program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setAttributes(attribSetters, attribs);\n *\n * Properties of attribs. For each attrib you can add\n * properties:\n *\n * * type: the type of data in the buffer. Default = gl.FLOAT\n * * normalize: whether or not to normalize the data. Default = false\n * * stride: the stride. Default = 0\n * * offset: offset into the buffer. Default = 0\n * * divisor: the divisor for instances. Default = undefined\n *\n * For example if you had 3 value float positions, 2 value\n * float texcoord and 4 value uint8 colors you'd setup your\n * attribs like this\n *\n * const attribs = {\n * a_position: {buffer: positionBuffer, numComponents: 3},\n * a_texcoord: {buffer: texcoordBuffer, numComponents: 2},\n * a_color: {\n * buffer: colorBuffer,\n * numComponents: 4,\n * type: gl.UNSIGNED_BYTE,\n * normalize: true,\n * },\n * };\n *\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} buffers AttribInfos mapped by attribute name.\n * @memberOf module:twgl/programs\n * @deprecated use {@link module:twgl.setBuffersAndAttributes}\n * @private\n */\nfunction setAttributes(setters, buffers) {\n for (const name in buffers) {\n const setter = setters[name];\n if (setter) {\n setter(buffers[name]);\n }\n }\n}\n\n/**\n * Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate\n *\n * Example:\n *\n * const programInfo = createProgramInfo(\n * gl, [\"some-vs\", \"some-fs\");\n *\n * const arrays = {\n * position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },\n * texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },\n * };\n *\n * const bufferInfo = createBufferInfoFromArrays(gl, arrays);\n *\n * gl.useProgram(programInfo.program);\n *\n * This will automatically bind the buffers AND set the\n * attributes.\n *\n * setBuffersAndAttributes(gl, programInfo, bufferInfo);\n *\n * For the example above it is equivalent to\n *\n * gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n * gl.enableVertexAttribArray(a_positionLocation);\n * gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);\n * gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);\n * gl.enableVertexAttribArray(a_texcoordLocation);\n * gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext.\n * @param {(module:twgl.ProgramInfo|Object.)} setters A `ProgramInfo` as returned from {@link module:twgl.createProgramInfo} or Attribute setters as returned from {@link module:twgl.createAttributeSetters}\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} buffers a `BufferInfo` as returned from {@link module:twgl.createBufferInfoFromArrays}.\n * or a `VertexArrayInfo` as returned from {@link module:twgl.createVertexArrayInfo}\n * @memberOf module:twgl/programs\n */\nfunction setBuffersAndAttributes(gl, programInfo, buffers) {\n if (buffers.vertexArrayObject) {\n gl.bindVertexArray(buffers.vertexArrayObject);\n } else {\n setAttributes(programInfo.attribSetters || programInfo, buffers.attribs);\n if (buffers.indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER$1, buffers.indices);\n }\n }\n}\n\n/**\n * @typedef {Object} ProgramInfo\n * @property {WebGLProgram} program A shader program\n * @property {Object} uniformSetters object of setters as returned from createUniformSetters,\n * @property {Object} attribSetters object of setters as returned from createAttribSetters,\n * @property {module:twgl.UniformBlockSpec} [uniformBlockSpec] a uniform block spec for making UniformBlockInfos with createUniformBlockInfo etc..\n * @property {Object} [transformFeedbackInfo] info for transform feedbacks\n * @memberOf module:twgl\n */\n\n/**\n * Creates a ProgramInfo from an existing program.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {WebGLProgram} program an existing WebGLProgram.\n * @return {module:twgl.ProgramInfo} The created ProgramInfo.\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfoFromProgram(gl, program) {\n const uniformSetters = createUniformSetters(gl, program);\n const attribSetters = createAttributeSetters(gl, program);\n const programInfo = {\n program,\n uniformSetters,\n attribSetters,\n };\n\n if (isWebGL2(gl)) {\n programInfo.uniformBlockSpec = createUniformBlockSpecFromProgram(gl, program);\n programInfo.transformFeedbackInfo = createTransformFeedbackInfo(gl, program);\n }\n\n return programInfo;\n}\n\nconst notIdRE = /\\s|{|}|;/;\n\n/**\n * Creates a ProgramInfo from 2 sources.\n *\n * A ProgramInfo contains\n *\n * programInfo = {\n * program: WebGLProgram,\n * uniformSetters: object of setters as returned from createUniformSetters,\n * attribSetters: object of setters as returned from createAttribSetters,\n * }\n *\n * NOTE: There are 4 signatures for this function\n *\n * twgl.createProgramInfo(gl, [vs, fs], options);\n * twgl.createProgramInfo(gl, [vs, fs], opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc);\n * twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {string[]} shaderSources Array of sources for the\n * shaders or ids. The first is assumed to be the vertex shader,\n * the second the fragment shader.\n * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in\n * @param {number[]} [opt_locations|module:twgl.ErrorCallback] The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.\n * @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console\n * on error. If you want something else pass an callback. It's passed an error message.\n * @return {module:twgl.ProgramInfo?} The created ProgramInfo or null if it failed to link or compile\n * @memberOf module:twgl/programs\n */\nfunction createProgramInfo(\n gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {\n const progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);\n const errors = [];\n shaderSources = shaderSources.map(function(source) {\n // Lets assume if there is no \\n it's an id\n if (!notIdRE.test(source)) {\n const script = getElementById(source);\n if (!script) {\n const err = `no element with id: ${source}`;\n progOptions.errorCallback(err);\n errors.push(err);\n } else {\n source = script.text;\n }\n }\n return source;\n });\n\n if (errors.length) {\n return reportError(progOptions, '');\n }\n\n const origCallback = progOptions.callback;\n if (origCallback) {\n progOptions.callback = (err, program) => {\n origCallback(err, err ? undefined : createProgramInfoFromProgram(gl, program));\n };\n }\n\n const program = createProgramFromSources(gl, shaderSources, progOptions);\n if (!program) {\n return null;\n }\n\n return createProgramInfoFromProgram(gl, program);\n}\n\nfunction checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions) {\n // check errors for everything.\n for (const [name, program] of Object.entries(programs)) {\n const options = {...programOptions};\n const spec = programSpecs[name];\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n const errors = getProgramErrors(gl, program, options.errorCallback);\n if (errors) {\n // delete everything we created\n for (const program of Object.values(programs)) {\n const shaders = gl.getAttachedShaders(program);\n gl.deleteProgram(program);\n for (const shader of shaders) {\n // Don't delete it if we didn't create it.\n if (!noDeleteShadersSet.has(shader)) {\n gl.deleteShader(shader);\n }\n }\n }\n return errors;\n }\n }\n\n return undefined;\n}\n\n/**\n * Creates multiple programs\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgram}\n *\n * Example:\n *\n * const programs = twgl.createPrograms(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createPrograms(gl, programSpecs, programOptions = {}) {\n // Remember existing shaders so that if there is an error we don't delete them\n const noDeleteShadersSet = new Set();\n\n // compile and link everything\n const programs = Object.fromEntries(Object.entries(programSpecs).map(([name, spec]) => {\n const options = {...programOptions};\n const shaders = Array.isArray(spec) ? spec : spec.shaders;\n if (!Array.isArray(spec)) {\n Object.assign(options, spec);\n }\n shaders.forEach(noDeleteShadersSet.add, noDeleteShadersSet);\n return [name, createProgramNoCheck(gl, shaders, options)];\n }));\n\n if (programOptions.callback) {\n waitForAllProgramsLinkCompletionAsync(gl, programs).then(() => {\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n programOptions.callback(errors, errors ? undefined : programs);\n });\n return undefined;\n }\n\n const errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);\n return errors ? undefined : programs;\n}\n\n/**\n * Creates multiple programInfos\n *\n * Note: the reason this function exists is because the fastest way to create multiple\n * programs in WebGL is to create and compile all shaders and link all programs and only\n * afterwards check if they succeeded. In that way, giving all your shaders\n *\n * @see {@link module:twgl.createProgramInfo}\n *\n * Examples:\n *\n * const programInfos = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * or\n *\n * const {lambert, phong, particles} = twgl.createProgramInfos(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nfunction createProgramInfos(gl, programSpecs, programOptions) {\n programOptions = getProgramOptions(programOptions);\n\n function createProgramInfosForPrograms(gl, programs) {\n return Object.fromEntries(Object.entries(programs).map(([name, program]) =>\n [name, createProgramInfoFromProgram(gl, program)]\n ));\n }\n\n const origCallback = programOptions.callback;\n if (origCallback) {\n programOptions.callback = (err, programs) => {\n origCallback(err, err ? undefined : createProgramInfosForPrograms(gl, programs));\n };\n }\n\n const programs = createPrograms(gl, programSpecs, programOptions);\n if (origCallback || !programs) {\n return undefined;\n }\n\n return createProgramInfosForPrograms(gl, programs);\n}\n\n/**\n * Creates multiple programs asynchronously\n *\n * @see {@link module:twgl.createProgramAsync}\n *\n * Example:\n *\n * const programs = await twgl.createProgramsAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Object.?} the created programInfos by name\n */\nconst createProgramsAsync = wrapCallbackFnToAsyncFn(createPrograms);\n\n/**\n * Creates multiple programInfos asynchronously\n *\n * @see {@link module:twgl.createProgramInfoAsync}\n *\n * Example:\n *\n * const programInfos = await twgl.createProgramInfosAsync(gl, {\n * lambert: [lambertVS, lambertFS],\n * phong: [phongVS, phoneFS],\n * particles: {\n * shaders: [particlesVS, particlesFS],\n * transformFeedbackVaryings: ['position', 'velocity'],\n * },\n * });\n *\n * @function\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {Object.} programSpecs An object of ProgramSpecs, one per program.\n * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs\n * @return {Promise>} the created programInfos by name\n */\nconst createProgramInfosAsync = wrapCallbackFnToAsyncFn(createProgramInfos);\n\nvar programs = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createAttributeSetters: createAttributeSetters,\n createProgram: createProgram,\n createProgramAsync: createProgramAsync,\n createPrograms: createPrograms,\n createProgramsAsync: createProgramsAsync,\n createProgramFromScripts: createProgramFromScripts,\n createProgramFromSources: createProgramFromSources,\n createProgramInfo: createProgramInfo,\n createProgramInfoAsync: createProgramInfoAsync,\n createProgramInfos: createProgramInfos,\n createProgramInfosAsync: createProgramInfosAsync,\n createProgramInfoFromProgram: createProgramInfoFromProgram,\n createUniformSetters: createUniformSetters,\n createUniformBlockSpecFromProgram: createUniformBlockSpecFromProgram,\n createUniformBlockInfoFromProgram: createUniformBlockInfoFromProgram,\n createUniformBlockInfo: createUniformBlockInfo,\n createTransformFeedback: createTransformFeedback,\n createTransformFeedbackInfo: createTransformFeedbackInfo,\n bindTransformFeedbackInfo: bindTransformFeedbackInfo,\n setAttributes: setAttributes,\n setBuffersAndAttributes: setBuffersAndAttributes,\n setUniforms: setUniforms,\n setUniformsAndBindTextures: setUniformsAndBindTextures,\n setUniformBlock: setUniformBlock,\n setBlockUniforms: setBlockUniforms,\n bindUniformBlock: bindUniformBlock\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst TRIANGLES = 0x0004;\nconst UNSIGNED_SHORT = 0x1403;\n\n/**\n * Drawing related functions\n *\n * For backward compatibility they are available at both `twgl.draw` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/draw\n */\n\n/**\n * Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate\n *\n * normally you'd call `gl.drawElements` or `gl.drawArrays` yourself\n * but calling this means if you switch from indexed data to non-indexed\n * data you don't have to remember to update your draw call.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} bufferInfo A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays} or\n * a VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @param {number} [type] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to `gl.TRIANGLES`\n * @param {number} [count] An optional count. Defaults to bufferInfo.numElements\n * @param {number} [offset] An optional offset. Defaults to 0.\n * @param {number} [instanceCount] An optional instanceCount. if set then `drawArraysInstanced` or `drawElementsInstanced` will be called\n * @memberOf module:twgl/draw\n */\nfunction drawBufferInfo(gl, bufferInfo, type, count, offset, instanceCount) {\n type = type === undefined ? TRIANGLES : type;\n const indices = bufferInfo.indices;\n const elementType = bufferInfo.elementType;\n const numElements = count === undefined ? bufferInfo.numElements : count;\n offset = offset === undefined ? 0 : offset;\n if (elementType || indices) {\n if (instanceCount !== undefined) {\n gl.drawElementsInstanced(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset, instanceCount);\n } else {\n gl.drawElements(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset);\n }\n } else {\n if (instanceCount !== undefined) {\n gl.drawArraysInstanced(type, offset, numElements, instanceCount);\n } else {\n gl.drawArrays(type, offset, numElements);\n }\n }\n}\n\n/**\n * A DrawObject is useful for putting objects in to an array and passing them to {@link module:twgl.drawObjectList}.\n *\n * You need either a `BufferInfo` or a `VertexArrayInfo`.\n *\n * @typedef {Object} DrawObject\n * @property {boolean} [active] whether or not to draw. Default = `true` (must be `false` to be not true). In other words `undefined` = `true`\n * @property {number} [type] type to draw eg. `gl.TRIANGLES`, `gl.LINES`, etc...\n * @property {module:twgl.ProgramInfo} programInfo A ProgramInfo as returned from {@link module:twgl.createProgramInfo}\n * @property {module:twgl.BufferInfo} [bufferInfo] A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays}\n * @property {module:twgl.VertexArrayInfo} [vertexArrayInfo] A VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}\n * @property {Object} uniforms The values for the uniforms.\n * You can pass multiple objects by putting them in an array. For example\n *\n * var sharedUniforms = {\n * u_fogNear: 10,\n * u_projection: ...\n * ...\n * };\n *\n * var localUniforms = {\n * u_world: ...\n * u_diffuseColor: ...\n * };\n *\n * var drawObj = {\n * ...\n * uniforms: [sharedUniforms, localUniforms],\n * };\n *\n * @property {number} [offset] the offset to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to 0.\n * @property {number} [count] the count to pass to `gl.drawArrays` or `gl.drawElements`. Defaults to bufferInfo.numElements.\n * @property {number} [instanceCount] the number of instances. Defaults to undefined.\n * @memberOf module:twgl\n */\n\n/**\n * Draws a list of objects\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {DrawObject[]} objectsToDraw an array of objects to draw.\n * @memberOf module:twgl/draw\n */\nfunction drawObjectList(gl, objectsToDraw) {\n let lastUsedProgramInfo = null;\n let lastUsedBufferInfo = null;\n\n objectsToDraw.forEach(function(object) {\n if (object.active === false) {\n return;\n }\n\n const programInfo = object.programInfo;\n const bufferInfo = object.vertexArrayInfo || object.bufferInfo;\n let bindBuffers = false;\n const type = object.type === undefined ? TRIANGLES : object.type;\n\n if (programInfo !== lastUsedProgramInfo) {\n lastUsedProgramInfo = programInfo;\n gl.useProgram(programInfo.program);\n\n // We have to rebind buffers when changing programs because we\n // only bind buffers the program uses. So if 2 programs use the same\n // bufferInfo but the 1st one uses only positions the when the\n // we switch to the 2nd one some of the attributes will not be on.\n bindBuffers = true;\n }\n\n // Setup all the needed attributes.\n if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject && !bufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n lastUsedBufferInfo = bufferInfo;\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n }\n\n // Set the uniforms.\n setUniforms(programInfo, object.uniforms);\n\n // Draw\n drawBufferInfo(gl, bufferInfo, type, object.count, object.offset, object.instanceCount);\n });\n\n if (lastUsedBufferInfo && lastUsedBufferInfo.vertexArrayObject) {\n gl.bindVertexArray(null);\n }\n}\n\nvar draw = /*#__PURE__*/Object.freeze({\n __proto__: null,\n drawBufferInfo: drawBufferInfo,\n drawObjectList: drawObjectList\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nconst FRAMEBUFFER = 0x8d40;\nconst RENDERBUFFER = 0x8d41;\nconst TEXTURE_2D = 0x0de1;\n\nconst UNSIGNED_BYTE = 0x1401;\n\n/* PixelFormat */\nconst DEPTH_COMPONENT = 0x1902;\nconst RGBA = 0x1908;\nconst DEPTH_COMPONENT24 = 0x81a6;\nconst DEPTH_COMPONENT32F = 0x8cac;\nconst DEPTH24_STENCIL8 = 0x88f0;\nconst DEPTH32F_STENCIL8 = 0x8cad;\n\n/* Framebuffer Object. */\nconst RGBA4 = 0x8056;\nconst RGB5_A1 = 0x8057;\nconst RGB565 = 0x8D62;\nconst DEPTH_COMPONENT16 = 0x81A5;\nconst STENCIL_INDEX = 0x1901;\nconst STENCIL_INDEX8 = 0x8D48;\nconst DEPTH_STENCIL = 0x84F9;\nconst COLOR_ATTACHMENT0 = 0x8CE0;\nconst DEPTH_ATTACHMENT = 0x8D00;\nconst STENCIL_ATTACHMENT = 0x8D20;\nconst DEPTH_STENCIL_ATTACHMENT = 0x821A;\n\n/* TextureWrapMode */\nconst CLAMP_TO_EDGE = 0x812F;\n\n/* TextureMagFilter */\nconst LINEAR = 0x2601;\n\n/**\n * The options for a framebuffer attachment.\n *\n * Note: For a `format` that is a texture include all the texture\n * options from {@link module:twgl.TextureOptions} for example\n * `min`, `mag`, `clamp`, etc... Note that unlike {@link module:twgl.TextureOptions}\n * `auto` defaults to `false` for attachment textures but `min` and `mag` default\n * to `gl.LINEAR` and `wrap` defaults to `CLAMP_TO_EDGE`\n *\n * @typedef {Object} AttachmentOptions\n * @property {number} [attachmentPoint] The attachment point. Defaults\n * to `gl.COLOR_ATTACHMENT0 + ndx` unless type is a depth or stencil type\n * then it's gl.DEPTH_ATTACHMENT or `gl.DEPTH_STENCIL_ATTACHMENT` depending\n * on the format or attachment type.\n * @property {number} [format] The format. If one of `gl.RGBA4`,\n * `gl.RGB565`, `gl.RGB5_A1`, `gl.DEPTH_COMPONENT16`,\n * `gl.STENCIL_INDEX8` or `gl.DEPTH_STENCIL` then will create a\n * renderbuffer. Otherwise will create a texture. Default = `gl.RGBA`\n * @property {number} [type] The type. Used for texture. Default = `gl.UNSIGNED_BYTE`.\n * @property {number} [target] The texture target for `gl.framebufferTexture2D`.\n * Defaults to `gl.TEXTURE_2D`. Set to appropriate face for cube maps.\n * @property {number} [samples] The number of samples. Default = 1\n * @property {number} [level] level for `gl.framebufferTexture2D`. Defaults to 0.\n * @property {number} [layer] layer for `gl.framebufferTextureLayer`. Defaults to undefined.\n * If set then `gl.framebufferTextureLayer` is called, if not then `gl.framebufferTexture2D`\n * @property {(WebGLRenderbuffer | WebGLTexture)} [attachment] An existing renderbuffer or texture.\n * If provided will attach this Object. This allows you to share\n * attachments across framebuffers.\n * @memberOf module:twgl\n * @mixes module:twgl.TextureOptions\n */\n\nconst defaultAttachments = [\n { format: RGBA, type: UNSIGNED_BYTE, min: LINEAR, wrap: CLAMP_TO_EDGE, },\n { format: DEPTH_STENCIL, },\n];\n\nconst attachmentsByFormat = {};\nattachmentsByFormat[DEPTH_STENCIL] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX] = STENCIL_ATTACHMENT;\nattachmentsByFormat[STENCIL_INDEX8] = STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT16] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT24] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH_COMPONENT32F] = DEPTH_ATTACHMENT;\nattachmentsByFormat[DEPTH24_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\nattachmentsByFormat[DEPTH32F_STENCIL8] = DEPTH_STENCIL_ATTACHMENT;\n\nfunction getAttachmentPointForFormat(format, internalFormat) {\n return attachmentsByFormat[format] || attachmentsByFormat[internalFormat];\n}\n\nconst renderbufferFormats = {};\nrenderbufferFormats[RGBA4] = true;\nrenderbufferFormats[RGB5_A1] = true;\nrenderbufferFormats[RGB565] = true;\nrenderbufferFormats[DEPTH_STENCIL] = true;\nrenderbufferFormats[DEPTH_COMPONENT16] = true;\nrenderbufferFormats[STENCIL_INDEX] = true;\nrenderbufferFormats[STENCIL_INDEX8] = true;\n\nfunction isRenderbufferFormat(format) {\n return renderbufferFormats[format];\n}\n\nconst MAX_COLOR_ATTACHMENT_POINTS = 32; // even an 3090 only supports 8 but WebGL/OpenGL ES define constants for 32\n\nfunction isColorAttachmentPoint(attachmentPoint) {\n return attachmentPoint >= COLOR_ATTACHMENT0 && attachmentPoint < COLOR_ATTACHMENT0 + MAX_COLOR_ATTACHMENT_POINTS;\n}\n\n/**\n * @typedef {Object} FramebufferInfo\n * @property {WebGLFramebuffer} framebuffer The WebGLFramebuffer for this framebufferInfo\n * @property {Array.<(WebGLRenderbuffer | WebGLTexture)>} attachments The created attachments in the same order as passed in to {@link module:twgl.createFramebufferInfo}.\n * @property {number} width The width of the framebuffer and its attachments\n * @property {number} height The width of the framebuffer and its attachments\n * @memberOf module:twgl\n */\n\n/**\n * Creates a framebuffer and attachments.\n *\n * This returns a {@link module:twgl.FramebufferInfo} because it needs to return the attachments as well as the framebuffer.\n * It also leaves the framebuffer it just created as the currently bound `FRAMEBUFFER`.\n * Note: If this is WebGL2 or if you called {@link module:twgl.addExtensionsToContext} then it will set the drawBuffers\n * to `[COLOR_ATTACHMENT0, COLOR_ATTACHMENT1, ...]` for how ever many color attachments were created.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * Passing in a specific size\n *\n * const width = 256;\n * const height = 256;\n * const fbi = twgl.createFramebufferInfo(gl, attachments, width, height);\n *\n * **Note!!** It is up to you to check if the framebuffer is renderable by calling `gl.checkFramebufferStatus`.\n * [WebGL1 only guarantees 3 combinations of attachments work](https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.6).\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.AttachmentOptions[]} [attachments] which attachments to create. If not provided the default is a framebuffer with an\n * `RGBA`, `UNSIGNED_BYTE` texture `COLOR_ATTACHMENT0` and a `DEPTH_STENCIL` renderbuffer `DEPTH_STENCIL_ATTACHMENT`.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @return {module:twgl.FramebufferInfo} the framebuffer and attachments.\n * @memberOf module:twgl/framebuffers\n */\nfunction createFramebufferInfo(gl, attachments, width, height) {\n const target = FRAMEBUFFER;\n const fb = gl.createFramebuffer();\n gl.bindFramebuffer(target, fb);\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n attachments = attachments || defaultAttachments;\n const usedColorAttachmentsPoints = [];\n const framebufferInfo = {\n framebuffer: fb,\n attachments: [],\n width: width,\n height: height,\n };\n\n attachments.forEach(function(attachmentOptions, i) {\n let attachment = attachmentOptions.attachment;\n const samples = attachmentOptions.samples;\n const format = attachmentOptions.format;\n let attachmentPoint = attachmentOptions.attachmentPoint || getAttachmentPointForFormat(format, attachmentOptions.internalFormat);\n if (!attachmentPoint) {\n attachmentPoint = COLOR_ATTACHMENT0 + i;\n }\n if (isColorAttachmentPoint(attachmentPoint)) {\n usedColorAttachmentsPoints.push(attachmentPoint);\n }\n if (!attachment) {\n if (samples !== undefined || isRenderbufferFormat(format)) {\n attachment = gl.createRenderbuffer();\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else {\n const textureOptions = Object.assign({}, attachmentOptions);\n textureOptions.width = width;\n textureOptions.height = height;\n if (textureOptions.auto === undefined) {\n textureOptions.auto = false;\n textureOptions.min = textureOptions.min || textureOptions.minMag || LINEAR;\n textureOptions.mag = textureOptions.mag || textureOptions.minMag || LINEAR;\n textureOptions.wrapS = textureOptions.wrapS || textureOptions.wrap || CLAMP_TO_EDGE;\n textureOptions.wrapT = textureOptions.wrapT || textureOptions.wrap || CLAMP_TO_EDGE;\n }\n attachment = createTexture(gl, textureOptions);\n }\n }\n if (isRenderbuffer(gl, attachment)) {\n gl.framebufferRenderbuffer(target, attachmentPoint, RENDERBUFFER, attachment);\n } else if (isTexture(gl, attachment)) {\n if (attachmentOptions.layer !== undefined) {\n gl.framebufferTextureLayer(\n target,\n attachmentPoint,\n attachment,\n attachmentOptions.level || 0,\n attachmentOptions.layer);\n } else {\n gl.framebufferTexture2D(\n target,\n attachmentPoint,\n attachmentOptions.target || TEXTURE_2D,\n attachment,\n attachmentOptions.level || 0);\n }\n } else {\n throw new Error('unknown attachment type');\n }\n framebufferInfo.attachments.push(attachment);\n });\n if (gl.drawBuffers) {\n gl.drawBuffers(usedColorAttachmentsPoints);\n }\n return framebufferInfo;\n}\n\n/**\n * Resizes the attachments of a framebuffer.\n *\n * You need to pass in the same `attachments` as you passed in {@link module:twgl.createFramebufferInfo}\n * because TWGL has no idea the format/type of each attachment.\n *\n * The simplest usage\n *\n * // create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer\n * const fbi = twgl.createFramebufferInfo(gl);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments\n * twgl.resizeFramebufferInfo(gl, fbi);\n * }\n *\n * More complex usage\n *\n * // create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer\n * const attachments = [\n * { format: RGB565, mag: NEAREST },\n * { format: STENCIL_INDEX8 },\n * ]\n * const fbi = twgl.createFramebufferInfo(gl, attachments);\n *\n * ...\n *\n * function render() {\n * if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {\n * // resize the attachments to match\n * twgl.resizeFramebufferInfo(gl, fbi, attachments);\n * }\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo} framebufferInfo a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * @param {module:twgl.AttachmentOptions[]} [attachments] the same attachments options as passed to {@link module:twgl.createFramebufferInfo}.\n * @param {number} [width] the width for the attachments. Default = size of drawingBuffer\n * @param {number} [height] the height for the attachments. Default = size of drawingBuffer\n * @memberOf module:twgl/framebuffers\n */\nfunction resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height) {\n width = width || gl.drawingBufferWidth;\n height = height || gl.drawingBufferHeight;\n framebufferInfo.width = width;\n framebufferInfo.height = height;\n attachments = attachments || defaultAttachments;\n attachments.forEach(function(attachmentOptions, ndx) {\n const attachment = framebufferInfo.attachments[ndx];\n const format = attachmentOptions.format;\n const samples = attachmentOptions.samples;\n if (samples !== undefined || isRenderbuffer(gl, attachment)) {\n gl.bindRenderbuffer(RENDERBUFFER, attachment);\n if (samples > 1) {\n gl.renderbufferStorageMultisample(RENDERBUFFER, samples, format, width, height);\n } else {\n gl.renderbufferStorage(RENDERBUFFER, format, width, height);\n }\n } else if (isTexture(gl, attachment)) {\n resizeTexture(gl, attachment, attachmentOptions, width, height);\n } else {\n throw new Error('unknown attachment type');\n }\n });\n}\n\n/**\n * Binds a framebuffer\n *\n * This function pretty much solely exists because I spent hours\n * trying to figure out why something I wrote wasn't working only\n * to realize I forget to set the viewport dimensions.\n * My hope is this function will fix that.\n *\n * It is effectively the same as\n *\n * gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer);\n * gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height);\n *\n * @param {WebGLRenderingContext} gl the WebGLRenderingContext\n * @param {module:twgl.FramebufferInfo|null} [framebufferInfo] a framebufferInfo as returned from {@link module:twgl.createFramebufferInfo}.\n * If falsy will bind the canvas.\n * @param {number} [target] The target. If not passed `gl.FRAMEBUFFER` will be used.\n * @memberOf module:twgl/framebuffers\n */\n\nfunction bindFramebufferInfo(gl, framebufferInfo, target) {\n target = target || FRAMEBUFFER;\n if (framebufferInfo) {\n gl.bindFramebuffer(target, framebufferInfo.framebuffer);\n gl.viewport(0, 0, framebufferInfo.width, framebufferInfo.height);\n } else {\n gl.bindFramebuffer(target, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n }\n}\n\nvar framebuffers = /*#__PURE__*/Object.freeze({\n __proto__: null,\n bindFramebufferInfo: bindFramebufferInfo,\n createFramebufferInfo: createFramebufferInfo,\n resizeFramebufferInfo: resizeFramebufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * vertex array object related functions\n *\n * You should generally not need to use these functions. They are provided\n * for those cases where you're doing something out of the ordinary\n * and you need lower level access.\n *\n * For backward compatibility they are available at both `twgl.attributes` and `twgl`\n * itself\n *\n * See {@link module:twgl} for core functions\n *\n * @module twgl/vertexArrays\n */\n\nconst ELEMENT_ARRAY_BUFFER = 0x8893;\n\n/**\n * @typedef {Object} VertexArrayInfo\n * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.\n * @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..\n * @property {WebGLVertexArrayObject} [vertexArrayObject] a vertex array object\n * @memberOf module:twgl\n */\n\n/**\n * Creates a VertexArrayInfo from a BufferInfo and one or more ProgramInfos\n *\n * This can be passed to {@link module:twgl.setBuffersAndAttributes} and to\n * {@link module:twgl:drawBufferInfo}.\n *\n * > **IMPORTANT:** Vertex Array Objects are **not** a direct analog for a BufferInfo. Vertex Array Objects\n * assign buffers to specific attributes at creation time. That means they can only be used with programs\n * who's attributes use the same attribute locations for the same purposes.\n *\n * > Bind your attribute locations by passing an array of attribute names to {@link module:twgl.createProgramInfo}\n * or use WebGL 2's GLSL ES 3's `layout(location = )` to make sure locations match.\n *\n * also\n *\n * > **IMPORTANT:** After calling twgl.setBuffersAndAttribute with a BufferInfo that uses a Vertex Array Object\n * that Vertex Array Object will be bound. That means **ANY MANIPULATION OF ELEMENT_ARRAY_BUFFER or ATTRIBUTES**\n * will affect the Vertex Array Object state.\n *\n * > Call `gl.bindVertexArray(null)` to get back manipulating the global attributes and ELEMENT_ARRAY_BUFFER.\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @param {module:twgl.ProgramInfo|module:twgl.ProgramInfo[]} programInfo a programInfo or array of programInfos\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n *\n * You need to make sure every attribute that will be used is bound. So for example assume shader 1\n * uses attributes A, B, C and shader 2 uses attributes A, B, D. If you only pass in the programInfo\n * for shader 1 then only attributes A, B, and C will have their attributes set because TWGL doesn't\n * now attribute D's location.\n *\n * So, you can pass in both shader 1 and shader 2's programInfo\n *\n * @return {module:twgl.VertexArrayInfo} The created VertexArrayInfo\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVertexArrayInfo(gl, programInfos, bufferInfo) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n if (!programInfos.length) {\n programInfos = [programInfos];\n }\n programInfos.forEach(function(programInfo) {\n setBuffersAndAttributes(gl, programInfo, bufferInfo);\n });\n gl.bindVertexArray(null);\n return {\n numElements: bufferInfo.numElements,\n elementType: bufferInfo.elementType,\n vertexArrayObject: vao,\n };\n}\n\n/**\n * Creates a vertex array object and then sets the attributes on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.\n * @param {Object.} setters Attribute setters as returned from createAttributeSetters\n * @param {Object.} attribs AttribInfos mapped by attribute name.\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOAndSetAttributes(gl, setters, attribs, indices) {\n const vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n setAttributes(setters, attribs);\n if (indices) {\n gl.bindBuffer(ELEMENT_ARRAY_BUFFER, indices);\n }\n // We unbind this because otherwise any change to ELEMENT_ARRAY_BUFFER\n // like when creating buffers for other stuff will mess up this VAO's binding\n gl.bindVertexArray(null);\n return vao;\n}\n\n/**\n * Creates a vertex array object and then sets the attributes\n * on it\n *\n * @param {WebGLRenderingContext} gl The WebGLRenderingContext\n * to use.\n * @param {Object.| module:twgl.ProgramInfo} programInfo as returned from createProgramInfo or Attribute setters as returned from createAttributeSetters\n * @param {module:twgl.BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc...\n * @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices\n *\n * @return {WebGLVertexArrayObject|null} The created WebGLVertexArrayObject\n *\n * @memberOf module:twgl/vertexArrays\n */\nfunction createVAOFromBufferInfo(gl, programInfo, bufferInfo) {\n return createVAOAndSetAttributes(gl, programInfo.attribSetters || programInfo, bufferInfo.attribs, bufferInfo.indices);\n}\n\nvar vertexArrays = /*#__PURE__*/Object.freeze({\n __proto__: null,\n createVertexArrayInfo: createVertexArrayInfo,\n createVAOAndSetAttributes: createVAOAndSetAttributes,\n createVAOFromBufferInfo: createVAOFromBufferInfo\n});\n\n/*\n * Copyright 2019 Gregg Tavares\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nconst defaults = {\n addExtensionsToContext: true,\n};\n\n/**\n * Various default settings for twgl.\n *\n * Note: You can call this any number of times. Example:\n *\n * twgl.setDefaults({ textureColor: [1, 0, 0, 1] });\n * twgl.setDefaults({ attribPrefix: 'a_' });\n *\n * is equivalent to\n *\n * twgl.setDefaults({\n * textureColor: [1, 0, 0, 1],\n * attribPrefix: 'a_',\n * });\n *\n * @typedef {Object} Defaults\n * @property {string} [attribPrefix] The prefix to stick on attributes\n *\n * When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`\n * as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.\n *\n * In other words I'll create arrays of geometry like this\n *\n * const arrays = {\n * position: ...\n * normal: ...\n * texcoord: ...\n * };\n *\n * But need those mapped to attributes and my attributes start with `a_`.\n *\n * Default: `\"\"`\n *\n * @property {number[]} [textureColor] Array of 4 values in the range 0 to 1\n *\n * The default texture color is used when loading textures from\n * urls. Because the URL will be loaded async we'd like to be\n * able to use the texture immediately. By putting a 1x1 pixel\n * color in the texture we can start using the texture before\n * the URL has loaded.\n *\n * Default: `[0.5, 0.75, 1, 1]`\n *\n * @property {string} [crossOrigin]\n *\n * If not undefined sets the crossOrigin attribute on images\n * that twgl creates when downloading images for textures.\n *\n * Also see {@link module:twgl.TextureOptions}.\n *\n * @property {bool} [addExtensionsToContext]\n *\n * If true, then, when twgl will try to add any supported WebGL extensions\n * directly to the context under their normal GL names. For example\n * if ANGLE_instances_arrays exists then twgl would enable it,\n * add the functions `vertexAttribDivisor`, `drawArraysInstanced`,\n * `drawElementsInstanced`, and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR`\n * to the `WebGLRenderingContext`.\n *\n * @memberOf module:twgl\n */\n\n/**\n * Sets various defaults for twgl.\n *\n * In the interest of terseness which is kind of the point\n * of twgl I've integrated a few of the older functions here\n *\n * @param {module:twgl.Defaults} newDefaults The default settings.\n * @memberOf module:twgl\n */\nfunction setDefaults(newDefaults) {\n copyExistingProperties(newDefaults, defaults);\n setDefaults$2(newDefaults); // eslint-disable-line\n setDefaults$1(newDefaults); // eslint-disable-line\n}\n\nconst prefixRE = /^(.*?)_/;\nfunction addExtensionToContext(gl, extensionName) {\n glEnumToString(gl, 0);\n const ext = gl.getExtension(extensionName);\n if (ext) {\n const enums = {};\n const fnSuffix = prefixRE.exec(extensionName)[1];\n const enumSuffix = '_' + fnSuffix;\n for (const key in ext) {\n const value = ext[key];\n const isFunc = typeof (value) === 'function';\n const suffix = isFunc ? fnSuffix : enumSuffix;\n let name = key;\n // examples of where this is not true are WEBGL_compressed_texture_s3tc\n // and WEBGL_compressed_texture_pvrtc\n if (key.endsWith(suffix)) {\n name = key.substring(0, key.length - suffix.length);\n }\n if (gl[name] !== undefined) {\n if (!isFunc && gl[name] !== value) {\n warn$1(name, gl[name], value, key);\n }\n } else {\n if (isFunc) {\n gl[name] = function(origFn) {\n return function() {\n return origFn.apply(ext, arguments);\n };\n }(value);\n } else {\n gl[name] = value;\n enums[name] = value;\n }\n }\n }\n // pass the modified enums to glEnumToString\n enums.constructor = {\n name: ext.constructor.name,\n };\n glEnumToString(enums, 0);\n }\n return ext;\n}\n\n/*\n * If you're wondering why the code doesn't just iterate\n * over all extensions using `gl.getExtensions` is that it's possible\n * some future extension is incompatible with this code. Rather than\n * have thing suddenly break it seems better to manually add to this\n * list.\n *\n */\nconst supportedExtensions = [\n 'ANGLE_instanced_arrays',\n 'EXT_blend_minmax',\n 'EXT_color_buffer_float',\n 'EXT_color_buffer_half_float',\n 'EXT_disjoint_timer_query',\n 'EXT_disjoint_timer_query_webgl2',\n 'EXT_frag_depth',\n 'EXT_sRGB',\n 'EXT_shader_texture_lod',\n 'EXT_texture_filter_anisotropic',\n 'OES_element_index_uint',\n 'OES_standard_derivatives',\n 'OES_texture_float',\n 'OES_texture_float_linear',\n 'OES_texture_half_float',\n 'OES_texture_half_float_linear',\n 'OES_vertex_array_object',\n 'WEBGL_color_buffer_float',\n 'WEBGL_compressed_texture_atc',\n 'WEBGL_compressed_texture_etc1',\n 'WEBGL_compressed_texture_pvrtc',\n 'WEBGL_compressed_texture_s3tc',\n 'WEBGL_compressed_texture_s3tc_srgb',\n 'WEBGL_depth_texture',\n 'WEBGL_draw_buffers',\n];\n\n/**\n * Attempts to enable all of the following extensions\n * and add their functions and constants to the\n * `WebGLRenderingContext` using their normal non-extension like names.\n *\n * ANGLE_instanced_arrays\n * EXT_blend_minmax\n * EXT_color_buffer_float\n * EXT_color_buffer_half_float\n * EXT_disjoint_timer_query\n * EXT_disjoint_timer_query_webgl2\n * EXT_frag_depth\n * EXT_sRGB\n * EXT_shader_texture_lod\n * EXT_texture_filter_anisotropic\n * OES_element_index_uint\n * OES_standard_derivatives\n * OES_texture_float\n * OES_texture_float_linear\n * OES_texture_half_float\n * OES_texture_half_float_linear\n * OES_vertex_array_object\n * WEBGL_color_buffer_float\n * WEBGL_compressed_texture_atc\n * WEBGL_compressed_texture_etc1\n * WEBGL_compressed_texture_pvrtc\n * WEBGL_compressed_texture_s3tc\n * WEBGL_compressed_texture_s3tc_srgb\n * WEBGL_depth_texture\n * WEBGL_draw_buffers\n *\n * For example if `ANGLE_instanced_arrays` exists then the functions\n * `drawArraysInstanced`, `drawElementsInstanced`, `vertexAttribDivisor`\n * and the constant `VERTEX_ATTRIB_ARRAY_DIVISOR` are added to the\n * `WebGLRenderingContext`.\n *\n * Note that if you want to know if the extension exists you should\n * probably call `gl.getExtension` for each extension. Alternatively\n * you can check for the existence of the functions or constants that\n * are expected to be added. For example\n *\n * if (gl.drawBuffers) {\n * // Either WEBGL_draw_buffers was enabled OR you're running in WebGL2\n * ....\n *\n * @param {WebGLRenderingContext} gl A WebGLRenderingContext\n * @memberOf module:twgl\n */\nfunction addExtensionsToContext(gl) {\n for (let ii = 0; ii < supportedExtensions.length; ++ii) {\n addExtensionToContext(gl, supportedExtensions[ii]);\n }\n}\n\n/**\n * Creates a webgl context.\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n * @private\n */\nfunction create3DContext(canvas, opt_attribs) {\n const names = [\"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL1 context.\n *\n * Note: Will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n * @deprecated\n * @private\n */\nfunction getWebGLContext(canvas, opt_attribs) {\n const gl = create3DContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Creates a webgl context.\n *\n * Will return a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * twgl.isWebGL2(gl);\n *\n * @param {HTMLCanvasElement} canvas The canvas tag to get\n * context from. If one is not passed in one will be\n * created.\n * @return {WebGLRenderingContext} The created context.\n */\nfunction createContext(canvas, opt_attribs) {\n const names = [\"webgl2\", \"webgl\", \"experimental-webgl\"];\n let context = null;\n for (let ii = 0; ii < names.length; ++ii) {\n context = canvas.getContext(names[ii], opt_attribs);\n if (context) {\n if (defaults.addExtensionsToContext) {\n addExtensionsToContext(context);\n }\n break;\n }\n }\n return context;\n}\n\n/**\n * Gets a WebGL context. Will create a WebGL2 context if possible.\n *\n * You can check if it's WebGL2 with\n *\n * function isWebGL2(gl) {\n * return gl.getParameter(gl.VERSION).indexOf(\"WebGL 2.0 \") == 0;\n * }\n *\n * Note: For a WebGL1 context will attempt to enable Vertex Array Objects\n * and add WebGL2 entry points. (unless you first set defaults with\n * `twgl.setDefaults({enableVertexArrayObjects: false})`;\n *\n * @param {HTMLCanvasElement} canvas a canvas element.\n * @param {WebGLContextAttributes} [opt_attribs] optional webgl context creation attributes\n * @return {WebGLRenderingContext} The created context.\n * @memberOf module:twgl\n */\nfunction getContext(canvas, opt_attribs) {\n const gl = createContext(canvas, opt_attribs);\n return gl;\n}\n\n/**\n * Resize a canvas to match the size it's displayed.\n * @param {HTMLCanvasElement} canvas The canvas to resize.\n * @param {number} [multiplier] So you can pass in `window.devicePixelRatio` or other scale value if you want to.\n * @return {boolean} true if the canvas was resized.\n * @memberOf module:twgl\n */\nfunction resizeCanvasToDisplaySize(canvas, multiplier) {\n multiplier = multiplier || 1;\n multiplier = Math.max(0, multiplier);\n const width = canvas.clientWidth * multiplier | 0;\n const height = canvas.clientHeight * multiplier | 0;\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n return true;\n }\n return false;\n}\n\nexport { addExtensionsToContext, attributes, bindFramebufferInfo, bindTransformFeedbackInfo, bindUniformBlock, canFilter, canGenerateMipmap, createAttribsFromArrays, createAttributeSetters, createBufferFromArray, createBufferFromTypedArray, createBufferInfoFromArrays, createBuffersFromArrays, createFramebufferInfo, createProgram, createProgramAsync, createProgramFromScripts, createProgramFromSources, createProgramInfo, createProgramInfoAsync, createProgramInfoFromProgram, createProgramInfos, createProgramInfosAsync, createPrograms, createProgramsAsync, createSampler, createSamplers, createTexture, createTextures, createTransformFeedback, createTransformFeedbackInfo, createUniformBlockInfo, createUniformBlockInfoFromProgram, createUniformBlockSpecFromProgram, createUniformSetters, createVAOAndSetAttributes, createVAOFromBufferInfo, createVertexArrayInfo, draw, drawBufferInfo, drawObjectList, framebuffers, getArray$1 as getArray_, getBytesPerElementForInternalFormat, getContext, getFormatAndTypeForInternalFormat, getGLTypeForTypedArray, getGLTypeForTypedArrayType, getNumComponentsForFormat, getNumComponents$1 as getNumComponents_, getTypedArrayTypeForGLType, getWebGLContext, glEnumToString, isArrayBuffer$1 as isArrayBuffer, isWebGL1, isWebGL2, loadTextureFromUrl, m4, primitives, programs, resizeCanvasToDisplaySize, resizeFramebufferInfo, resizeTexture, setAttribInfoBufferFromArray, setDefaults$2 as setAttributeDefaults_, setAttributePrefix, setAttributes, setBlockUniforms, setBuffersAndAttributes, setDefaultTextureColor, setDefaults, setEmptyTexture, setSamplerParameters, setDefaults$1 as setTextureDefaults_, setTextureFilteringForSize, setTextureFromArray, setTextureFromElement, setTextureParameters, setUniformBlock, setUniforms, setUniformsAndBindTextures, textures, typedarrays, utils, v3, vertexArrays };\n","/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\n\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};","import * as glMatrix from \"./common.js\";\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a the source 4x4 matrix\n * @returns {mat3} out\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\n\nexport var perspective = perspectiveNO;\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\n\nexport var ortho = orthoNO;\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\n * Quaternion\n * @module quat\n */\n\n/**\n * Creates a new identity quat\n *\n * @returns {quat} a new quaternion\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n out[3] = 1;\n return out;\n}\n/**\n * Set a quat to the identity quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\n * Sets a quat from the given angle and rotation axis,\n * then returns it.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyVec3} axis the axis around which to rotate\n * @param {Number} rad the angle in radians\n * @returns {quat} out\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\n * Gets the rotation axis and angle for a given\n * quaternion. If a quaternion is created with\n * setAxisAngle, this method will return the same\n * values as providied in the original parameter list\n * OR functionally equivalent values.\n * Example: The quaternion formed by axis [0, 0, 1] and\n * angle -90 is the same as the quaternion formed by\n * [0, 0, 1] and 270. This method favors the latter.\n * @param {vec3} out_axis Vector receiving the axis of rotation\n * @param {ReadonlyQuat} q Quaternion to be decomposed\n * @return {Number} Angle, in radians, of the rotation\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\n * Gets the angular distance between two unit quaternions\n *\n * @param {ReadonlyQuat} a Origin unit quaternion\n * @param {ReadonlyQuat} b Destination unit quaternion\n * @return {Number} Angle, in radians, between the two quaternions\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\n * Multiplies two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the X axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Y axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Z axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\n * Calculates the W component of a quat from the X, Y, and Z components.\n * Assumes that quaternion is 1 unit in length.\n * Any existing W component will be ignored.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate W component of\n * @returns {quat} out\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\n * Calculate the exponential of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\n * Calculate the natural logarithm of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\n * Calculate the scalar power of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @param {Number} b amount to scale the quaternion by\n * @returns {quat} out\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\n * Performs a spherical linear interpolation between two quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\n * Generates a random unit quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\n * Calculates the inverse of a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate inverse of\n * @returns {quat} out\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\n * Calculates the conjugate of a quat\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate conjugate of\n * @returns {quat} out\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a quaternion from the given 3x3 rotation matrix.\n *\n * NOTE: The resultant quaternion is not normalized, so you should be sure\n * to renormalize the quaternion yourself where necessary.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyMat3} m rotation matrix\n * @returns {quat} out\n * @function\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\n * Creates a quaternion from the given euler angle x, y, z.\n *\n * @param {quat} out the receiving quaternion\n * @param {x} Angle to rotate around X axis in degrees.\n * @param {y} Angle to rotate around Y axis in degrees.\n * @param {z} Angle to rotate around Z axis in degrees.\n * @returns {quat} out\n * @function\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\n * Returns a string representation of a quatenion\n *\n * @param {ReadonlyQuat} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Creates a new quat initialized with values from an existing quaternion\n *\n * @param {ReadonlyQuat} a quaternion to clone\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var clone = vec4.clone;\n/**\n * Creates a new quat initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var fromValues = vec4.fromValues;\n/**\n * Copy the values from one quat to another\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the source quaternion\n * @returns {quat} out\n * @function\n */\n\nexport var copy = vec4.copy;\n/**\n * Set the components of a quat to the given values\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} out\n * @function\n */\n\nexport var set = vec4.set;\n/**\n * Adds two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n * @function\n */\n\nexport var add = vec4.add;\n/**\n * Alias for {@link quat.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Scales a quat by a scalar number\n *\n * @param {quat} out the receiving vector\n * @param {ReadonlyQuat} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {quat} out\n * @function\n */\n\nexport var scale = vec4.scale;\n/**\n * Calculates the dot product of two quat's\n *\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {Number} dot product of a and b\n * @function\n */\n\nexport var dot = vec4.dot;\n/**\n * Performs a linear interpolation between two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n * @function\n */\n\nexport var lerp = vec4.lerp;\n/**\n * Calculates the length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport var length = vec4.length;\n/**\n * Alias for {@link quat.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Calculates the squared length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate squared length of\n * @returns {Number} squared length of a\n * @function\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\n * Alias for {@link quat.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Normalize a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quaternion to normalize\n * @returns {quat} out\n * @function\n */\n\nexport var normalize = vec4.normalize;\n/**\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyQuat} a The first quaternion.\n * @param {ReadonlyQuat} b The second quaternion.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\n * Returns whether or not the quaternions have approximately the same elements in the same position.\n *\n * @param {ReadonlyQuat} a The first vector.\n * @param {ReadonlyQuat} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var equals = vec4.equals;\n/**\n * Sets a quaternion to represent the shortest rotation from one\n * vector to another.\n *\n * Both vectors are assumed to be unit length.\n *\n * @param {quat} out the receiving quaternion.\n * @param {ReadonlyVec3} a the initial vector\n * @param {ReadonlyVec3} b the destination vector\n * @returns {quat} out\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\n * Performs a spherical linear interpolation with two control points\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {ReadonlyQuat} c the third operand\n * @param {ReadonlyQuat} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\n * Sets the specified quaternion with values corresponding to the given\n * axes. Each axis is a vec3 and is expected to be unit length and\n * perpendicular to all other specified axes.\n *\n * @param {ReadonlyVec3} view the vector representing the viewing direction\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\n * @param {ReadonlyVec3} up the vector representing the local \"up\" direction\n * @returns {quat} out\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\n * Math.round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec3} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec3.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\n * Math.round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec4} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec4.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","{\n \"name\": \"gsots3d\",\n \"version\": \"0.0.5-alpha.10\",\n \"description\": \"Getting S**t On The Screen in 3D. A library for doing 3D graphics in the browser.\",\n \"author\": \"Ben Coleman\",\n \"license\": \"MIT\",\n \"homepage\": \"https://code.benco.io/gsots3d/docs\",\n \"type\": \"module\",\n \"publishConfig\": {\n \"@benc-uk:registry\": \"https://npm.pkg.github.com\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/benc-uk/gsots3d.git\"\n },\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./parsers\": \"./dist/parsers/index.js\"\n },\n \"browser\": {\n \".\": \"./dist-single/gsots3d.js\"\n },\n \"files\": [\n \"dist/\",\n \"readme.md\"\n ],\n \"keywords\": [\n \"webgl\",\n \"graphics\",\n \"3d\",\n \"twgl\",\n \"typescript\"\n ],\n \"scripts\": {\n \"lint\": \"eslint --ext .ts src && prettier --check src && prettier --check shaders\",\n \"lint-fix\": \"eslint --ext .ts src --fix && prettier --write src && prettier --write shaders\",\n \"check\": \"tsc\",\n \"build\": \"tsc && tsup\",\n \"watch\": \"tsc && npm run build && run-when-changed --watch 'src/**' --watch 'shaders/**' --exec 'npm run build'\",\n \"build-single\": \"tsc && tsup --config tsup.config-single.js\",\n \"watch-single\": \"tsc && npm run build-single && run-when-changed --watch 'src/**' --watch 'shaders/**' --exec 'npm run build-single'\",\n \"clean\": \"rm -rf dist docs dist-single\",\n \"docs\": \"typedoc --out docs --gitRevision main ./src/\",\n \"examples\": \"vite --port 3000 --host 0.0.0.0 ./examples/\"\n },\n \"devDependencies\": {\n \"@typescript-eslint/eslint-plugin\": \"^7.0.2\",\n \"@typescript-eslint/parser\": \"^7.0.2\",\n \"esbuild-plugin-glsl\": \"^1.2.2\",\n \"eslint\": \"^8.57.0\",\n \"prettier\": \"^3.2.5\",\n \"prettier-plugin-glsl\": \"^0.1.3\",\n \"run-when-changed\": \"^2.1.0\",\n \"tsup\": \"^8.0.2\",\n \"typedoc\": \"^0.25.8\",\n \"typescript\": \"^5.3.3\",\n \"vite\": \"^5.1.4\"\n },\n \"dependencies\": {\n \"cannon-es\": \"^0.20.0\",\n \"gl-matrix\": \"^3.4.3\",\n \"loglevel\": \"^1.9.1\",\n \"twgl.js\": \"^5.5.3\"\n }\n}\n","/**\n * Records what objects are colliding with each other\n */\nclass ObjectCollisionMatrix {\n /**\n * The matrix storage.\n */\n\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n this.matrix = {};\n }\n /**\n * get\n */\n\n\n get(bi, bj) {\n let {\n id: i\n } = bi;\n let {\n id: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return `${i}-${j}` in this.matrix;\n }\n /**\n * set\n */\n\n\n set(bi, bj, value) {\n let {\n id: i\n } = bi;\n let {\n id: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n if (value) {\n this.matrix[`${i}-${j}`] = true;\n } else {\n delete this.matrix[`${i}-${j}`];\n }\n }\n /**\n * Empty the matrix\n */\n\n\n reset() {\n this.matrix = {};\n }\n /**\n * Set max number of objects\n */\n\n\n setNumObjects(n) {}\n\n}\n\n/**\n * A 3x3 matrix.\n * Authored by {@link http://github.com/schteppe/ schteppe}\n */\nclass Mat3 {\n /**\n * A vector of length 9, containing all matrix elements.\n */\n\n /**\n * @param elements A vector of length 9, containing all matrix elements.\n */\n constructor(elements) {\n if (elements === void 0) {\n elements = [0, 0, 0, 0, 0, 0, 0, 0, 0];\n }\n\n this.elements = elements;\n }\n /**\n * Sets the matrix to identity\n * @todo Should perhaps be renamed to `setIdentity()` to be more clear.\n * @todo Create another function that immediately creates an identity matrix eg. `eye()`\n */\n\n\n identity() {\n const e = this.elements;\n e[0] = 1;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 1;\n e[5] = 0;\n e[6] = 0;\n e[7] = 0;\n e[8] = 1;\n }\n /**\n * Set all elements to zero\n */\n\n\n setZero() {\n const e = this.elements;\n e[0] = 0;\n e[1] = 0;\n e[2] = 0;\n e[3] = 0;\n e[4] = 0;\n e[5] = 0;\n e[6] = 0;\n e[7] = 0;\n e[8] = 0;\n }\n /**\n * Sets the matrix diagonal elements from a Vec3\n */\n\n\n setTrace(vector) {\n const e = this.elements;\n e[0] = vector.x;\n e[4] = vector.y;\n e[8] = vector.z;\n }\n /**\n * Gets the matrix diagonal elements\n */\n\n\n getTrace(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const e = this.elements;\n target.x = e[0];\n target.y = e[4];\n target.z = e[8];\n return target;\n }\n /**\n * Matrix-Vector multiplication\n * @param v The vector to multiply with\n * @param target Optional, target to save the result in.\n */\n\n\n vmult(v, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const e = this.elements;\n const x = v.x;\n const y = v.y;\n const z = v.z;\n target.x = e[0] * x + e[1] * y + e[2] * z;\n target.y = e[3] * x + e[4] * y + e[5] * z;\n target.z = e[6] * x + e[7] * y + e[8] * z;\n return target;\n }\n /**\n * Matrix-scalar multiplication\n */\n\n\n smult(s) {\n for (let i = 0; i < this.elements.length; i++) {\n this.elements[i] *= s;\n }\n }\n /**\n * Matrix multiplication\n * @param matrix Matrix to multiply with from left side.\n */\n\n\n mmult(matrix, target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const A = this.elements;\n const B = matrix.elements;\n const T = target.elements;\n const a11 = A[0],\n a12 = A[1],\n a13 = A[2],\n a21 = A[3],\n a22 = A[4],\n a23 = A[5],\n a31 = A[6],\n a32 = A[7],\n a33 = A[8];\n const b11 = B[0],\n b12 = B[1],\n b13 = B[2],\n b21 = B[3],\n b22 = B[4],\n b23 = B[5],\n b31 = B[6],\n b32 = B[7],\n b33 = B[8];\n T[0] = a11 * b11 + a12 * b21 + a13 * b31;\n T[1] = a11 * b12 + a12 * b22 + a13 * b32;\n T[2] = a11 * b13 + a12 * b23 + a13 * b33;\n T[3] = a21 * b11 + a22 * b21 + a23 * b31;\n T[4] = a21 * b12 + a22 * b22 + a23 * b32;\n T[5] = a21 * b13 + a22 * b23 + a23 * b33;\n T[6] = a31 * b11 + a32 * b21 + a33 * b31;\n T[7] = a31 * b12 + a32 * b22 + a33 * b32;\n T[8] = a31 * b13 + a32 * b23 + a33 * b33;\n return target;\n }\n /**\n * Scale each column of the matrix\n */\n\n\n scale(vector, target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const e = this.elements;\n const t = target.elements;\n\n for (let i = 0; i !== 3; i++) {\n t[3 * i + 0] = vector.x * e[3 * i + 0];\n t[3 * i + 1] = vector.y * e[3 * i + 1];\n t[3 * i + 2] = vector.z * e[3 * i + 2];\n }\n\n return target;\n }\n /**\n * Solve Ax=b\n * @param b The right hand side\n * @param target Optional. Target vector to save in.\n * @return The solution x\n * @todo should reuse arrays\n */\n\n\n solve(b, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n // Construct equations\n const nr = 3; // num rows\n\n const nc = 4; // num cols\n\n const eqns = [];\n let i;\n let j;\n\n for (i = 0; i < nr * nc; i++) {\n eqns.push(0);\n }\n\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n eqns[i + nc * j] = this.elements[i + 3 * j];\n }\n }\n\n eqns[3 + 4 * 0] = b.x;\n eqns[3 + 4 * 1] = b.y;\n eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination\n\n let n = 3;\n const k = n;\n let np;\n const kp = 4; // num rows\n\n let p;\n\n do {\n i = k - n;\n\n if (eqns[i + nc * i] === 0) {\n // the pivot is null, swap lines\n for (j = i + 1; j < k; j++) {\n if (eqns[i + nc * j] !== 0) {\n np = kp;\n\n do {\n // do ligne( i ) = ligne( i ) + ligne( k )\n p = kp - np;\n eqns[p + nc * i] += eqns[p + nc * j];\n } while (--np);\n\n break;\n }\n }\n }\n\n if (eqns[i + nc * i] !== 0) {\n for (j = i + 1; j < k; j++) {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = kp;\n\n do {\n // do ligne( k ) = ligne( k ) - multiplier * ligne( i )\n p = kp - np;\n eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n }\n }\n } while (--n); // Get the solution\n\n\n target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];\n target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];\n target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];\n\n if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {\n throw `Could not solve equation! Got x=[${target.toString()}], b=[${b.toString()}], A=[${this.toString()}]`;\n }\n\n return target;\n }\n /**\n * Get an element in the matrix by index. Index starts at 0, not 1!!!\n * @param value If provided, the matrix element will be set to this value.\n */\n\n\n e(row, column, value) {\n if (value === undefined) {\n return this.elements[column + 3 * row];\n } else {\n // Set value\n this.elements[column + 3 * row] = value;\n }\n }\n /**\n * Copy another matrix into this matrix object.\n */\n\n\n copy(matrix) {\n for (let i = 0; i < matrix.elements.length; i++) {\n this.elements[i] = matrix.elements[i];\n }\n\n return this;\n }\n /**\n * Returns a string representation of the matrix.\n */\n\n\n toString() {\n let r = '';\n const sep = ',';\n\n for (let i = 0; i < 9; i++) {\n r += this.elements[i] + sep;\n }\n\n return r;\n }\n /**\n * reverse the matrix\n * @param target Target matrix to save in.\n * @return The solution x\n */\n\n\n reverse(target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n // Construct equations\n const nr = 3; // num rows\n\n const nc = 6; // num cols\n\n const eqns = reverse_eqns;\n let i;\n let j;\n\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n eqns[i + nc * j] = this.elements[i + 3 * j];\n }\n }\n\n eqns[3 + 6 * 0] = 1;\n eqns[3 + 6 * 1] = 0;\n eqns[3 + 6 * 2] = 0;\n eqns[4 + 6 * 0] = 0;\n eqns[4 + 6 * 1] = 1;\n eqns[4 + 6 * 2] = 0;\n eqns[5 + 6 * 0] = 0;\n eqns[5 + 6 * 1] = 0;\n eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination\n\n let n = 3;\n const k = n;\n let np;\n const kp = nc; // num rows\n\n let p;\n\n do {\n i = k - n;\n\n if (eqns[i + nc * i] === 0) {\n // the pivot is null, swap lines\n for (j = i + 1; j < k; j++) {\n if (eqns[i + nc * j] !== 0) {\n np = kp;\n\n do {\n // do line( i ) = line( i ) + line( k )\n p = kp - np;\n eqns[p + nc * i] += eqns[p + nc * j];\n } while (--np);\n\n break;\n }\n }\n }\n\n if (eqns[i + nc * i] !== 0) {\n for (j = i + 1; j < k; j++) {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = kp;\n\n do {\n // do line( k ) = line( k ) - multiplier * line( i )\n p = kp - np;\n eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n }\n }\n } while (--n); // eliminate the upper left triangle of the matrix\n\n\n i = 2;\n\n do {\n j = i - 1;\n\n do {\n const multiplier = eqns[i + nc * j] / eqns[i + nc * i];\n np = nc;\n\n do {\n p = nc - np;\n eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;\n } while (--np);\n } while (j--);\n } while (--i); // operations on the diagonal\n\n\n i = 2;\n\n do {\n const multiplier = 1 / eqns[i + nc * i];\n np = nc;\n\n do {\n p = nc - np;\n eqns[p + nc * i] = eqns[p + nc * i] * multiplier;\n } while (--np);\n } while (i--);\n\n i = 2;\n\n do {\n j = 2;\n\n do {\n p = eqns[nr + j + nc * i];\n\n if (isNaN(p) || p === Infinity) {\n throw `Could not reverse! A=[${this.toString()}]`;\n }\n\n target.e(i, j, p);\n } while (j--);\n } while (i--);\n\n return target;\n }\n /**\n * Set the matrix from a quaterion\n */\n\n\n setRotationFromQuaternion(q) {\n const x = q.x;\n const y = q.y;\n const z = q.z;\n const w = q.w;\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const e = this.elements;\n e[3 * 0 + 0] = 1 - (yy + zz);\n e[3 * 0 + 1] = xy - wz;\n e[3 * 0 + 2] = xz + wy;\n e[3 * 1 + 0] = xy + wz;\n e[3 * 1 + 1] = 1 - (xx + zz);\n e[3 * 1 + 2] = yz - wx;\n e[3 * 2 + 0] = xz - wy;\n e[3 * 2 + 1] = yz + wx;\n e[3 * 2 + 2] = 1 - (xx + yy);\n return this;\n }\n /**\n * Transpose the matrix\n * @param target Optional. Where to store the result.\n * @return The target Mat3, or a new Mat3 if target was omitted.\n */\n\n\n transpose(target) {\n if (target === void 0) {\n target = new Mat3();\n }\n\n const M = this.elements;\n const T = target.elements;\n let tmp; //Set diagonals\n\n T[0] = M[0];\n T[4] = M[4];\n T[8] = M[8];\n tmp = M[1];\n T[1] = M[3];\n T[3] = tmp;\n tmp = M[2];\n T[2] = M[6];\n T[6] = tmp;\n tmp = M[5];\n T[5] = M[7];\n T[7] = tmp;\n return target;\n }\n\n}\nconst reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n/**\n * 3-dimensional vector\n * @example\n * const v = new Vec3(1, 2, 3)\n * console.log('x=' + v.x) // x=1\n */\n\nclass Vec3 {\n constructor(x, y, z) {\n if (x === void 0) {\n x = 0.0;\n }\n\n if (y === void 0) {\n y = 0.0;\n }\n\n if (z === void 0) {\n z = 0.0;\n }\n\n this.x = x;\n this.y = y;\n this.z = z;\n }\n /**\n * Vector cross product\n * @param target Optional target to save in.\n */\n\n\n cross(vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const vx = vector.x;\n const vy = vector.y;\n const vz = vector.z;\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = y * vz - z * vy;\n target.y = z * vx - x * vz;\n target.z = x * vy - y * vx;\n return target;\n }\n /**\n * Set the vectors' 3 elements\n */\n\n\n set(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n /**\n * Set all components of the vector to zero.\n */\n\n\n setZero() {\n this.x = this.y = this.z = 0;\n }\n /**\n * Vector addition\n */\n\n\n vadd(vector, target) {\n if (target) {\n target.x = vector.x + this.x;\n target.y = vector.y + this.y;\n target.z = vector.z + this.z;\n } else {\n return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);\n }\n }\n /**\n * Vector subtraction\n * @param target Optional target to save in.\n */\n\n\n vsub(vector, target) {\n if (target) {\n target.x = this.x - vector.x;\n target.y = this.y - vector.y;\n target.z = this.z - vector.z;\n } else {\n return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);\n }\n }\n /**\n * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c\n *\n * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}\n */\n\n\n crossmat() {\n return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);\n }\n /**\n * Normalize the vector. Note that this changes the values in the vector.\n * @return Returns the norm of the vector\n */\n\n\n normalize() {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const n = Math.sqrt(x * x + y * y + z * z);\n\n if (n > 0.0) {\n const invN = 1 / n;\n this.x *= invN;\n this.y *= invN;\n this.z *= invN;\n } else {\n // Make something up\n this.x = 0;\n this.y = 0;\n this.z = 0;\n }\n\n return n;\n }\n /**\n * Get the version of this vector that is of length 1.\n * @param target Optional target to save in\n * @return Returns the unit vector\n */\n\n\n unit(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n let ninv = Math.sqrt(x * x + y * y + z * z);\n\n if (ninv > 0.0) {\n ninv = 1.0 / ninv;\n target.x = x * ninv;\n target.y = y * ninv;\n target.z = z * ninv;\n } else {\n target.x = 1;\n target.y = 0;\n target.z = 0;\n }\n\n return target;\n }\n /**\n * Get the length of the vector\n */\n\n\n length() {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n return Math.sqrt(x * x + y * y + z * z);\n }\n /**\n * Get the squared length of the vector.\n */\n\n\n lengthSquared() {\n return this.dot(this);\n }\n /**\n * Get distance from this point to another point\n */\n\n\n distanceTo(p) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const px = p.x;\n const py = p.y;\n const pz = p.z;\n return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));\n }\n /**\n * Get squared distance from this point to another point\n */\n\n\n distanceSquared(p) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const px = p.x;\n const py = p.y;\n const pz = p.z;\n return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);\n }\n /**\n * Multiply all the components of the vector with a scalar.\n * @param target The vector to save the result in.\n */\n\n\n scale(scalar, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = scalar * x;\n target.y = scalar * y;\n target.z = scalar * z;\n return target;\n }\n /**\n * Multiply the vector with an other vector, component-wise.\n * @param target The vector to save the result in.\n */\n\n\n vmul(vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = vector.x * this.x;\n target.y = vector.y * this.y;\n target.z = vector.z * this.z;\n return target;\n }\n /**\n * Scale a vector and add it to this vector. Save the result in \"target\". (target = this + vector * scalar)\n * @param target The vector to save the result in.\n */\n\n\n addScaledVector(scalar, vector, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = this.x + scalar * vector.x;\n target.y = this.y + scalar * vector.y;\n target.z = this.z + scalar * vector.z;\n return target;\n }\n /**\n * Calculate dot product\n * @param vector\n */\n\n\n dot(vector) {\n return this.x * vector.x + this.y * vector.y + this.z * vector.z;\n }\n\n isZero() {\n return this.x === 0 && this.y === 0 && this.z === 0;\n }\n /**\n * Make the vector point in the opposite direction.\n * @param target Optional target to save in\n */\n\n\n negate(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.x = -this.x;\n target.y = -this.y;\n target.z = -this.z;\n return target;\n }\n /**\n * Compute two artificial tangents to the vector\n * @param t1 Vector object to save the first tangent in\n * @param t2 Vector object to save the second tangent in\n */\n\n\n tangents(t1, t2) {\n const norm = this.length();\n\n if (norm > 0.0) {\n const n = Vec3_tangents_n;\n const inorm = 1 / norm;\n n.set(this.x * inorm, this.y * inorm, this.z * inorm);\n const randVec = Vec3_tangents_randVec;\n\n if (Math.abs(n.x) < 0.9) {\n randVec.set(1, 0, 0);\n n.cross(randVec, t1);\n } else {\n randVec.set(0, 1, 0);\n n.cross(randVec, t1);\n }\n\n n.cross(t1, t2);\n } else {\n // The normal length is zero, make something up\n t1.set(1, 0, 0);\n t2.set(0, 1, 0);\n }\n }\n /**\n * Converts to a more readable format\n */\n\n\n toString() {\n return `${this.x},${this.y},${this.z}`;\n }\n /**\n * Converts to an array\n */\n\n\n toArray() {\n return [this.x, this.y, this.z];\n }\n /**\n * Copies value of source to this vector.\n */\n\n\n copy(vector) {\n this.x = vector.x;\n this.y = vector.y;\n this.z = vector.z;\n return this;\n }\n /**\n * Do a linear interpolation between two vectors\n * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.\n */\n\n\n lerp(vector, t, target) {\n const x = this.x;\n const y = this.y;\n const z = this.z;\n target.x = x + (vector.x - x) * t;\n target.y = y + (vector.y - y) * t;\n target.z = z + (vector.z - z) * t;\n }\n /**\n * Check if a vector equals is almost equal to another one.\n */\n\n\n almostEquals(vector, precision) {\n if (precision === void 0) {\n precision = 1e-6;\n }\n\n if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {\n return false;\n }\n\n return true;\n }\n /**\n * Check if a vector is almost zero\n */\n\n\n almostZero(precision) {\n if (precision === void 0) {\n precision = 1e-6;\n }\n\n if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {\n return false;\n }\n\n return true;\n }\n /**\n * Check if the vector is anti-parallel to another vector.\n * @param precision Set to zero for exact comparisons\n */\n\n\n isAntiparallelTo(vector, precision) {\n this.negate(antip_neg);\n return antip_neg.almostEquals(vector, precision);\n }\n /**\n * Clone the vector\n */\n\n\n clone() {\n return new Vec3(this.x, this.y, this.z);\n }\n\n}\nVec3.ZERO = new Vec3(0, 0, 0);\nVec3.UNIT_X = new Vec3(1, 0, 0);\nVec3.UNIT_Y = new Vec3(0, 1, 0);\nVec3.UNIT_Z = new Vec3(0, 0, 1);\nconst Vec3_tangents_n = new Vec3();\nconst Vec3_tangents_randVec = new Vec3();\nconst antip_neg = new Vec3();\n\n/**\n * Axis aligned bounding box class.\n */\nclass AABB {\n /**\n * The lower bound of the bounding box\n */\n\n /**\n * The upper bound of the bounding box\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.lowerBound = new Vec3();\n this.upperBound = new Vec3();\n\n if (options.lowerBound) {\n this.lowerBound.copy(options.lowerBound);\n }\n\n if (options.upperBound) {\n this.upperBound.copy(options.upperBound);\n }\n }\n /**\n * Set the AABB bounds from a set of points.\n * @param points An array of Vec3's.\n * @return The self object\n */\n\n\n setFromPoints(points, position, quaternion, skinSize) {\n const l = this.lowerBound;\n const u = this.upperBound;\n const q = quaternion; // Set to the first point\n\n l.copy(points[0]);\n\n if (q) {\n q.vmult(l, l);\n }\n\n u.copy(l);\n\n for (let i = 1; i < points.length; i++) {\n let p = points[i];\n\n if (q) {\n q.vmult(p, tmp$1);\n p = tmp$1;\n }\n\n if (p.x > u.x) {\n u.x = p.x;\n }\n\n if (p.x < l.x) {\n l.x = p.x;\n }\n\n if (p.y > u.y) {\n u.y = p.y;\n }\n\n if (p.y < l.y) {\n l.y = p.y;\n }\n\n if (p.z > u.z) {\n u.z = p.z;\n }\n\n if (p.z < l.z) {\n l.z = p.z;\n }\n } // Add offset\n\n\n if (position) {\n position.vadd(l, l);\n position.vadd(u, u);\n }\n\n if (skinSize) {\n l.x -= skinSize;\n l.y -= skinSize;\n l.z -= skinSize;\n u.x += skinSize;\n u.y += skinSize;\n u.z += skinSize;\n }\n\n return this;\n }\n /**\n * Copy bounds from an AABB to this AABB\n * @param aabb Source to copy from\n * @return The this object, for chainability\n */\n\n\n copy(aabb) {\n this.lowerBound.copy(aabb.lowerBound);\n this.upperBound.copy(aabb.upperBound);\n return this;\n }\n /**\n * Clone an AABB\n */\n\n\n clone() {\n return new AABB().copy(this);\n }\n /**\n * Extend this AABB so that it covers the given AABB too.\n */\n\n\n extend(aabb) {\n this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);\n this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);\n this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);\n this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);\n this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);\n this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);\n }\n /**\n * Returns true if the given AABB overlaps this AABB.\n */\n\n\n overlaps(aabb) {\n const l1 = this.lowerBound;\n const u1 = this.upperBound;\n const l2 = aabb.lowerBound;\n const u2 = aabb.upperBound; // l2 u2\n // |---------|\n // |--------|\n // l1 u1\n\n const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;\n const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;\n const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;\n return overlapsX && overlapsY && overlapsZ;\n } // Mostly for debugging\n\n\n volume() {\n const l = this.lowerBound;\n const u = this.upperBound;\n return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);\n }\n /**\n * Returns true if the given AABB is fully contained in this AABB.\n */\n\n\n contains(aabb) {\n const l1 = this.lowerBound;\n const u1 = this.upperBound;\n const l2 = aabb.lowerBound;\n const u2 = aabb.upperBound; // l2 u2\n // |---------|\n // |---------------|\n // l1 u1\n\n return l1.x <= l2.x && u1.x >= u2.x && l1.y <= l2.y && u1.y >= u2.y && l1.z <= l2.z && u1.z >= u2.z;\n }\n\n getCorners(a, b, c, d, e, f, g, h) {\n const l = this.lowerBound;\n const u = this.upperBound;\n a.copy(l);\n b.set(u.x, l.y, l.z);\n c.set(u.x, u.y, l.z);\n d.set(l.x, u.y, u.z);\n e.set(u.x, l.y, u.z);\n f.set(l.x, u.y, l.z);\n g.set(l.x, l.y, u.z);\n h.copy(u);\n }\n /**\n * Get the representation of an AABB in another frame.\n * @return The \"target\" AABB object.\n */\n\n\n toLocalFrame(frame, target) {\n const corners = transformIntoFrame_corners;\n const a = corners[0];\n const b = corners[1];\n const c = corners[2];\n const d = corners[3];\n const e = corners[4];\n const f = corners[5];\n const g = corners[6];\n const h = corners[7]; // Get corners in current frame\n\n this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame\n\n for (let i = 0; i !== 8; i++) {\n const corner = corners[i];\n frame.pointToLocal(corner, corner);\n }\n\n return target.setFromPoints(corners);\n }\n /**\n * Get the representation of an AABB in the global frame.\n * @return The \"target\" AABB object.\n */\n\n\n toWorldFrame(frame, target) {\n const corners = transformIntoFrame_corners;\n const a = corners[0];\n const b = corners[1];\n const c = corners[2];\n const d = corners[3];\n const e = corners[4];\n const f = corners[5];\n const g = corners[6];\n const h = corners[7]; // Get corners in current frame\n\n this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame\n\n for (let i = 0; i !== 8; i++) {\n const corner = corners[i];\n frame.pointToWorld(corner, corner);\n }\n\n return target.setFromPoints(corners);\n }\n /**\n * Check if the AABB is hit by a ray.\n */\n\n\n overlapsRay(ray) {\n const {\n direction,\n from\n } = ray; // const t = 0\n // ray.direction is unit direction vector of ray\n\n const dirFracX = 1 / direction.x;\n const dirFracY = 1 / direction.y;\n const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner\n\n const t1 = (this.lowerBound.x - from.x) * dirFracX;\n const t2 = (this.upperBound.x - from.x) * dirFracX;\n const t3 = (this.lowerBound.y - from.y) * dirFracY;\n const t4 = (this.upperBound.y - from.y) * dirFracY;\n const t5 = (this.lowerBound.z - from.z) * dirFracZ;\n const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));\n // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));\n\n const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));\n const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us\n\n if (tmax < 0) {\n //t = tmax;\n return false;\n } // if tmin > tmax, ray doesn't intersect AABB\n\n\n if (tmin > tmax) {\n //t = tmax;\n return false;\n }\n\n return true;\n }\n\n}\nconst tmp$1 = new Vec3();\nconst transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\n\n/**\n * Collision \"matrix\".\n * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step\n */\nclass ArrayCollisionMatrix {\n /**\n * The matrix storage.\n */\n constructor() {\n this.matrix = [];\n }\n /**\n * Get an element\n */\n\n\n get(bi, bj) {\n let {\n index: i\n } = bi;\n let {\n index: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return this.matrix[(i * (i + 1) >> 1) + j - 1];\n }\n /**\n * Set an element\n */\n\n\n set(bi, bj, value) {\n let {\n index: i\n } = bi;\n let {\n index: j\n } = bj;\n\n if (j > i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;\n }\n /**\n * Sets all elements to zero\n */\n\n\n reset() {\n for (let i = 0, l = this.matrix.length; i !== l; i++) {\n this.matrix[i] = 0;\n }\n }\n /**\n * Sets the max number of objects\n */\n\n\n setNumObjects(n) {\n this.matrix.length = n * (n - 1) >> 1;\n }\n\n}\n\n/**\n * Base class for objects that dispatches events.\n */\nclass EventTarget {\n /**\n * Add an event listener\n * @return The self object, for chainability.\n */\n addEventListener(type, listener) {\n if (this._listeners === undefined) {\n this._listeners = {};\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] === undefined) {\n listeners[type] = [];\n }\n\n if (!listeners[type].includes(listener)) {\n listeners[type].push(listener);\n }\n\n return this;\n }\n /**\n * Check if an event listener is added\n */\n\n\n hasEventListener(type, listener) {\n if (this._listeners === undefined) {\n return false;\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] !== undefined && listeners[type].includes(listener)) {\n return true;\n }\n\n return false;\n }\n /**\n * Check if any event listener of the given type is added\n */\n\n\n hasAnyEventListener(type) {\n if (this._listeners === undefined) {\n return false;\n }\n\n const listeners = this._listeners;\n return listeners[type] !== undefined;\n }\n /**\n * Remove an event listener\n * @return The self object, for chainability.\n */\n\n\n removeEventListener(type, listener) {\n if (this._listeners === undefined) {\n return this;\n }\n\n const listeners = this._listeners;\n\n if (listeners[type] === undefined) {\n return this;\n }\n\n const index = listeners[type].indexOf(listener);\n\n if (index !== -1) {\n listeners[type].splice(index, 1);\n }\n\n return this;\n }\n /**\n * Emit an event.\n * @return The self object, for chainability.\n */\n\n\n dispatchEvent(event) {\n if (this._listeners === undefined) {\n return this;\n }\n\n const listeners = this._listeners;\n const listenerArray = listeners[event.type];\n\n if (listenerArray !== undefined) {\n event.target = this;\n\n for (let i = 0, l = listenerArray.length; i < l; i++) {\n listenerArray[i].call(this, event);\n }\n }\n\n return this;\n }\n\n}\n\n/**\n * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.\n * @param x Multiplier of the imaginary basis vector i.\n * @param y Multiplier of the imaginary basis vector j.\n * @param z Multiplier of the imaginary basis vector k.\n * @param w Multiplier of the real part.\n * @see http://en.wikipedia.org/wiki/Quaternion\n */\n\nclass Quaternion {\n constructor(x, y, z, w) {\n if (x === void 0) {\n x = 0;\n }\n\n if (y === void 0) {\n y = 0;\n }\n\n if (z === void 0) {\n z = 0;\n }\n\n if (w === void 0) {\n w = 1;\n }\n\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n }\n /**\n * Set the value of the quaternion.\n */\n\n\n set(x, y, z, w) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.w = w;\n return this;\n }\n /**\n * Convert to a readable format\n * @return \"x,y,z,w\"\n */\n\n\n toString() {\n return `${this.x},${this.y},${this.z},${this.w}`;\n }\n /**\n * Convert to an Array\n * @return [x, y, z, w]\n */\n\n\n toArray() {\n return [this.x, this.y, this.z, this.w];\n }\n /**\n * Set the quaternion components given an axis and an angle in radians.\n */\n\n\n setFromAxisAngle(vector, angle) {\n const s = Math.sin(angle * 0.5);\n this.x = vector.x * s;\n this.y = vector.y * s;\n this.z = vector.z * s;\n this.w = Math.cos(angle * 0.5);\n return this;\n }\n /**\n * Converts the quaternion to [ axis, angle ] representation.\n * @param targetAxis A vector object to reuse for storing the axis.\n * @return An array, first element is the axis and the second is the angle in radians.\n */\n\n\n toAxisAngle(targetAxis) {\n if (targetAxis === void 0) {\n targetAxis = new Vec3();\n }\n\n this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised\n\n const angle = 2 * Math.acos(this.w);\n const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.\n\n if (s < 0.001) {\n // test to avoid divide by zero, s is always positive due to sqrt\n // if s close to zero then direction of axis not important\n targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;\n\n targetAxis.y = this.y;\n targetAxis.z = this.z;\n } else {\n targetAxis.x = this.x / s; // normalise axis\n\n targetAxis.y = this.y / s;\n targetAxis.z = this.z / s;\n }\n\n return [targetAxis, angle];\n }\n /**\n * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.\n */\n\n\n setFromVectors(u, v) {\n if (u.isAntiparallelTo(v)) {\n const t1 = sfv_t1;\n const t2 = sfv_t2;\n u.tangents(t1, t2);\n this.setFromAxisAngle(t1, Math.PI);\n } else {\n const a = u.cross(v);\n this.x = a.x;\n this.y = a.y;\n this.z = a.z;\n this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);\n this.normalize();\n }\n\n return this;\n }\n /**\n * Multiply the quaternion with an other quaternion.\n */\n\n\n mult(quat, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = this.x;\n const ay = this.y;\n const az = this.z;\n const aw = this.w;\n const bx = quat.x;\n const by = quat.y;\n const bz = quat.z;\n const bw = quat.w;\n target.x = ax * bw + aw * bx + ay * bz - az * by;\n target.y = ay * bw + aw * by + az * bx - ax * bz;\n target.z = az * bw + aw * bz + ax * by - ay * bx;\n target.w = aw * bw - ax * bx - ay * by - az * bz;\n return target;\n }\n /**\n * Get the inverse quaternion rotation.\n */\n\n\n inverse(target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const w = this.w;\n this.conjugate(target);\n const inorm2 = 1 / (x * x + y * y + z * z + w * w);\n target.x *= inorm2;\n target.y *= inorm2;\n target.z *= inorm2;\n target.w *= inorm2;\n return target;\n }\n /**\n * Get the quaternion conjugate\n */\n\n\n conjugate(target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n target.x = -this.x;\n target.y = -this.y;\n target.z = -this.z;\n target.w = this.w;\n return target;\n }\n /**\n * Normalize the quaternion. Note that this changes the values of the quaternion.\n */\n\n\n normalize() {\n let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);\n\n if (l === 0) {\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n } else {\n l = 1 / l;\n this.x *= l;\n this.y *= l;\n this.z *= l;\n this.w *= l;\n }\n\n return this;\n }\n /**\n * Approximation of quaternion normalization. Works best when quat is already almost-normalized.\n * @author unphased, https://github.com/unphased\n */\n\n\n normalizeFast() {\n const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;\n\n if (f === 0) {\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n } else {\n this.x *= f;\n this.y *= f;\n this.z *= f;\n this.w *= f;\n }\n\n return this;\n }\n /**\n * Multiply the quaternion by a vector\n */\n\n\n vmult(v, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const x = v.x;\n const y = v.y;\n const z = v.z;\n const qx = this.x;\n const qy = this.y;\n const qz = this.z;\n const qw = this.w; // q*v\n\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = -qx * x - qy * y - qz * z;\n target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n return target;\n }\n /**\n * Copies value of source to this quaternion.\n * @return this\n */\n\n\n copy(quat) {\n this.x = quat.x;\n this.y = quat.y;\n this.z = quat.z;\n this.w = quat.w;\n return this;\n }\n /**\n * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm\n * @param order Three-character string, defaults to \"YZX\"\n */\n\n\n toEuler(target, order) {\n if (order === void 0) {\n order = 'YZX';\n }\n\n let heading;\n let attitude;\n let bank;\n const x = this.x;\n const y = this.y;\n const z = this.z;\n const w = this.w;\n\n switch (order) {\n case 'YZX':\n const test = x * y + z * w;\n\n if (test > 0.499) {\n // singularity at north pole\n heading = 2 * Math.atan2(x, w);\n attitude = Math.PI / 2;\n bank = 0;\n }\n\n if (test < -0.499) {\n // singularity at south pole\n heading = -2 * Math.atan2(x, w);\n attitude = -Math.PI / 2;\n bank = 0;\n }\n\n if (heading === undefined) {\n const sqx = x * x;\n const sqy = y * y;\n const sqz = z * z;\n heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading\n\n attitude = Math.asin(2 * test); // attitude\n\n bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank\n }\n\n break;\n\n default:\n throw new Error(`Euler order ${order} not supported yet.`);\n }\n\n target.y = heading;\n target.z = attitude;\n target.x = bank;\n }\n /**\n * Set the quaternion components given Euler angle representation.\n *\n * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.\n *\n * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference\n */\n\n\n setFromEuler(x, y, z, order) {\n if (order === void 0) {\n order = 'XYZ';\n }\n\n const c1 = Math.cos(x / 2);\n const c2 = Math.cos(y / 2);\n const c3 = Math.cos(z / 2);\n const s1 = Math.sin(x / 2);\n const s2 = Math.sin(y / 2);\n const s3 = Math.sin(z / 2);\n\n if (order === 'XYZ') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'YXZ') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n } else if (order === 'ZXY') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'ZYX') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n } else if (order === 'YZX') {\n this.x = s1 * c2 * c3 + c1 * s2 * s3;\n this.y = c1 * s2 * c3 + s1 * c2 * s3;\n this.z = c1 * c2 * s3 - s1 * s2 * c3;\n this.w = c1 * c2 * c3 - s1 * s2 * s3;\n } else if (order === 'XZY') {\n this.x = s1 * c2 * c3 - c1 * s2 * s3;\n this.y = c1 * s2 * c3 - s1 * c2 * s3;\n this.z = c1 * c2 * s3 + s1 * s2 * c3;\n this.w = c1 * c2 * c3 + s1 * s2 * s3;\n }\n\n return this;\n }\n\n clone() {\n return new Quaternion(this.x, this.y, this.z, this.w);\n }\n /**\n * Performs a spherical linear interpolation between two quat\n *\n * @param toQuat second operand\n * @param t interpolation amount between the self quaternion and toQuat\n * @param target A quaternion to store the result in. If not provided, a new one will be created.\n * @returns {Quaternion} The \"target\" object\n */\n\n\n slerp(toQuat, t, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = this.x;\n const ay = this.y;\n const az = this.z;\n const aw = this.w;\n let bx = toQuat.x;\n let by = toQuat.y;\n let bz = toQuat.z;\n let bw = toQuat.w;\n let omega;\n let cosom;\n let sinom;\n let scale0;\n let scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > 0.000001) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n target.x = scale0 * ax + scale1 * bx;\n target.y = scale0 * ay + scale1 * by;\n target.z = scale0 * az + scale1 * bz;\n target.w = scale0 * aw + scale1 * bw;\n return target;\n }\n /**\n * Rotate an absolute orientation quaternion given an angular velocity and a time step.\n */\n\n\n integrate(angularVelocity, dt, angularFactor, target) {\n if (target === void 0) {\n target = new Quaternion();\n }\n\n const ax = angularVelocity.x * angularFactor.x,\n ay = angularVelocity.y * angularFactor.y,\n az = angularVelocity.z * angularFactor.z,\n bx = this.x,\n by = this.y,\n bz = this.z,\n bw = this.w;\n const half_dt = dt * 0.5;\n target.x += half_dt * (ax * bw + ay * bz - az * by);\n target.y += half_dt * (ay * bw + az * bx - ax * bz);\n target.z += half_dt * (az * bw + ax * by - ay * bx);\n target.w += half_dt * (-ax * bx - ay * by - az * bz);\n return target;\n }\n\n}\nconst sfv_t1 = new Vec3();\nconst sfv_t2 = new Vec3();\n\n/**\n * The available shape types.\n */\nconst SHAPE_TYPES = {\n /** SPHERE */\n SPHERE: 1,\n\n /** PLANE */\n PLANE: 2,\n\n /** BOX */\n BOX: 4,\n\n /** COMPOUND */\n COMPOUND: 8,\n\n /** CONVEXPOLYHEDRON */\n CONVEXPOLYHEDRON: 16,\n\n /** HEIGHTFIELD */\n HEIGHTFIELD: 32,\n\n /** PARTICLE */\n PARTICLE: 64,\n\n /** CYLINDER */\n CYLINDER: 128,\n\n /** TRIMESH */\n TRIMESH: 256\n};\n/**\n * ShapeType\n */\n\n/**\n * Base class for shapes\n */\nclass Shape {\n /**\n * Identifier of the Shape.\n */\n\n /**\n * The type of this shape. Must be set to an int > 0 by subclasses.\n */\n\n /**\n * The local bounding sphere radius of this shape.\n */\n\n /**\n * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.\n * @default true\n */\n\n /**\n * @default 1\n */\n\n /**\n * @default -1\n */\n\n /**\n * Optional material of the shape that regulates contact properties.\n */\n\n /**\n * The body to which the shape is added to.\n */\n\n /**\n * All the Shape types.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.id = Shape.idCounter++;\n this.type = options.type || 0;\n this.boundingSphereRadius = 0;\n this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;\n this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;\n this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;\n this.material = options.material ? options.material : null;\n this.body = null;\n }\n /**\n * Computes the bounding sphere radius.\n * The result is stored in the property `.boundingSphereRadius`\n */\n\n\n updateBoundingSphereRadius() {\n throw `computeBoundingSphereRadius() not implemented for shape type ${this.type}`;\n }\n /**\n * Get the volume of this shape\n */\n\n\n volume() {\n throw `volume() not implemented for shape type ${this.type}`;\n }\n /**\n * Calculates the inertia in the local frame for this shape.\n * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia\n */\n\n\n calculateLocalInertia(mass, target) {\n throw `calculateLocalInertia() not implemented for shape type ${this.type}`;\n }\n /**\n * @todo use abstract for these kind of methods\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n throw `calculateWorldAABB() not implemented for shape type ${this.type}`;\n }\n\n}\nShape.idCounter = 0;\nShape.types = SHAPE_TYPES;\n\n/**\n * Transformation utilities.\n */\nclass Transform {\n /**\n * position\n */\n\n /**\n * quaternion\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.position = new Vec3();\n this.quaternion = new Quaternion();\n\n if (options.position) {\n this.position.copy(options.position);\n }\n\n if (options.quaternion) {\n this.quaternion.copy(options.quaternion);\n }\n }\n /**\n * Get a global point in local transform coordinates.\n */\n\n\n pointToLocal(worldPoint, result) {\n return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);\n }\n /**\n * Get a local point in global transform coordinates.\n */\n\n\n pointToWorld(localPoint, result) {\n return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);\n }\n /**\n * vectorToWorldFrame\n */\n\n\n vectorToWorldFrame(localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * pointToLocalFrame\n */\n\n\n static pointToLocalFrame(position, quaternion, worldPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n worldPoint.vsub(position, result);\n quaternion.conjugate(tmpQuat$1);\n tmpQuat$1.vmult(result, result);\n return result;\n }\n /**\n * pointToWorldFrame\n */\n\n\n static pointToWorldFrame(position, quaternion, localPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.vmult(localPoint, result);\n result.vadd(position, result);\n return result;\n }\n /**\n * vectorToWorldFrame\n */\n\n\n static vectorToWorldFrame(quaternion, localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * vectorToLocalFrame\n */\n\n\n static vectorToLocalFrame(position, quaternion, worldVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n quaternion.w *= -1;\n quaternion.vmult(worldVector, result);\n quaternion.w *= -1;\n return result;\n }\n\n}\nconst tmpQuat$1 = new Quaternion();\n\n/**\n * A set of polygons describing a convex shape.\n *\n * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained\n * in the same 3D plane), instead these should be merged into one polygon.\n *\n * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)\n * @author schteppe / https://github.com/schteppe\n * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/\n *\n * @todo Move the clipping functions to ContactGenerator?\n * @todo Automatically merge coplanar polygons in constructor.\n * @example\n * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })\n * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })\n * world.addBody(convexBody)\n */\nclass ConvexPolyhedron extends Shape {\n /** vertices */\n\n /**\n * Array of integer arrays, indicating which vertices each face consists of\n */\n\n /** faceNormals */\n\n /** worldVertices */\n\n /** worldVerticesNeedsUpdate */\n\n /** worldFaceNormals */\n\n /** worldFaceNormalsNeedsUpdate */\n\n /**\n * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.\n */\n\n /** uniqueEdges */\n\n /**\n * @param vertices An array of Vec3's\n * @param faces Array of integer arrays, describing which vertices that is included in each face.\n */\n constructor(props) {\n if (props === void 0) {\n props = {};\n }\n\n const {\n vertices = [],\n faces = [],\n normals = [],\n axes,\n boundingSphereRadius\n } = props;\n super({\n type: Shape.types.CONVEXPOLYHEDRON\n });\n this.vertices = vertices;\n this.faces = faces;\n this.faceNormals = normals;\n\n if (this.faceNormals.length === 0) {\n this.computeNormals();\n }\n\n if (!boundingSphereRadius) {\n this.updateBoundingSphereRadius();\n } else {\n this.boundingSphereRadius = boundingSphereRadius;\n }\n\n this.worldVertices = []; // World transformed version of .vertices\n\n this.worldVerticesNeedsUpdate = true;\n this.worldFaceNormals = []; // World transformed version of .faceNormals\n\n this.worldFaceNormalsNeedsUpdate = true;\n this.uniqueAxes = axes ? axes.slice() : null;\n this.uniqueEdges = [];\n this.computeEdges();\n }\n /**\n * Computes uniqueEdges\n */\n\n\n computeEdges() {\n const faces = this.faces;\n const vertices = this.vertices;\n const edges = this.uniqueEdges;\n edges.length = 0;\n const edge = new Vec3();\n\n for (let i = 0; i !== faces.length; i++) {\n const face = faces[i];\n const numVertices = face.length;\n\n for (let j = 0; j !== numVertices; j++) {\n const k = (j + 1) % numVertices;\n vertices[face[j]].vsub(vertices[face[k]], edge);\n edge.normalize();\n let found = false;\n\n for (let p = 0; p !== edges.length; p++) {\n if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n edges.push(edge.clone());\n }\n }\n }\n }\n /**\n * Compute the normals of the faces.\n * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.\n */\n\n\n computeNormals() {\n this.faceNormals.length = this.faces.length; // Generate normals\n\n for (let i = 0; i < this.faces.length; i++) {\n // Check so all vertices exists for this face\n for (let j = 0; j < this.faces[i].length; j++) {\n if (!this.vertices[this.faces[i][j]]) {\n throw new Error(`Vertex ${this.faces[i][j]} not found!`);\n }\n }\n\n const n = this.faceNormals[i] || new Vec3();\n this.getFaceNormal(i, n);\n n.negate(n);\n this.faceNormals[i] = n;\n const vertex = this.vertices[this.faces[i][0]];\n\n if (n.dot(vertex) < 0) {\n console.error(`.faceNormals[${i}] = Vec3(${n.toString()}) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.`);\n\n for (let j = 0; j < this.faces[i].length; j++) {\n console.warn(`.vertices[${this.faces[i][j]}] = Vec3(${this.vertices[this.faces[i][j]].toString()})`);\n }\n }\n }\n }\n /**\n * Compute the normal of a face from its vertices\n */\n\n\n getFaceNormal(i, target) {\n const f = this.faces[i];\n const va = this.vertices[f[0]];\n const vb = this.vertices[f[1]];\n const vc = this.vertices[f[2]];\n ConvexPolyhedron.computeNormal(va, vb, vc, target);\n }\n /**\n * Get face normal given 3 vertices\n */\n\n\n static computeNormal(va, vb, vc, target) {\n const cb = new Vec3();\n const ab = new Vec3();\n vb.vsub(va, ab);\n vc.vsub(vb, cb);\n cb.cross(ab, target);\n\n if (!target.isZero()) {\n target.normalize();\n }\n }\n /**\n * @param minDist Clamp distance\n * @param result The an array of contact point objects, see clipFaceAgainstHull\n */\n\n\n clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {\n const WorldNormal = new Vec3();\n let closestFaceB = -1;\n let dmax = -Number.MAX_VALUE;\n\n for (let face = 0; face < hullB.faces.length; face++) {\n WorldNormal.copy(hullB.faceNormals[face]);\n quatB.vmult(WorldNormal, WorldNormal);\n const d = WorldNormal.dot(separatingNormal);\n\n if (d > dmax) {\n dmax = d;\n closestFaceB = face;\n }\n }\n\n const worldVertsB1 = [];\n\n for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {\n const b = hullB.vertices[hullB.faces[closestFaceB][i]];\n const worldb = new Vec3();\n worldb.copy(b);\n quatB.vmult(worldb, worldb);\n posB.vadd(worldb, worldb);\n worldVertsB1.push(worldb);\n }\n\n if (closestFaceB >= 0) {\n this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);\n }\n }\n /**\n * Find the separating axis between this hull and another\n * @param target The target vector to save the axis in\n * @return Returns false if a separation is found, else true\n */\n\n\n findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {\n const faceANormalWS3 = new Vec3();\n const Worldnormal1 = new Vec3();\n const deltaC = new Vec3();\n const worldEdge0 = new Vec3();\n const worldEdge1 = new Vec3();\n const Cross = new Vec3();\n let dmin = Number.MAX_VALUE;\n const hullA = this;\n\n if (!hullA.uniqueAxes) {\n const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA\n\n for (let i = 0; i < numFacesA; i++) {\n const fi = faceListA ? faceListA[i] : i; // Get world face normal\n\n faceANormalWS3.copy(hullA.faceNormals[fi]);\n quatA.vmult(faceANormalWS3, faceANormalWS3);\n const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(faceANormalWS3);\n }\n }\n } else {\n // Test unique axes\n for (let i = 0; i !== hullA.uniqueAxes.length; i++) {\n // Get world axis\n quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);\n const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(faceANormalWS3);\n }\n }\n }\n\n if (!hullB.uniqueAxes) {\n // Test face normals from hullB\n const numFacesB = faceListB ? faceListB.length : hullB.faces.length;\n\n for (let i = 0; i < numFacesB; i++) {\n const fi = faceListB ? faceListB[i] : i;\n Worldnormal1.copy(hullB.faceNormals[fi]);\n quatB.vmult(Worldnormal1, Worldnormal1);\n const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(Worldnormal1);\n }\n }\n } else {\n // Test unique axes in B\n for (let i = 0; i !== hullB.uniqueAxes.length; i++) {\n quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);\n const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);\n\n if (d === false) {\n return false;\n }\n\n if (d < dmin) {\n dmin = d;\n target.copy(Worldnormal1);\n }\n }\n } // Test edges\n\n\n for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {\n // Get world edge\n quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);\n\n for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {\n // Get world edge 2\n quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);\n worldEdge0.cross(worldEdge1, Cross);\n\n if (!Cross.almostZero()) {\n Cross.normalize();\n const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);\n\n if (dist === false) {\n return false;\n }\n\n if (dist < dmin) {\n dmin = dist;\n target.copy(Cross);\n }\n }\n }\n }\n\n posB.vsub(posA, deltaC);\n\n if (deltaC.dot(target) > 0.0) {\n target.negate(target);\n }\n\n return true;\n }\n /**\n * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.\n * @return The overlap depth, or FALSE if no penetration.\n */\n\n\n testSepAxis(axis, hullB, posA, quatA, posB, quatB) {\n const hullA = this;\n ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);\n ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);\n const maxA = maxminA[0];\n const minA = maxminA[1];\n const maxB = maxminB[0];\n const minB = maxminB[1];\n\n if (maxA < minB || maxB < minA) {\n return false; // Separated\n }\n\n const d0 = maxA - minB;\n const d1 = maxB - minA;\n const depth = d0 < d1 ? d0 : d1;\n return depth;\n }\n /**\n * calculateLocalInertia\n */\n\n\n calculateLocalInertia(mass, target) {\n // Approximate with box inertia\n // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it\n const aabbmax = new Vec3();\n const aabbmin = new Vec3();\n this.computeLocalAABB(aabbmin, aabbmax);\n const x = aabbmax.x - aabbmin.x;\n const y = aabbmax.y - aabbmin.y;\n const z = aabbmax.z - aabbmin.z;\n target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);\n target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);\n target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);\n }\n /**\n * @param face_i Index of the face\n */\n\n\n getPlaneConstantOfFace(face_i) {\n const f = this.faces[face_i];\n const n = this.faceNormals[face_i];\n const v = this.vertices[f[0]];\n const c = -n.dot(v);\n return c;\n }\n /**\n * Clip a face against a hull.\n * @param worldVertsB1 An array of Vec3 with vertices in the world frame.\n * @param minDist Distance clamping\n * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.\n */\n\n\n clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {\n const faceANormalWS = new Vec3();\n const edge0 = new Vec3();\n const WorldEdge0 = new Vec3();\n const worldPlaneAnormal1 = new Vec3();\n const planeNormalWS1 = new Vec3();\n const worldA1 = new Vec3();\n const localPlaneNormal = new Vec3();\n const planeNormalWS = new Vec3();\n const hullA = this;\n const worldVertsB2 = [];\n const pVtxIn = worldVertsB1;\n const pVtxOut = worldVertsB2;\n let closestFaceA = -1;\n let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis\n\n for (let face = 0; face < hullA.faces.length; face++) {\n faceANormalWS.copy(hullA.faceNormals[face]);\n quatA.vmult(faceANormalWS, faceANormalWS);\n const d = faceANormalWS.dot(separatingNormal);\n\n if (d < dmin) {\n dmin = d;\n closestFaceA = face;\n }\n }\n\n if (closestFaceA < 0) {\n return;\n } // Get the face and construct connected faces\n\n\n const polyA = hullA.faces[closestFaceA];\n polyA.connectedFaces = [];\n\n for (let i = 0; i < hullA.faces.length; i++) {\n for (let j = 0; j < hullA.faces[i].length; j++) {\n if (\n /* Sharing a vertex*/\n polyA.indexOf(hullA.faces[i][j]) !== -1 &&\n /* Not the one we are looking for connections from */\n i !== closestFaceA &&\n /* Not already added */\n polyA.connectedFaces.indexOf(i) === -1) {\n polyA.connectedFaces.push(i);\n }\n }\n } // Clip the polygon to the back of the planes of all faces of hull A,\n // that are adjacent to the witness face\n\n\n const numVerticesA = polyA.length;\n\n for (let i = 0; i < numVerticesA; i++) {\n const a = hullA.vertices[polyA[i]];\n const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];\n a.vsub(b, edge0);\n WorldEdge0.copy(edge0);\n quatA.vmult(WorldEdge0, WorldEdge0);\n posA.vadd(WorldEdge0, WorldEdge0);\n worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);\n quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);\n posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);\n WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);\n planeNormalWS1.negate(planeNormalWS1);\n worldA1.copy(a);\n quatA.vmult(worldA1, worldA1);\n posA.vadd(worldA1, worldA1);\n const otherFace = polyA.connectedFaces[i];\n localPlaneNormal.copy(this.faceNormals[otherFace]);\n const localPlaneEq = this.getPlaneConstantOfFace(otherFace);\n planeNormalWS.copy(localPlaneNormal);\n quatA.vmult(planeNormalWS, planeNormalWS);\n const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane\n\n this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip\n\n while (pVtxIn.length) {\n pVtxIn.shift();\n }\n\n while (pVtxOut.length) {\n pVtxIn.push(pVtxOut.shift());\n }\n } // only keep contact points that are behind the witness face\n\n\n localPlaneNormal.copy(this.faceNormals[closestFaceA]);\n const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);\n planeNormalWS.copy(localPlaneNormal);\n quatA.vmult(planeNormalWS, planeNormalWS);\n const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);\n\n for (let i = 0; i < pVtxIn.length; i++) {\n let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???\n\n if (depth <= minDist) {\n console.log(`clamped: depth=${depth} to minDist=${minDist}`);\n depth = minDist;\n }\n\n if (depth <= maxDist) {\n const point = pVtxIn[i];\n\n if (depth <= 1e-6) {\n const p = {\n point,\n normal: planeNormalWS,\n depth\n };\n result.push(p);\n }\n }\n }\n }\n /**\n * Clip a face in a hull against the back of a plane.\n * @param planeConstant The constant in the mathematical plane equation\n */\n\n\n clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {\n let n_dot_first;\n let n_dot_last;\n const numVerts = inVertices.length;\n\n if (numVerts < 2) {\n return outVertices;\n }\n\n let firstVertex = inVertices[inVertices.length - 1];\n let lastVertex = inVertices[0];\n n_dot_first = planeNormal.dot(firstVertex) + planeConstant;\n\n for (let vi = 0; vi < numVerts; vi++) {\n lastVertex = inVertices[vi];\n n_dot_last = planeNormal.dot(lastVertex) + planeConstant;\n\n if (n_dot_first < 0) {\n if (n_dot_last < 0) {\n // Start < 0, end < 0, so output lastVertex\n const newv = new Vec3();\n newv.copy(lastVertex);\n outVertices.push(newv);\n } else {\n // Start < 0, end >= 0, so output intersection\n const newv = new Vec3();\n firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);\n outVertices.push(newv);\n }\n } else {\n if (n_dot_last < 0) {\n // Start >= 0, end < 0 so output intersection and end\n const newv = new Vec3();\n firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);\n outVertices.push(newv);\n outVertices.push(lastVertex);\n }\n }\n\n firstVertex = lastVertex;\n n_dot_first = n_dot_last;\n }\n\n return outVertices;\n }\n /**\n * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.\n */\n\n\n computeWorldVertices(position, quat) {\n while (this.worldVertices.length < this.vertices.length) {\n this.worldVertices.push(new Vec3());\n }\n\n const verts = this.vertices;\n const worldVerts = this.worldVertices;\n\n for (let i = 0; i !== this.vertices.length; i++) {\n quat.vmult(verts[i], worldVerts[i]);\n position.vadd(worldVerts[i], worldVerts[i]);\n }\n\n this.worldVerticesNeedsUpdate = false;\n }\n\n computeLocalAABB(aabbmin, aabbmax) {\n const vertices = this.vertices;\n aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n\n for (let i = 0; i < this.vertices.length; i++) {\n const v = vertices[i];\n\n if (v.x < aabbmin.x) {\n aabbmin.x = v.x;\n } else if (v.x > aabbmax.x) {\n aabbmax.x = v.x;\n }\n\n if (v.y < aabbmin.y) {\n aabbmin.y = v.y;\n } else if (v.y > aabbmax.y) {\n aabbmax.y = v.y;\n }\n\n if (v.z < aabbmin.z) {\n aabbmin.z = v.z;\n } else if (v.z > aabbmax.z) {\n aabbmax.z = v.z;\n }\n }\n }\n /**\n * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.\n */\n\n\n computeWorldFaceNormals(quat) {\n const N = this.faceNormals.length;\n\n while (this.worldFaceNormals.length < N) {\n this.worldFaceNormals.push(new Vec3());\n }\n\n const normals = this.faceNormals;\n const worldNormals = this.worldFaceNormals;\n\n for (let i = 0; i !== N; i++) {\n quat.vmult(normals[i], worldNormals[i]);\n }\n\n this.worldFaceNormalsNeedsUpdate = false;\n }\n /**\n * updateBoundingSphereRadius\n */\n\n\n updateBoundingSphereRadius() {\n // Assume points are distributed with local (0,0,0) as center\n let max2 = 0;\n const verts = this.vertices;\n\n for (let i = 0; i !== verts.length; i++) {\n const norm2 = verts[i].lengthSquared();\n\n if (norm2 > max2) {\n max2 = norm2;\n }\n }\n\n this.boundingSphereRadius = Math.sqrt(max2);\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n const verts = this.vertices;\n let minx;\n let miny;\n let minz;\n let maxx;\n let maxy;\n let maxz;\n let tempWorldVertex = new Vec3();\n\n for (let i = 0; i < verts.length; i++) {\n tempWorldVertex.copy(verts[i]);\n quat.vmult(tempWorldVertex, tempWorldVertex);\n pos.vadd(tempWorldVertex, tempWorldVertex);\n const v = tempWorldVertex;\n\n if (minx === undefined || v.x < minx) {\n minx = v.x;\n }\n\n if (maxx === undefined || v.x > maxx) {\n maxx = v.x;\n }\n\n if (miny === undefined || v.y < miny) {\n miny = v.y;\n }\n\n if (maxy === undefined || v.y > maxy) {\n maxy = v.y;\n }\n\n if (minz === undefined || v.z < minz) {\n minz = v.z;\n }\n\n if (maxz === undefined || v.z > maxz) {\n maxz = v.z;\n }\n }\n\n min.set(minx, miny, minz);\n max.set(maxx, maxy, maxz);\n }\n /**\n * Get approximate convex volume\n */\n\n\n volume() {\n return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;\n }\n /**\n * Get an average of all the vertices positions\n */\n\n\n getAveragePointLocal(target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const verts = this.vertices;\n\n for (let i = 0; i < verts.length; i++) {\n target.vadd(verts[i], target);\n }\n\n target.scale(1 / verts.length, target);\n return target;\n }\n /**\n * Transform all local points. Will change the .vertices\n */\n\n\n transformAllPoints(offset, quat) {\n const n = this.vertices.length;\n const verts = this.vertices; // Apply rotation\n\n if (quat) {\n // Rotate vertices\n for (let i = 0; i < n; i++) {\n const v = verts[i];\n quat.vmult(v, v);\n } // Rotate face normals\n\n\n for (let i = 0; i < this.faceNormals.length; i++) {\n const v = this.faceNormals[i];\n quat.vmult(v, v);\n }\n /*\n // Rotate edges\n for(let i=0; i 0 || r1 > 0 && r2 < 0) {\n return false; // Encountered some other sign. Exit.\n }\n } // If we got here, all dot products were of the same sign.\n\n\n return positiveResult ? 1 : -1;\n }\n /**\n * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.\n * Results are saved in the array maxmin.\n * @param result result[0] and result[1] will be set to maximum and minimum, respectively.\n */\n\n\n static project(shape, axis, pos, quat, result) {\n const n = shape.vertices.length;\n project_worldVertex;\n const localAxis = project_localAxis;\n let max = 0;\n let min = 0;\n const localOrigin = project_localOrigin;\n const vs = shape.vertices;\n localOrigin.setZero(); // Transform the axis to local\n\n Transform.vectorToLocalFrame(pos, quat, axis, localAxis);\n Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);\n const add = localOrigin.dot(localAxis);\n min = max = vs[0].dot(localAxis);\n\n for (let i = 1; i < n; i++) {\n const val = vs[i].dot(localAxis);\n\n if (val > max) {\n max = val;\n }\n\n if (val < min) {\n min = val;\n }\n }\n\n min -= add;\n max -= add;\n\n if (min > max) {\n // Inconsistent - swap\n const temp = min;\n min = max;\n max = temp;\n } // Output\n\n\n result[0] = max;\n result[1] = min;\n }\n\n}\nconst maxminA = [];\nconst maxminB = [];\nconst project_worldVertex = new Vec3();\nconst project_localAxis = new Vec3();\nconst project_localOrigin = new Vec3();\n\n/**\n * A 3d box shape.\n * @example\n * const size = 1\n * const halfExtents = new CANNON.Vec3(size, size, size)\n * const boxShape = new CANNON.Box(halfExtents)\n * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })\n * world.addBody(boxBody)\n */\nclass Box extends Shape {\n /**\n * The half extents of the box.\n */\n\n /**\n * Used by the contact generator to make contacts with other convex polyhedra for example.\n */\n constructor(halfExtents) {\n super({\n type: Shape.types.BOX\n });\n this.halfExtents = halfExtents;\n this.convexPolyhedronRepresentation = null;\n this.updateConvexPolyhedronRepresentation();\n this.updateBoundingSphereRadius();\n }\n /**\n * Updates the local convex polyhedron representation used for some collisions.\n */\n\n\n updateConvexPolyhedronRepresentation() {\n const sx = this.halfExtents.x;\n const sy = this.halfExtents.y;\n const sz = this.halfExtents.z;\n const V = Vec3;\n const vertices = [new V(-sx, -sy, -sz), new V(sx, -sy, -sz), new V(sx, sy, -sz), new V(-sx, sy, -sz), new V(-sx, -sy, sz), new V(sx, -sy, sz), new V(sx, sy, sz), new V(-sx, sy, sz)];\n const faces = [[3, 2, 1, 0], // -z\n [4, 5, 6, 7], // +z\n [5, 4, 0, 1], // -y\n [2, 3, 7, 6], // +y\n [0, 4, 7, 3], // -x\n [1, 2, 6, 5] // +x\n ];\n const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];\n const h = new ConvexPolyhedron({\n vertices,\n faces,\n axes\n });\n this.convexPolyhedronRepresentation = h;\n h.material = this.material;\n }\n /**\n * Calculate the inertia of the box.\n */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n Box.calculateInertia(this.halfExtents, mass, target);\n return target;\n }\n\n static calculateInertia(halfExtents, mass, target) {\n const e = halfExtents;\n target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);\n target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);\n target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);\n }\n /**\n * Get the box 6 side normals\n * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.\n * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.\n */\n\n\n getSideNormals(sixTargetVectors, quat) {\n const sides = sixTargetVectors;\n const ex = this.halfExtents;\n sides[0].set(ex.x, 0, 0);\n sides[1].set(0, ex.y, 0);\n sides[2].set(0, 0, ex.z);\n sides[3].set(-ex.x, 0, 0);\n sides[4].set(0, -ex.y, 0);\n sides[5].set(0, 0, -ex.z);\n\n if (quat !== undefined) {\n for (let i = 0; i !== sides.length; i++) {\n quat.vmult(sides[i], sides[i]);\n }\n }\n\n return sides;\n }\n /**\n * Returns the volume of the box.\n */\n\n\n volume() {\n return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;\n }\n /**\n * updateBoundingSphereRadius\n */\n\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = this.halfExtents.length();\n }\n /**\n * forEachWorldCorner\n */\n\n\n forEachWorldCorner(pos, quat, callback) {\n const e = this.halfExtents;\n const corners = [[e.x, e.y, e.z], [-e.x, e.y, e.z], [-e.x, -e.y, e.z], [-e.x, -e.y, -e.z], [e.x, -e.y, -e.z], [e.x, e.y, -e.z], [-e.x, e.y, -e.z], [e.x, -e.y, e.z]];\n\n for (let i = 0; i < corners.length; i++) {\n worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);\n quat.vmult(worldCornerTempPos, worldCornerTempPos);\n pos.vadd(worldCornerTempPos, worldCornerTempPos);\n callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);\n }\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n const e = this.halfExtents;\n worldCornersTemp[0].set(e.x, e.y, e.z);\n worldCornersTemp[1].set(-e.x, e.y, e.z);\n worldCornersTemp[2].set(-e.x, -e.y, e.z);\n worldCornersTemp[3].set(-e.x, -e.y, -e.z);\n worldCornersTemp[4].set(e.x, -e.y, -e.z);\n worldCornersTemp[5].set(e.x, e.y, -e.z);\n worldCornersTemp[6].set(-e.x, e.y, -e.z);\n worldCornersTemp[7].set(e.x, -e.y, e.z);\n const wc = worldCornersTemp[0];\n quat.vmult(wc, wc);\n pos.vadd(wc, wc);\n max.copy(wc);\n min.copy(wc);\n\n for (let i = 1; i < 8; i++) {\n const wc = worldCornersTemp[i];\n quat.vmult(wc, wc);\n pos.vadd(wc, wc);\n const x = wc.x;\n const y = wc.y;\n const z = wc.z;\n\n if (x > max.x) {\n max.x = x;\n }\n\n if (y > max.y) {\n max.y = y;\n }\n\n if (z > max.z) {\n max.z = z;\n }\n\n if (x < min.x) {\n min.x = x;\n }\n\n if (y < min.y) {\n min.y = y;\n }\n\n if (z < min.z) {\n min.z = z;\n }\n } // Get each axis max\n // min.set(Infinity,Infinity,Infinity);\n // max.set(-Infinity,-Infinity,-Infinity);\n // this.forEachWorldCorner(pos,quat,function(x,y,z){\n // if(x > max.x){\n // max.x = x;\n // }\n // if(y > max.y){\n // max.y = y;\n // }\n // if(z > max.z){\n // max.z = z;\n // }\n // if(x < min.x){\n // min.x = x;\n // }\n // if(y < min.y){\n // min.y = y;\n // }\n // if(z < min.z){\n // min.z = z;\n // }\n // });\n\n }\n\n}\nconst worldCornerTempPos = new Vec3();\nconst worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\n\n/**\n * BODY_TYPES\n */\nconst BODY_TYPES = {\n /** DYNAMIC */\n DYNAMIC: 1,\n\n /** STATIC */\n STATIC: 2,\n\n /** KINEMATIC */\n KINEMATIC: 4\n};\n/**\n * BodyType\n */\n\n/**\n * BODY_SLEEP_STATES\n */\nconst BODY_SLEEP_STATES = {\n /** AWAKE */\n AWAKE: 0,\n\n /** SLEEPY */\n SLEEPY: 1,\n\n /** SLEEPING */\n SLEEPING: 2\n};\n/**\n * BodySleepState\n */\n\n/**\n * Base class for all body types.\n * @example\n * const shape = new CANNON.Sphere(1)\n * const body = new CANNON.Body({\n * mass: 1,\n * shape,\n * })\n * world.addBody(body)\n */\nclass Body extends EventTarget {\n /**\n * Dispatched after two bodies collide. This event is dispatched on each\n * of the two bodies involved in the collision.\n * @event collide\n * @param body The body that was involved in the collision.\n * @param contact The details of the collision.\n */\n\n /**\n * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.\n */\n\n /**\n * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.\n */\n\n /**\n * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.\n */\n\n /**\n * AWAKE\n */\n\n /**\n * SLEEPY\n */\n\n /**\n * SLEEPING\n */\n\n /**\n * Dispatched after a sleeping body has woken up.\n * @event wakeup\n */\n\n /**\n * Dispatched after a body has gone in to the sleepy state.\n * @event sleepy\n */\n\n /**\n * Dispatched after a body has fallen asleep.\n * @event sleep\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n super();\n this.id = Body.idCounter++;\n this.index = -1;\n this.world = null;\n this.vlambda = new Vec3();\n this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;\n this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;\n this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;\n this.position = new Vec3();\n this.previousPosition = new Vec3();\n this.interpolatedPosition = new Vec3();\n this.initPosition = new Vec3();\n\n if (options.position) {\n this.position.copy(options.position);\n this.previousPosition.copy(options.position);\n this.interpolatedPosition.copy(options.position);\n this.initPosition.copy(options.position);\n }\n\n this.velocity = new Vec3();\n\n if (options.velocity) {\n this.velocity.copy(options.velocity);\n }\n\n this.initVelocity = new Vec3();\n this.force = new Vec3();\n const mass = typeof options.mass === 'number' ? options.mass : 0;\n this.mass = mass;\n this.invMass = mass > 0 ? 1.0 / mass : 0;\n this.material = options.material || null;\n this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;\n this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;\n\n if (typeof options.type === typeof Body.STATIC) {\n this.type = options.type;\n }\n\n this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;\n this.sleepState = Body.AWAKE;\n this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;\n this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;\n this.timeLastSleepy = 0;\n this.wakeUpAfterNarrowphase = false;\n this.torque = new Vec3();\n this.quaternion = new Quaternion();\n this.initQuaternion = new Quaternion();\n this.previousQuaternion = new Quaternion();\n this.interpolatedQuaternion = new Quaternion();\n\n if (options.quaternion) {\n this.quaternion.copy(options.quaternion);\n this.initQuaternion.copy(options.quaternion);\n this.previousQuaternion.copy(options.quaternion);\n this.interpolatedQuaternion.copy(options.quaternion);\n }\n\n this.angularVelocity = new Vec3();\n\n if (options.angularVelocity) {\n this.angularVelocity.copy(options.angularVelocity);\n }\n\n this.initAngularVelocity = new Vec3();\n this.shapes = [];\n this.shapeOffsets = [];\n this.shapeOrientations = [];\n this.inertia = new Vec3();\n this.invInertia = new Vec3();\n this.invInertiaWorld = new Mat3();\n this.invMassSolve = 0;\n this.invInertiaSolve = new Vec3();\n this.invInertiaWorldSolve = new Mat3();\n this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;\n this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;\n this.linearFactor = new Vec3(1, 1, 1);\n\n if (options.linearFactor) {\n this.linearFactor.copy(options.linearFactor);\n }\n\n this.angularFactor = new Vec3(1, 1, 1);\n\n if (options.angularFactor) {\n this.angularFactor.copy(options.angularFactor);\n }\n\n this.aabb = new AABB();\n this.aabbNeedsUpdate = true;\n this.boundingRadius = 0;\n this.wlambda = new Vec3();\n this.isTrigger = Boolean(options.isTrigger);\n\n if (options.shape) {\n this.addShape(options.shape);\n }\n\n this.updateMassProperties();\n }\n /**\n * Wake the body up.\n */\n\n\n wakeUp() {\n const prevState = this.sleepState;\n this.sleepState = Body.AWAKE;\n this.wakeUpAfterNarrowphase = false;\n\n if (prevState === Body.SLEEPING) {\n this.dispatchEvent(Body.wakeupEvent);\n }\n }\n /**\n * Force body sleep\n */\n\n\n sleep() {\n this.sleepState = Body.SLEEPING;\n this.velocity.set(0, 0, 0);\n this.angularVelocity.set(0, 0, 0);\n this.wakeUpAfterNarrowphase = false;\n }\n /**\n * Called every timestep to update internal sleep timer and change sleep state if needed.\n * @param time The world time in seconds\n */\n\n\n sleepTick(time) {\n if (this.allowSleep) {\n const sleepState = this.sleepState;\n const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();\n const speedLimitSquared = this.sleepSpeedLimit ** 2;\n\n if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {\n this.sleepState = Body.SLEEPY; // Sleepy\n\n this.timeLastSleepy = time;\n this.dispatchEvent(Body.sleepyEvent);\n } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {\n this.wakeUp(); // Wake up\n } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {\n this.sleep(); // Sleeping\n\n this.dispatchEvent(Body.sleepEvent);\n }\n }\n }\n /**\n * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate \"solve mass\".\n */\n\n\n updateSolveMassProperties() {\n if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {\n this.invMassSolve = 0;\n this.invInertiaSolve.setZero();\n this.invInertiaWorldSolve.setZero();\n } else {\n this.invMassSolve = this.invMass;\n this.invInertiaSolve.copy(this.invInertia);\n this.invInertiaWorldSolve.copy(this.invInertiaWorld);\n }\n }\n /**\n * Convert a world point to local body frame.\n */\n\n\n pointToLocalFrame(worldPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n worldPoint.vsub(this.position, result);\n this.quaternion.conjugate().vmult(result, result);\n return result;\n }\n /**\n * Convert a world vector to local body frame.\n */\n\n\n vectorToLocalFrame(worldVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.conjugate().vmult(worldVector, result);\n return result;\n }\n /**\n * Convert a local body point to world frame.\n */\n\n\n pointToWorldFrame(localPoint, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localPoint, result);\n result.vadd(this.position, result);\n return result;\n }\n /**\n * Convert a local body point to world frame.\n */\n\n\n vectorToWorldFrame(localVector, result) {\n if (result === void 0) {\n result = new Vec3();\n }\n\n this.quaternion.vmult(localVector, result);\n return result;\n }\n /**\n * Add a shape to the body with a local offset and orientation.\n * @return The body object, for chainability.\n */\n\n\n addShape(shape, _offset, _orientation) {\n const offset = new Vec3();\n const orientation = new Quaternion();\n\n if (_offset) {\n offset.copy(_offset);\n }\n\n if (_orientation) {\n orientation.copy(_orientation);\n }\n\n this.shapes.push(shape);\n this.shapeOffsets.push(offset);\n this.shapeOrientations.push(orientation);\n this.updateMassProperties();\n this.updateBoundingRadius();\n this.aabbNeedsUpdate = true;\n shape.body = this;\n return this;\n }\n /**\n * Remove a shape from the body.\n * @return The body object, for chainability.\n */\n\n\n removeShape(shape) {\n const index = this.shapes.indexOf(shape);\n\n if (index === -1) {\n console.warn('Shape does not belong to the body');\n return this;\n }\n\n this.shapes.splice(index, 1);\n this.shapeOffsets.splice(index, 1);\n this.shapeOrientations.splice(index, 1);\n this.updateMassProperties();\n this.updateBoundingRadius();\n this.aabbNeedsUpdate = true;\n shape.body = null;\n return this;\n }\n /**\n * Update the bounding radius of the body. Should be done if any of the shapes are changed.\n */\n\n\n updateBoundingRadius() {\n const shapes = this.shapes;\n const shapeOffsets = this.shapeOffsets;\n const N = shapes.length;\n let radius = 0;\n\n for (let i = 0; i !== N; i++) {\n const shape = shapes[i];\n shape.updateBoundingSphereRadius();\n const offset = shapeOffsets[i].length();\n const r = shape.boundingSphereRadius;\n\n if (offset + r > radius) {\n radius = offset + r;\n }\n }\n\n this.boundingRadius = radius;\n }\n /**\n * Updates the .aabb\n */\n\n\n updateAABB() {\n const shapes = this.shapes;\n const shapeOffsets = this.shapeOffsets;\n const shapeOrientations = this.shapeOrientations;\n const N = shapes.length;\n const offset = tmpVec;\n const orientation = tmpQuat;\n const bodyQuat = this.quaternion;\n const aabb = this.aabb;\n const shapeAABB = updateAABB_shapeAABB;\n\n for (let i = 0; i !== N; i++) {\n const shape = shapes[i]; // Get shape world position\n\n bodyQuat.vmult(shapeOffsets[i], offset);\n offset.vadd(this.position, offset); // Get shape world quaternion\n\n bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB\n\n shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);\n\n if (i === 0) {\n aabb.copy(shapeAABB);\n } else {\n aabb.extend(shapeAABB);\n }\n }\n\n this.aabbNeedsUpdate = false;\n }\n /**\n * Update `.inertiaWorld` and `.invInertiaWorld`\n */\n\n\n updateInertiaWorld(force) {\n const I = this.invInertia;\n\n if (I.x === I.y && I.y === I.z && !force) ; else {\n const m1 = uiw_m1;\n const m2 = uiw_m2;\n uiw_m3;\n m1.setRotationFromQuaternion(this.quaternion);\n m1.transpose(m2);\n m1.scale(I, m1);\n m1.mmult(m2, this.invInertiaWorld);\n }\n }\n /**\n * Apply force to a point of the body. This could for example be a point on the Body surface.\n * Applying force this way will add to Body.force and Body.torque.\n * @param force The amount of force to add.\n * @param relativePoint A point relative to the center of mass to apply the force on.\n */\n\n\n applyForce(force, relativePoint) {\n if (relativePoint === void 0) {\n relativePoint = new Vec3();\n }\n\n // Needed?\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Compute produced rotational force\n\n\n const rotForce = Body_applyForce_rotForce;\n relativePoint.cross(force, rotForce); // Add linear force\n\n this.force.vadd(force, this.force); // Add rotational force\n\n this.torque.vadd(rotForce, this.torque);\n }\n /**\n * Apply force to a local point in the body.\n * @param force The force vector to apply, defined locally in the body frame.\n * @param localPoint A local point in the body to apply the force on.\n */\n\n\n applyLocalForce(localForce, localPoint) {\n if (localPoint === void 0) {\n localPoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n const worldForce = Body_applyLocalForce_worldForce;\n const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space\n\n this.vectorToWorldFrame(localForce, worldForce);\n this.vectorToWorldFrame(localPoint, relativePointWorld);\n this.applyForce(worldForce, relativePointWorld);\n }\n /**\n * Apply torque to the body.\n * @param torque The amount of torque to add.\n */\n\n\n applyTorque(torque) {\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Add rotational force\n\n\n this.torque.vadd(torque, this.torque);\n }\n /**\n * Apply impulse to a point of the body. This could for example be a point on the Body surface.\n * An impulse is a force added to a body during a short period of time (impulse = force * time).\n * Impulses will be added to Body.velocity and Body.angularVelocity.\n * @param impulse The amount of impulse to add.\n * @param relativePoint A point relative to the center of mass to apply the force on.\n */\n\n\n applyImpulse(impulse, relativePoint) {\n if (relativePoint === void 0) {\n relativePoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n if (this.sleepState === Body.SLEEPING) {\n this.wakeUp();\n } // Compute point position relative to the body center\n\n\n const r = relativePoint; // Compute produced central impulse velocity\n\n const velo = Body_applyImpulse_velo;\n velo.copy(impulse);\n velo.scale(this.invMass, velo); // Add linear impulse\n\n this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity\n\n const rotVelo = Body_applyImpulse_rotVelo;\n r.cross(impulse, rotVelo);\n /*\n rotVelo.x *= this.invInertia.x;\n rotVelo.y *= this.invInertia.y;\n rotVelo.z *= this.invInertia.z;\n */\n\n this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse\n\n this.angularVelocity.vadd(rotVelo, this.angularVelocity);\n }\n /**\n * Apply locally-defined impulse to a local point in the body.\n * @param force The force vector to apply, defined locally in the body frame.\n * @param localPoint A local point in the body to apply the force on.\n */\n\n\n applyLocalImpulse(localImpulse, localPoint) {\n if (localPoint === void 0) {\n localPoint = new Vec3();\n }\n\n if (this.type !== Body.DYNAMIC) {\n return;\n }\n\n const worldImpulse = Body_applyLocalImpulse_worldImpulse;\n const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space\n\n this.vectorToWorldFrame(localImpulse, worldImpulse);\n this.vectorToWorldFrame(localPoint, relativePointWorld);\n this.applyImpulse(worldImpulse, relativePointWorld);\n }\n /**\n * Should be called whenever you change the body shape or mass.\n */\n\n\n updateMassProperties() {\n const halfExtents = Body_updateMassProperties_halfExtents;\n this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;\n const I = this.inertia;\n const fixed = this.fixedRotation; // Approximate with AABB box\n\n this.updateAABB();\n halfExtents.set((this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2, (this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2, (this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2);\n Box.calculateInertia(halfExtents, this.mass, I);\n this.invInertia.set(I.x > 0 && !fixed ? 1.0 / I.x : 0, I.y > 0 && !fixed ? 1.0 / I.y : 0, I.z > 0 && !fixed ? 1.0 / I.z : 0);\n this.updateInertiaWorld(true);\n }\n /**\n * Get world velocity of a point in the body.\n * @param worldPoint\n * @param result\n * @return The result vector.\n */\n\n\n getVelocityAtWorldPoint(worldPoint, result) {\n const r = new Vec3();\n worldPoint.vsub(this.position, r);\n this.angularVelocity.cross(r, result);\n this.velocity.vadd(result, result);\n return result;\n }\n /**\n * Move the body forward in time.\n * @param dt Time step\n * @param quatNormalize Set to true to normalize the body quaternion\n * @param quatNormalizeFast If the quaternion should be normalized using \"fast\" quaternion normalization\n */\n\n\n integrate(dt, quatNormalize, quatNormalizeFast) {\n // Save previous position\n this.previousPosition.copy(this.position);\n this.previousQuaternion.copy(this.quaternion);\n\n if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {\n // Only for dynamic\n return;\n }\n\n const velo = this.velocity;\n const angularVelo = this.angularVelocity;\n const pos = this.position;\n const force = this.force;\n const torque = this.torque;\n const quat = this.quaternion;\n const invMass = this.invMass;\n const invInertia = this.invInertiaWorld;\n const linearFactor = this.linearFactor;\n const iMdt = invMass * dt;\n velo.x += force.x * iMdt * linearFactor.x;\n velo.y += force.y * iMdt * linearFactor.y;\n velo.z += force.z * iMdt * linearFactor.z;\n const e = invInertia.elements;\n const angularFactor = this.angularFactor;\n const tx = torque.x * angularFactor.x;\n const ty = torque.y * angularFactor.y;\n const tz = torque.z * angularFactor.z;\n angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);\n angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);\n angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog\n\n pos.x += velo.x * dt;\n pos.y += velo.y * dt;\n pos.z += velo.z * dt;\n quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);\n\n if (quatNormalize) {\n if (quatNormalizeFast) {\n quat.normalizeFast();\n } else {\n quat.normalize();\n }\n }\n\n this.aabbNeedsUpdate = true; // Update world inertia\n\n this.updateInertiaWorld();\n }\n\n}\nBody.idCounter = 0;\nBody.COLLIDE_EVENT_NAME = 'collide';\nBody.DYNAMIC = BODY_TYPES.DYNAMIC;\nBody.STATIC = BODY_TYPES.STATIC;\nBody.KINEMATIC = BODY_TYPES.KINEMATIC;\nBody.AWAKE = BODY_SLEEP_STATES.AWAKE;\nBody.SLEEPY = BODY_SLEEP_STATES.SLEEPY;\nBody.SLEEPING = BODY_SLEEP_STATES.SLEEPING;\nBody.wakeupEvent = {\n type: 'wakeup'\n};\nBody.sleepyEvent = {\n type: 'sleepy'\n};\nBody.sleepEvent = {\n type: 'sleep'\n};\nconst tmpVec = new Vec3();\nconst tmpQuat = new Quaternion();\nconst updateAABB_shapeAABB = new AABB();\nconst uiw_m1 = new Mat3();\nconst uiw_m2 = new Mat3();\nconst uiw_m3 = new Mat3();\nconst Body_applyForce_rotForce = new Vec3();\nconst Body_applyLocalForce_worldForce = new Vec3();\nconst Body_applyLocalForce_relativePointWorld = new Vec3();\nconst Body_applyImpulse_velo = new Vec3();\nconst Body_applyImpulse_rotVelo = new Vec3();\nconst Body_applyLocalImpulse_worldImpulse = new Vec3();\nconst Body_applyLocalImpulse_relativePoint = new Vec3();\nconst Body_updateMassProperties_halfExtents = new Vec3();\n\n/**\n * Base class for broadphase implementations\n * @author schteppe\n */\nclass Broadphase {\n /**\n * The world to search for collisions in.\n */\n\n /**\n * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.\n */\n\n /**\n * Set to true if the objects in the world moved.\n */\n constructor() {\n this.world = null;\n this.useBoundingBoxes = false;\n this.dirty = true;\n }\n /**\n * Get the collision pairs from the world\n * @param world The world to search in\n * @param p1 Empty array to be filled with body objects\n * @param p2 Empty array to be filled with body objects\n */\n\n\n collisionPairs(world, p1, p2) {\n throw new Error('collisionPairs not implemented for this BroadPhase class!');\n }\n /**\n * Check if a body pair needs to be intersection tested at all.\n */\n\n\n needBroadphaseCollision(bodyA, bodyB) {\n // Check collision filter masks\n if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {\n return false;\n } // Check types\n\n\n if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {\n // Both bodies are static or sleeping. Skip.\n return false;\n }\n\n return true;\n }\n /**\n * Check if the bounding volumes of two bodies intersect.\n */\n\n\n intersectionTest(bodyA, bodyB, pairs1, pairs2) {\n if (this.useBoundingBoxes) {\n this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);\n } else {\n this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);\n }\n }\n /**\n * Check if the bounding spheres of two bodies are intersecting.\n * @param pairs1 bodyA is appended to this array if intersection\n * @param pairs2 bodyB is appended to this array if intersection\n */\n\n\n doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {\n const r = Broadphase_collisionPairs_r;\n bodyB.position.vsub(bodyA.position, r);\n const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;\n const norm2 = r.lengthSquared();\n\n if (norm2 < boundingRadiusSum2) {\n pairs1.push(bodyA);\n pairs2.push(bodyB);\n }\n }\n /**\n * Check if the bounding boxes of two bodies are intersecting.\n */\n\n\n doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {\n if (bodyA.aabbNeedsUpdate) {\n bodyA.updateAABB();\n }\n\n if (bodyB.aabbNeedsUpdate) {\n bodyB.updateAABB();\n } // Check AABB / AABB\n\n\n if (bodyA.aabb.overlaps(bodyB.aabb)) {\n pairs1.push(bodyA);\n pairs2.push(bodyB);\n }\n }\n /**\n * Removes duplicate pairs from the pair arrays.\n */\n\n\n makePairsUnique(pairs1, pairs2) {\n const t = Broadphase_makePairsUnique_temp;\n const p1 = Broadphase_makePairsUnique_p1;\n const p2 = Broadphase_makePairsUnique_p2;\n const N = pairs1.length;\n\n for (let i = 0; i !== N; i++) {\n p1[i] = pairs1[i];\n p2[i] = pairs2[i];\n }\n\n pairs1.length = 0;\n pairs2.length = 0;\n\n for (let i = 0; i !== N; i++) {\n const id1 = p1[i].id;\n const id2 = p2[i].id;\n const key = id1 < id2 ? `${id1},${id2}` : `${id2},${id1}`;\n t[key] = i;\n t.keys.push(key);\n }\n\n for (let i = 0; i !== t.keys.length; i++) {\n const key = t.keys.pop();\n const pairIndex = t[key];\n pairs1.push(p1[pairIndex]);\n pairs2.push(p2[pairIndex]);\n delete t[key];\n }\n }\n /**\n * To be implemented by subcasses\n */\n\n\n setWorld(world) {}\n /**\n * Check if the bounding spheres of two bodies overlap.\n */\n\n\n static boundingSphereCheck(bodyA, bodyB) {\n const dist = new Vec3(); // bsc_dist;\n\n bodyA.position.vsub(bodyB.position, dist);\n const sa = bodyA.shapes[0];\n const sb = bodyB.shapes[0];\n return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();\n }\n /**\n * Returns all the bodies within the AABB.\n */\n\n\n aabbQuery(world, aabb, result) {\n console.warn('.aabbQuery is not implemented in this Broadphase subclass.');\n return [];\n }\n\n} // Temp objects\n\nconst Broadphase_collisionPairs_r = new Vec3();\nnew Vec3();\nnew Quaternion();\nnew Vec3();\nconst Broadphase_makePairsUnique_temp = {\n keys: []\n};\nconst Broadphase_makePairsUnique_p1 = [];\nconst Broadphase_makePairsUnique_p2 = [];\nnew Vec3();\n\n/**\n * Axis aligned uniform grid broadphase.\n * @todo Needs support for more than just planes and spheres.\n */\nclass GridBroadphase extends Broadphase {\n /**\n * Number of boxes along x\n */\n\n /**\n * Number of boxes along y\n */\n\n /**\n * Number of boxes along z\n */\n\n /**\n * aabbMin\n */\n\n /**\n * aabbMax\n */\n\n /**\n * bins\n */\n\n /**\n * binLengths\n */\n\n /**\n * @param nx Number of boxes along x.\n * @param ny Number of boxes along y.\n * @param nz Number of boxes along z.\n */\n constructor(aabbMin, aabbMax, nx, ny, nz) {\n if (aabbMin === void 0) {\n aabbMin = new Vec3(100, 100, 100);\n }\n\n if (aabbMax === void 0) {\n aabbMax = new Vec3(-100, -100, -100);\n }\n\n if (nx === void 0) {\n nx = 10;\n }\n\n if (ny === void 0) {\n ny = 10;\n }\n\n if (nz === void 0) {\n nz = 10;\n }\n\n super();\n this.nx = nx;\n this.ny = ny;\n this.nz = nz;\n this.aabbMin = aabbMin;\n this.aabbMax = aabbMax;\n const nbins = this.nx * this.ny * this.nz;\n\n if (nbins <= 0) {\n throw \"GridBroadphase: Each dimension's n must be >0\";\n }\n\n this.bins = [];\n this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow\n\n this.bins.length = nbins;\n this.binLengths.length = nbins;\n\n for (let i = 0; i < nbins; i++) {\n this.bins[i] = [];\n this.binLengths[i] = 0;\n }\n }\n /**\n * Get all the collision pairs in the physics world\n */\n\n\n collisionPairs(world, pairs1, pairs2) {\n const N = world.bodies.length;\n const bodies = world.bodies;\n const max = this.aabbMax;\n const min = this.aabbMin;\n const nx = this.nx;\n const ny = this.ny;\n const nz = this.nz;\n const xstep = ny * nz;\n const ystep = nz;\n const zstep = 1;\n const xmax = max.x;\n const ymax = max.y;\n const zmax = max.z;\n const xmin = min.x;\n const ymin = min.y;\n const zmin = min.z;\n const xmult = nx / (xmax - xmin);\n const ymult = ny / (ymax - ymin);\n const zmult = nz / (zmax - zmin);\n const binsizeX = (xmax - xmin) / nx;\n const binsizeY = (ymax - ymin) / ny;\n const binsizeZ = (zmax - zmin) / nz;\n const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;\n const types = Shape.types;\n const SPHERE = types.SPHERE;\n const PLANE = types.PLANE;\n types.BOX;\n types.COMPOUND;\n types.CONVEXPOLYHEDRON;\n const bins = this.bins;\n const binLengths = this.binLengths;\n const Nbins = this.bins.length; // Reset bins\n\n for (let i = 0; i !== Nbins; i++) {\n binLengths[i] = 0;\n }\n\n const ceil = Math.ceil;\n\n function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {\n let xoff0 = (x0 - xmin) * xmult | 0;\n let yoff0 = (y0 - ymin) * ymult | 0;\n let zoff0 = (z0 - zmin) * zmult | 0;\n let xoff1 = ceil((x1 - xmin) * xmult);\n let yoff1 = ceil((y1 - ymin) * ymult);\n let zoff1 = ceil((z1 - zmin) * zmult);\n\n if (xoff0 < 0) {\n xoff0 = 0;\n } else if (xoff0 >= nx) {\n xoff0 = nx - 1;\n }\n\n if (yoff0 < 0) {\n yoff0 = 0;\n } else if (yoff0 >= ny) {\n yoff0 = ny - 1;\n }\n\n if (zoff0 < 0) {\n zoff0 = 0;\n } else if (zoff0 >= nz) {\n zoff0 = nz - 1;\n }\n\n if (xoff1 < 0) {\n xoff1 = 0;\n } else if (xoff1 >= nx) {\n xoff1 = nx - 1;\n }\n\n if (yoff1 < 0) {\n yoff1 = 0;\n } else if (yoff1 >= ny) {\n yoff1 = ny - 1;\n }\n\n if (zoff1 < 0) {\n zoff1 = 0;\n } else if (zoff1 >= nz) {\n zoff1 = nz - 1;\n }\n\n xoff0 *= xstep;\n yoff0 *= ystep;\n zoff0 *= zstep;\n xoff1 *= xstep;\n yoff1 *= ystep;\n zoff1 *= zstep;\n\n for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) {\n for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) {\n for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) {\n const idx = xoff + yoff + zoff;\n bins[idx][binLengths[idx]++] = bi;\n }\n }\n }\n } // Put all bodies into the bins\n\n\n for (let i = 0; i !== N; i++) {\n const bi = bodies[i];\n const si = bi.shapes[0];\n\n switch (si.type) {\n case SPHERE:\n {\n const shape = si; // Put in bin\n // check if overlap with other bins\n\n const x = bi.position.x;\n const y = bi.position.y;\n const z = bi.position.z;\n const r = shape.radius;\n addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);\n break;\n }\n\n case PLANE:\n {\n const shape = si;\n\n if (shape.worldNormalNeedsUpdate) {\n shape.computeWorldNormal(bi.quaternion);\n }\n\n const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin\n //Incremented as we iterate through the bins\n\n const xreset = xmin + binsizeX * 0.5 - bi.position.x;\n const yreset = ymin + binsizeY * 0.5 - bi.position.y;\n const zreset = zmin + binsizeZ * 0.5 - bi.position.z;\n const d = GridBroadphase_collisionPairs_d;\n d.set(xreset, yreset, zreset);\n\n for (let xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {\n for (let yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {\n for (let zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {\n if (d.dot(planeNormal) < binRadius) {\n const idx = xoff + yoff + zoff;\n bins[idx][binLengths[idx]++] = bi;\n }\n }\n }\n }\n\n break;\n }\n\n default:\n {\n if (bi.aabbNeedsUpdate) {\n bi.updateAABB();\n }\n\n addBoxToBins(bi.aabb.lowerBound.x, bi.aabb.lowerBound.y, bi.aabb.lowerBound.z, bi.aabb.upperBound.x, bi.aabb.upperBound.y, bi.aabb.upperBound.z, bi);\n break;\n }\n }\n } // Check each bin\n\n\n for (let i = 0; i !== Nbins; i++) {\n const binLength = binLengths[i]; //Skip bins with no potential collisions\n\n if (binLength > 1) {\n const bin = bins[i]; // Do N^2 broadphase inside\n\n for (let xi = 0; xi !== binLength; xi++) {\n const bi = bin[xi];\n\n for (let yi = 0; yi !== xi; yi++) {\n const bj = bin[yi];\n\n if (this.needBroadphaseCollision(bi, bj)) {\n this.intersectionTest(bi, bj, pairs1, pairs2);\n }\n }\n }\n }\n } //\tfor (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {\n //\t\tconsole.log(\"layer \"+zi);\n //\t\tfor (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {\n //\t\t\tconst row = '';\n //\t\t\tfor (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {\n //\t\t\t\tconst idx = xoff + yoff + zoff;\n //\t\t\t\trow += ' ' + binLengths[idx];\n //\t\t\t}\n //\t\t\tconsole.log(row);\n //\t\t}\n //\t}\n\n\n this.makePairsUnique(pairs1, pairs2);\n }\n\n}\nconst GridBroadphase_collisionPairs_d = new Vec3();\nnew Vec3();\n\n/**\n * Naive broadphase implementation, used in lack of better ones.\n *\n * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_\n */\nclass NaiveBroadphase extends Broadphase {\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n super();\n }\n /**\n * Get all the collision pairs in the physics world\n */\n\n\n collisionPairs(world, pairs1, pairs2) {\n const bodies = world.bodies;\n const n = bodies.length;\n let bi;\n let bj; // Naive N^2 ftw!\n\n for (let i = 0; i !== n; i++) {\n for (let j = 0; j !== i; j++) {\n bi = bodies[i];\n bj = bodies[j];\n\n if (!this.needBroadphaseCollision(bi, bj)) {\n continue;\n }\n\n this.intersectionTest(bi, bj, pairs1, pairs2);\n }\n }\n }\n /**\n * Returns all the bodies within an AABB.\n * @param result An array to store resulting bodies in.\n */\n\n\n aabbQuery(world, aabb, result) {\n if (result === void 0) {\n result = [];\n }\n\n for (let i = 0; i < world.bodies.length; i++) {\n const b = world.bodies[i];\n\n if (b.aabbNeedsUpdate) {\n b.updateAABB();\n } // Ugly hack until Body gets aabb\n\n\n if (b.aabb.overlaps(aabb)) {\n result.push(b);\n }\n }\n\n return result;\n }\n\n}\n\n/**\n * Storage for Ray casting data\n */\nclass RaycastResult {\n /**\n * rayFromWorld\n */\n\n /**\n * rayToWorld\n */\n\n /**\n * hitNormalWorld\n */\n\n /**\n * hitPointWorld\n */\n\n /**\n * hasHit\n */\n\n /**\n * shape\n */\n\n /**\n * body\n */\n\n /**\n * The index of the hit triangle, if the hit shape was a trimesh\n */\n\n /**\n * Distance to the hit. Will be set to -1 if there was no hit\n */\n\n /**\n * If the ray should stop traversing the bodies\n */\n constructor() {\n this.rayFromWorld = new Vec3();\n this.rayToWorld = new Vec3();\n this.hitNormalWorld = new Vec3();\n this.hitPointWorld = new Vec3();\n this.hasHit = false;\n this.shape = null;\n this.body = null;\n this.hitFaceIndex = -1;\n this.distance = -1;\n this.shouldStop = false;\n }\n /**\n * Reset all result data.\n */\n\n\n reset() {\n this.rayFromWorld.setZero();\n this.rayToWorld.setZero();\n this.hitNormalWorld.setZero();\n this.hitPointWorld.setZero();\n this.hasHit = false;\n this.shape = null;\n this.body = null;\n this.hitFaceIndex = -1;\n this.distance = -1;\n this.shouldStop = false;\n }\n /**\n * abort\n */\n\n\n abort() {\n this.shouldStop = true;\n }\n /**\n * Set result data.\n */\n\n\n set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {\n this.rayFromWorld.copy(rayFromWorld);\n this.rayToWorld.copy(rayToWorld);\n this.hitNormalWorld.copy(hitNormalWorld);\n this.hitPointWorld.copy(hitPointWorld);\n this.shape = shape;\n this.body = body;\n this.distance = distance;\n }\n\n}\n\nlet _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;\n\n/**\n * RAY_MODES\n */\nconst RAY_MODES = {\n /** CLOSEST */\n CLOSEST: 1,\n\n /** ANY */\n ANY: 2,\n\n /** ALL */\n ALL: 4\n};\n/**\n * RayMode\n */\n\n_Shape$types$SPHERE = Shape.types.SPHERE;\n_Shape$types$PLANE = Shape.types.PLANE;\n_Shape$types$BOX = Shape.types.BOX;\n_Shape$types$CYLINDER = Shape.types.CYLINDER;\n_Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;\n_Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;\n_Shape$types$TRIMESH = Shape.types.TRIMESH;\n\n/**\n * A line in 3D space that intersects bodies and return points.\n */\nclass Ray {\n /**\n * from\n */\n\n /**\n * to\n */\n\n /**\n * direction\n */\n\n /**\n * The precision of the ray. Used when checking parallelity etc.\n * @default 0.0001\n */\n\n /**\n * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.\n * @default true\n */\n\n /**\n * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.\n * @default false\n */\n\n /**\n * collisionFilterMask\n * @default -1\n */\n\n /**\n * collisionFilterGroup\n * @default -1\n */\n\n /**\n * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.\n * @default RAY.ANY\n */\n\n /**\n * Current result object.\n */\n\n /**\n * Will be set to `true` during intersectWorld() if the ray hit anything.\n */\n\n /**\n * User-provided result callback. Will be used if mode is Ray.ALL.\n */\n\n /**\n * CLOSEST\n */\n\n /**\n * ANY\n */\n\n /**\n * ALL\n */\n get [_Shape$types$SPHERE]() {\n return this._intersectSphere;\n }\n\n get [_Shape$types$PLANE]() {\n return this._intersectPlane;\n }\n\n get [_Shape$types$BOX]() {\n return this._intersectBox;\n }\n\n get [_Shape$types$CYLINDER]() {\n return this._intersectConvex;\n }\n\n get [_Shape$types$CONVEXPO]() {\n return this._intersectConvex;\n }\n\n get [_Shape$types$HEIGHTFI]() {\n return this._intersectHeightfield;\n }\n\n get [_Shape$types$TRIMESH]() {\n return this._intersectTrimesh;\n }\n\n constructor(from, to) {\n if (from === void 0) {\n from = new Vec3();\n }\n\n if (to === void 0) {\n to = new Vec3();\n }\n\n this.from = from.clone();\n this.to = to.clone();\n this.direction = new Vec3();\n this.precision = 0.0001;\n this.checkCollisionResponse = true;\n this.skipBackfaces = false;\n this.collisionFilterMask = -1;\n this.collisionFilterGroup = -1;\n this.mode = Ray.ANY;\n this.result = new RaycastResult();\n this.hasHit = false;\n\n this.callback = result => {};\n }\n /**\n * Do itersection against all bodies in the given World.\n * @return True if the ray hit anything, otherwise false.\n */\n\n\n intersectWorld(world, options) {\n this.mode = options.mode || Ray.ANY;\n this.result = options.result || new RaycastResult();\n this.skipBackfaces = !!options.skipBackfaces;\n this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;\n this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;\n this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;\n\n if (options.from) {\n this.from.copy(options.from);\n }\n\n if (options.to) {\n this.to.copy(options.to);\n }\n\n this.callback = options.callback || (() => {});\n\n this.hasHit = false;\n this.result.reset();\n this.updateDirection();\n this.getAABB(tmpAABB$1);\n tmpArray.length = 0;\n world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);\n this.intersectBodies(tmpArray);\n return this.hasHit;\n }\n /**\n * Shoot a ray at a body, get back information about the hit.\n * @deprecated @param result set the result property of the Ray instead.\n */\n\n\n intersectBody(body, result) {\n if (result) {\n this.result = result;\n this.updateDirection();\n }\n\n const checkCollisionResponse = this.checkCollisionResponse;\n\n if (checkCollisionResponse && !body.collisionResponse) {\n return;\n }\n\n if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {\n return;\n }\n\n const xi = intersectBody_xi;\n const qi = intersectBody_qi;\n\n for (let i = 0, N = body.shapes.length; i < N; i++) {\n const shape = body.shapes[i];\n\n if (checkCollisionResponse && !shape.collisionResponse) {\n continue; // Skip\n }\n\n body.quaternion.mult(body.shapeOrientations[i], qi);\n body.quaternion.vmult(body.shapeOffsets[i], xi);\n xi.vadd(body.position, xi);\n this.intersectShape(shape, qi, xi, body);\n\n if (this.result.shouldStop) {\n break;\n }\n }\n }\n /**\n * Shoot a ray at an array bodies, get back information about the hit.\n * @param bodies An array of Body objects.\n * @deprecated @param result set the result property of the Ray instead.\n *\n */\n\n\n intersectBodies(bodies, result) {\n if (result) {\n this.result = result;\n this.updateDirection();\n }\n\n for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {\n this.intersectBody(bodies[i]);\n }\n }\n /**\n * Updates the direction vector.\n */\n\n\n updateDirection() {\n this.to.vsub(this.from, this.direction);\n this.direction.normalize();\n }\n\n intersectShape(shape, quat, position, body) {\n const from = this.from; // Checking boundingSphere\n\n const distance = distanceFromIntersection(from, this.direction, position);\n\n if (distance > shape.boundingSphereRadius) {\n return;\n }\n\n const intersectMethod = this[shape.type];\n\n if (intersectMethod) {\n intersectMethod.call(this, shape, quat, position, body, shape);\n }\n }\n\n _intersectBox(box, quat, position, body, reportedShape) {\n return this._intersectConvex(box.convexPolyhedronRepresentation, quat, position, body, reportedShape);\n }\n\n _intersectPlane(shape, quat, position, body, reportedShape) {\n const from = this.from;\n const to = this.to;\n const direction = this.direction; // Get plane normal\n\n const worldNormal = new Vec3(0, 0, 1);\n quat.vmult(worldNormal, worldNormal);\n const len = new Vec3();\n from.vsub(position, len);\n const planeToFrom = len.dot(worldNormal);\n to.vsub(position, len);\n const planeToTo = len.dot(worldNormal);\n\n if (planeToFrom * planeToTo > 0) {\n // \"from\" and \"to\" are on the same side of the plane... bail out\n return;\n }\n\n if (from.distanceTo(to) < planeToFrom) {\n return;\n }\n\n const n_dot_dir = worldNormal.dot(direction);\n\n if (Math.abs(n_dot_dir) < this.precision) {\n // No intersection\n return;\n }\n\n const planePointToFrom = new Vec3();\n const dir_scaled_with_t = new Vec3();\n const hitPointWorld = new Vec3();\n from.vsub(position, planePointToFrom);\n const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;\n direction.scale(t, dir_scaled_with_t);\n from.vadd(dir_scaled_with_t, hitPointWorld);\n this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);\n }\n /**\n * Get the world AABB of the ray.\n */\n\n\n getAABB(aabb) {\n const {\n lowerBound,\n upperBound\n } = aabb;\n const to = this.to;\n const from = this.from;\n lowerBound.x = Math.min(to.x, from.x);\n lowerBound.y = Math.min(to.y, from.y);\n lowerBound.z = Math.min(to.z, from.z);\n upperBound.x = Math.max(to.x, from.x);\n upperBound.y = Math.max(to.y, from.y);\n upperBound.z = Math.max(to.z, from.z);\n }\n\n _intersectHeightfield(shape, quat, position, body, reportedShape) {\n shape.data;\n shape.elementSize; // Convert the ray to local heightfield coordinates\n\n const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);\n\n localRay.from.copy(this.from);\n localRay.to.copy(this.to);\n Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);\n Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);\n localRay.updateDirection(); // Get the index of the data points to test against\n\n const index = intersectHeightfield_index;\n let iMinX;\n let iMinY;\n let iMaxX;\n let iMaxY; // Set to max\n\n iMinX = iMinY = 0;\n iMaxX = iMaxY = shape.data.length - 1;\n const aabb = new AABB();\n localRay.getAABB(aabb);\n shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);\n iMinX = Math.max(iMinX, index[0]);\n iMinY = Math.max(iMinY, index[1]);\n shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);\n iMaxX = Math.min(iMaxX, index[0] + 1);\n iMaxY = Math.min(iMaxY, index[1] + 1);\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n if (this.result.shouldStop) {\n return;\n }\n\n shape.getAabbAtIndex(i, j, aabb);\n\n if (!aabb.overlapsRay(localRay)) {\n continue;\n } // Lower triangle\n\n\n shape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);\n\n this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);\n\n if (this.result.shouldStop) {\n return;\n } // Upper triangle\n\n\n shape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);\n\n this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);\n }\n }\n }\n\n _intersectSphere(sphere, quat, position, body, reportedShape) {\n const from = this.from;\n const to = this.to;\n const r = sphere.radius;\n const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;\n const b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));\n const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;\n const delta = b ** 2 - 4 * a * c;\n const intersectionPoint = Ray_intersectSphere_intersectionPoint;\n const normal = Ray_intersectSphere_normal;\n\n if (delta < 0) {\n // No intersection\n return;\n } else if (delta === 0) {\n // single intersection point\n from.lerp(to, delta, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n } else {\n const d1 = (-b - Math.sqrt(delta)) / (2 * a);\n const d2 = (-b + Math.sqrt(delta)) / (2 * a);\n\n if (d1 >= 0 && d1 <= 1) {\n from.lerp(to, d1, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n }\n\n if (this.result.shouldStop) {\n return;\n }\n\n if (d2 >= 0 && d2 <= 1) {\n from.lerp(to, d2, intersectionPoint);\n intersectionPoint.vsub(position, normal);\n normal.normalize();\n this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);\n }\n }\n }\n\n _intersectConvex(shape, quat, position, body, reportedShape, options) {\n intersectConvex_minDistNormal;\n const normal = intersectConvex_normal;\n const vector = intersectConvex_vector;\n intersectConvex_minDistIntersect;\n const faceList = options && options.faceList || null; // Checking faces\n\n const faces = shape.faces;\n const vertices = shape.vertices;\n const normals = shape.faceNormals;\n const direction = this.direction;\n const from = this.from;\n const to = this.to;\n const fromToDistance = from.distanceTo(to);\n const Nfaces = faceList ? faceList.length : faces.length;\n const result = this.result;\n\n for (let j = 0; !result.shouldStop && j < Nfaces; j++) {\n const fi = faceList ? faceList[j] : j;\n const face = faces[fi];\n const faceNormal = normals[fi];\n const q = quat;\n const x = position; // determine if ray intersects the plane of the face\n // note: this works regardless of the direction of the face normal\n // Get plane point in world coordinates...\n\n vector.copy(vertices[face[0]]);\n q.vmult(vector, vector);\n vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.\n\n vector.vsub(from, vector); // Get plane normal\n\n q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting\n\n const dot = direction.dot(normal); // Bail out if ray and plane are parallel\n\n if (Math.abs(dot) < this.precision) {\n continue;\n } // calc distance to plane\n\n\n const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray\n\n if (scalar < 0) {\n continue;\n } // if (dot < 0) {\n // Intersection point is from + direction * scalar\n\n\n direction.scale(scalar, intersectPoint);\n intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.\n\n a.copy(vertices[face[0]]);\n q.vmult(a, a);\n x.vadd(a, a);\n\n for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {\n // Transform 3 vertices to world coords\n b.copy(vertices[face[i]]);\n c.copy(vertices[face[i + 1]]);\n q.vmult(b, b);\n q.vmult(c, c);\n x.vadd(b, b);\n x.vadd(c, c);\n const distance = intersectPoint.distanceTo(from);\n\n if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {\n continue;\n }\n\n this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);\n } // }\n\n }\n }\n /**\n * @todo Optimize by transforming the world to local space first.\n * @todo Use Octree lookup\n */\n\n\n _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {\n const normal = intersectTrimesh_normal;\n const triangles = intersectTrimesh_triangles;\n const treeTransform = intersectTrimesh_treeTransform;\n const vector = intersectConvex_vector;\n const localDirection = intersectTrimesh_localDirection;\n const localFrom = intersectTrimesh_localFrom;\n const localTo = intersectTrimesh_localTo;\n const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;\n const worldNormal = intersectTrimesh_worldNormal; // Checking faces\n\n const indices = mesh.indices;\n mesh.vertices; // const normals = mesh.faceNormals\n\n const from = this.from;\n const to = this.to;\n const direction = this.direction;\n treeTransform.position.copy(position);\n treeTransform.quaternion.copy(quat); // Transform ray to local space!\n\n Transform.vectorToLocalFrame(position, quat, direction, localDirection);\n Transform.pointToLocalFrame(position, quat, from, localFrom);\n Transform.pointToLocalFrame(position, quat, to, localTo);\n localTo.x *= mesh.scale.x;\n localTo.y *= mesh.scale.y;\n localTo.z *= mesh.scale.z;\n localFrom.x *= mesh.scale.x;\n localFrom.y *= mesh.scale.y;\n localFrom.z *= mesh.scale.z;\n localTo.vsub(localFrom, localDirection);\n localDirection.normalize();\n const fromToDistanceSquared = localFrom.distanceSquared(localTo);\n mesh.tree.rayQuery(this, treeTransform, triangles);\n\n for (let i = 0, N = triangles.length; !this.result.shouldStop && i !== N; i++) {\n const trianglesIndex = triangles[i];\n mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face\n // note: this works regardless of the direction of the face normal\n // Get plane point in world coordinates...\n\n mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.\n\n a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting\n\n const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel\n // if (Math.abs( dot ) < this.precision){\n // continue;\n // }\n // calc distance to plane\n\n const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray\n\n if (scalar < 0) {\n continue;\n } // Intersection point is from + direction * scalar\n\n\n localDirection.scale(scalar, intersectPoint);\n intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices\n\n mesh.getVertex(indices[trianglesIndex * 3 + 1], b);\n mesh.getVertex(indices[trianglesIndex * 3 + 2], c);\n const squaredDistance = intersectPoint.distanceSquared(localFrom);\n\n if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {\n continue;\n } // transform intersectpoint and normal to world\n\n\n Transform.vectorToWorldFrame(quat, normal, worldNormal);\n Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);\n this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);\n }\n\n triangles.length = 0;\n }\n /**\n * @return True if the intersections should continue\n */\n\n\n reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {\n const from = this.from;\n const to = this.to;\n const distance = from.distanceTo(hitPointWorld);\n const result = this.result; // Skip back faces?\n\n if (this.skipBackfaces && normal.dot(this.direction) > 0) {\n return;\n }\n\n result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;\n\n switch (this.mode) {\n case Ray.ALL:\n this.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n result.hasHit = true;\n this.callback(result);\n break;\n\n case Ray.CLOSEST:\n // Store if closer than current closest\n if (distance < result.distance || !result.hasHit) {\n this.hasHit = true;\n result.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n }\n\n break;\n\n case Ray.ANY:\n // Report and stop.\n this.hasHit = true;\n result.hasHit = true;\n result.set(from, to, normal, hitPointWorld, shape, body, distance);\n result.shouldStop = true;\n break;\n }\n }\n /**\n * As per \"Barycentric Technique\" as named\n * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division\n */\n\n\n static pointInTriangle(p, a, b, c) {\n c.vsub(a, v0);\n b.vsub(a, v1);\n p.vsub(a, v2);\n const dot00 = v0.dot(v0);\n const dot01 = v0.dot(v1);\n const dot02 = v0.dot(v2);\n const dot11 = v1.dot(v1);\n const dot12 = v1.dot(v2);\n let u;\n let v;\n return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;\n }\n\n}\nRay.CLOSEST = RAY_MODES.CLOSEST;\nRay.ANY = RAY_MODES.ANY;\nRay.ALL = RAY_MODES.ALL;\nconst tmpAABB$1 = new AABB();\nconst tmpArray = [];\nconst v1 = new Vec3();\nconst v2 = new Vec3();\nconst intersectBody_xi = new Vec3();\nconst intersectBody_qi = new Quaternion();\nconst intersectPoint = new Vec3();\nconst a = new Vec3();\nconst b = new Vec3();\nconst c = new Vec3();\nnew Vec3();\nnew RaycastResult();\nconst intersectConvexOptions = {\n faceList: [0]\n};\nconst worldPillarOffset = new Vec3();\nconst intersectHeightfield_localRay = new Ray();\nconst intersectHeightfield_index = [];\nconst Ray_intersectSphere_intersectionPoint = new Vec3();\nconst Ray_intersectSphere_normal = new Vec3();\nconst intersectConvex_normal = new Vec3();\nconst intersectConvex_minDistNormal = new Vec3();\nconst intersectConvex_minDistIntersect = new Vec3();\nconst intersectConvex_vector = new Vec3();\nconst intersectTrimesh_normal = new Vec3();\nconst intersectTrimesh_localDirection = new Vec3();\nconst intersectTrimesh_localFrom = new Vec3();\nconst intersectTrimesh_localTo = new Vec3();\nconst intersectTrimesh_worldNormal = new Vec3();\nconst intersectTrimesh_worldIntersectPoint = new Vec3();\nnew AABB();\nconst intersectTrimesh_triangles = [];\nconst intersectTrimesh_treeTransform = new Transform();\nconst v0 = new Vec3();\nconst intersect = new Vec3();\n\nfunction distanceFromIntersection(from, direction, position) {\n // v0 is vector from from to position\n position.vsub(from, v0);\n const dot = v0.dot(direction); // intersect = direction*dot + from\n\n direction.scale(dot, intersect);\n intersect.vadd(from, intersect);\n const distance = position.distanceTo(intersect);\n return distance;\n}\n\n/**\n * Sweep and prune broadphase along one axis.\n */\nclass SAPBroadphase extends Broadphase {\n /**\n * List of bodies currently in the broadphase.\n */\n\n /**\n * The world to search in.\n */\n\n /**\n * Axis to sort the bodies along.\n * Set to 0 for x axis, and 1 for y axis.\n * For best performance, pick the axis where bodies are most distributed.\n */\n\n /**\n * Check if the bounds of two bodies overlap, along the given SAP axis.\n */\n static checkBounds(bi, bj, axisIndex) {\n let biPos;\n let bjPos;\n\n if (axisIndex === 0) {\n biPos = bi.position.x;\n bjPos = bj.position.x;\n } else if (axisIndex === 1) {\n biPos = bi.position.y;\n bjPos = bj.position.y;\n } else if (axisIndex === 2) {\n biPos = bi.position.z;\n bjPos = bj.position.z;\n }\n\n const ri = bi.boundingRadius,\n rj = bj.boundingRadius,\n boundA2 = biPos + ri,\n boundB1 = bjPos - rj;\n return boundB1 < boundA2;\n } // Note: these are identical, save for x/y/z lowerbound\n\n /**\n * insertionSortX\n */\n\n\n static insertionSortX(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n /**\n * insertionSortY\n */\n\n\n static insertionSortY(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n /**\n * insertionSortZ\n */\n\n\n static insertionSortZ(a) {\n for (let i = 1, l = a.length; i < l; i++) {\n const v = a[i];\n let j;\n\n for (j = i - 1; j >= 0; j--) {\n if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {\n break;\n }\n\n a[j + 1] = a[j];\n }\n\n a[j + 1] = v;\n }\n\n return a;\n }\n\n constructor(world) {\n super();\n this.axisList = [];\n this.world = null;\n this.axisIndex = 0;\n const axisList = this.axisList;\n\n this._addBodyHandler = event => {\n axisList.push(event.body);\n };\n\n this._removeBodyHandler = event => {\n const idx = axisList.indexOf(event.body);\n\n if (idx !== -1) {\n axisList.splice(idx, 1);\n }\n };\n\n if (world) {\n this.setWorld(world);\n }\n }\n /**\n * Change the world\n */\n\n\n setWorld(world) {\n // Clear the old axis array\n this.axisList.length = 0; // Add all bodies from the new world\n\n for (let i = 0; i < world.bodies.length; i++) {\n this.axisList.push(world.bodies[i]);\n } // Remove old handlers, if any\n\n\n world.removeEventListener('addBody', this._addBodyHandler);\n world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.\n\n world.addEventListener('addBody', this._addBodyHandler);\n world.addEventListener('removeBody', this._removeBodyHandler);\n this.world = world;\n this.dirty = true;\n }\n /**\n * Collect all collision pairs\n */\n\n\n collisionPairs(world, p1, p2) {\n const bodies = this.axisList;\n const N = bodies.length;\n const axisIndex = this.axisIndex;\n let i;\n let j;\n\n if (this.dirty) {\n this.sortList();\n this.dirty = false;\n } // Look through the list\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n for (j = i + 1; j < N; j++) {\n const bj = bodies[j];\n\n if (!this.needBroadphaseCollision(bi, bj)) {\n continue;\n }\n\n if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {\n break;\n }\n\n this.intersectionTest(bi, bj, p1, p2);\n }\n }\n }\n\n sortList() {\n const axisList = this.axisList;\n const axisIndex = this.axisIndex;\n const N = axisList.length; // Update AABBs\n\n for (let i = 0; i !== N; i++) {\n const bi = axisList[i];\n\n if (bi.aabbNeedsUpdate) {\n bi.updateAABB();\n }\n } // Sort the list\n\n\n if (axisIndex === 0) {\n SAPBroadphase.insertionSortX(axisList);\n } else if (axisIndex === 1) {\n SAPBroadphase.insertionSortY(axisList);\n } else if (axisIndex === 2) {\n SAPBroadphase.insertionSortZ(axisList);\n }\n }\n /**\n * Computes the variance of the body positions and estimates the best axis to use.\n * Will automatically set property `axisIndex`.\n */\n\n\n autoDetectAxis() {\n let sumX = 0;\n let sumX2 = 0;\n let sumY = 0;\n let sumY2 = 0;\n let sumZ = 0;\n let sumZ2 = 0;\n const bodies = this.axisList;\n const N = bodies.length;\n const invN = 1 / N;\n\n for (let i = 0; i !== N; i++) {\n const b = bodies[i];\n const centerX = b.position.x;\n sumX += centerX;\n sumX2 += centerX * centerX;\n const centerY = b.position.y;\n sumY += centerY;\n sumY2 += centerY * centerY;\n const centerZ = b.position.z;\n sumZ += centerZ;\n sumZ2 += centerZ * centerZ;\n }\n\n const varianceX = sumX2 - sumX * sumX * invN;\n const varianceY = sumY2 - sumY * sumY * invN;\n const varianceZ = sumZ2 - sumZ * sumZ * invN;\n\n if (varianceX > varianceY) {\n if (varianceX > varianceZ) {\n this.axisIndex = 0;\n } else {\n this.axisIndex = 2;\n }\n } else if (varianceY > varianceZ) {\n this.axisIndex = 1;\n } else {\n this.axisIndex = 2;\n }\n }\n /**\n * Returns all the bodies within an AABB.\n * @param result An array to store resulting bodies in.\n */\n\n\n aabbQuery(world, aabb, result) {\n if (result === void 0) {\n result = [];\n }\n\n if (this.dirty) {\n this.sortList();\n this.dirty = false;\n }\n\n const axisIndex = this.axisIndex;\n let axis = 'x';\n\n if (axisIndex === 1) {\n axis = 'y';\n }\n\n if (axisIndex === 2) {\n axis = 'z';\n }\n\n const axisList = this.axisList;\n aabb.lowerBound[axis];\n aabb.upperBound[axis];\n\n for (let i = 0; i < axisList.length; i++) {\n const b = axisList[i];\n\n if (b.aabbNeedsUpdate) {\n b.updateAABB();\n }\n\n if (b.aabb.overlaps(aabb)) {\n result.push(b);\n }\n }\n\n return result;\n }\n\n}\n\nclass Utils {\n /**\n * Extend an options object with default values.\n * @param options The options object. May be falsy: in this case, a new object is created and returned.\n * @param defaults An object containing default values.\n * @return The modified options object.\n */\n static defaults(options, defaults) {\n if (options === void 0) {\n options = {};\n }\n\n for (let key in defaults) {\n if (!(key in options)) {\n options[key] = defaults[key];\n }\n }\n\n return options;\n }\n\n}\n\n/**\n * Constraint base class\n */\nclass Constraint {\n /**\n * Equations to be solved in this constraint.\n */\n\n /**\n * Body A.\n */\n\n /**\n * Body B.\n */\n\n /**\n * Set to false if you don't want the bodies to collide when they are connected.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n collideConnected: true,\n wakeUpBodies: true\n });\n this.equations = [];\n this.bodyA = bodyA;\n this.bodyB = bodyB;\n this.id = Constraint.idCounter++;\n this.collideConnected = options.collideConnected;\n\n if (options.wakeUpBodies) {\n if (bodyA) {\n bodyA.wakeUp();\n }\n\n if (bodyB) {\n bodyB.wakeUp();\n }\n }\n }\n /**\n * Update all the equations with data.\n */\n\n\n update() {\n throw new Error('method update() not implmemented in this Constraint subclass!');\n }\n /**\n * Enables all equations in the constraint.\n */\n\n\n enable() {\n const eqs = this.equations;\n\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = true;\n }\n }\n /**\n * Disables all equations in the constraint.\n */\n\n\n disable() {\n const eqs = this.equations;\n\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = false;\n }\n }\n\n}\nConstraint.idCounter = 0;\n\n/**\n * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.\n */\n\nclass JacobianElement {\n /**\n * spatial\n */\n\n /**\n * rotational\n */\n constructor() {\n this.spatial = new Vec3();\n this.rotational = new Vec3();\n }\n /**\n * Multiply with other JacobianElement\n */\n\n\n multiplyElement(element) {\n return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);\n }\n /**\n * Multiply with two vectors\n */\n\n\n multiplyVectors(spatial, rotational) {\n return spatial.dot(this.spatial) + rotational.dot(this.rotational);\n }\n\n}\n\n/**\n * Equation base class.\n *\n * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation.\n */\nclass Equation {\n /**\n * Minimum (read: negative max) force to be applied by the constraint.\n */\n\n /**\n * Maximum (read: positive max) force to be applied by the constraint.\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * SPOOK parameter\n */\n\n /**\n * A number, proportional to the force added to the bodies.\n */\n constructor(bi, bj, minForce, maxForce) {\n if (minForce === void 0) {\n minForce = -1e6;\n }\n\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n this.id = Equation.idCounter++;\n this.minForce = minForce;\n this.maxForce = maxForce;\n this.bi = bi;\n this.bj = bj;\n this.a = 0.0; // SPOOK parameter\n\n this.b = 0.0; // SPOOK parameter\n\n this.eps = 0.0; // SPOOK parameter\n\n this.jacobianElementA = new JacobianElement();\n this.jacobianElementB = new JacobianElement();\n this.enabled = true;\n this.multiplier = 0;\n this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params\n }\n /**\n * Recalculates a, b, and eps.\n *\n * The Equation constructor sets typical SPOOK parameters as such:\n * * `stiffness` = 1e7\n * * `relaxation` = 4\n * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._\n */\n\n\n setSpookParams(stiffness, relaxation, timeStep) {\n const d = relaxation;\n const k = stiffness;\n const h = timeStep;\n this.a = 4.0 / (h * (1 + 4 * d));\n this.b = 4.0 * d / (1 + 4 * d);\n this.eps = 4.0 / (h * h * k * (1 + 4 * d));\n }\n /**\n * Computes the right hand side of the SPOOK equation\n */\n\n\n computeB(a, b, h) {\n const GW = this.computeGW();\n const Gq = this.computeGq();\n const GiMf = this.computeGiMf();\n return -Gq * a - GW * b - GiMf * h;\n }\n /**\n * Computes G*q, where q are the generalized body coordinates\n */\n\n\n computeGq() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const xi = bi.position;\n const xj = bj.position;\n return GA.spatial.dot(xi) + GB.spatial.dot(xj);\n }\n /**\n * Computes G*W, where W are the body velocities\n */\n\n\n computeGW() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const vi = bi.velocity;\n const vj = bj.velocity;\n const wi = bi.angularVelocity;\n const wj = bj.angularVelocity;\n return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);\n }\n /**\n * Computes G*Wlambda, where W are the body velocities\n */\n\n\n computeGWlambda() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const vi = bi.vlambda;\n const vj = bj.vlambda;\n const wi = bi.wlambda;\n const wj = bj.wlambda;\n return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);\n }\n /**\n * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.\n */\n\n\n computeGiMf() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const fi = bi.force;\n const ti = bi.torque;\n const fj = bj.force;\n const tj = bj.torque;\n const invMassi = bi.invMassSolve;\n const invMassj = bj.invMassSolve;\n fi.scale(invMassi, iMfi);\n fj.scale(invMassj, iMfj);\n bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);\n bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);\n return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);\n }\n /**\n * Computes G*inv(M)*G'\n */\n\n\n computeGiMGt() {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const invMassi = bi.invMassSolve;\n const invMassj = bj.invMassSolve;\n const invIi = bi.invInertiaWorldSolve;\n const invIj = bj.invInertiaWorldSolve;\n let result = invMassi + invMassj;\n invIi.vmult(GA.rotational, tmp);\n result += tmp.dot(GA.rotational);\n invIj.vmult(GB.rotational, tmp);\n result += tmp.dot(GB.rotational);\n return result;\n }\n /**\n * Add constraint velocity to the bodies.\n */\n\n\n addToWlambda(deltalambda) {\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const bi = this.bi;\n const bj = this.bj;\n const temp = addToWlambda_temp; // Add to linear velocity\n // v_lambda += inv(M) * delta_lamba * G\n\n bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);\n bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity\n\n bi.invInertiaWorldSolve.vmult(GA.rotational, temp);\n bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);\n bj.invInertiaWorldSolve.vmult(GB.rotational, temp);\n bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);\n }\n /**\n * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps\n */\n\n\n computeC() {\n return this.computeGiMGt() + this.eps;\n }\n\n}\nEquation.idCounter = 0;\nconst iMfi = new Vec3();\nconst iMfj = new Vec3();\nconst invIi_vmult_taui = new Vec3();\nconst invIj_vmult_tauj = new Vec3();\nconst tmp = new Vec3();\nconst addToWlambda_temp = new Vec3();\n\n/**\n * Contact/non-penetration constraint equation\n */\nclass ContactEquation extends Equation {\n /**\n * \"bounciness\": u1 = -e*u0\n */\n\n /**\n * World-oriented vector that goes from the center of bi to the contact point.\n */\n\n /**\n * World-oriented vector that starts in body j position and goes to the contact point.\n */\n\n /**\n * Contact normal, pointing out of body i.\n */\n constructor(bodyA, bodyB, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB, 0, maxForce);\n this.restitution = 0.0;\n this.ri = new Vec3();\n this.rj = new Vec3();\n this.ni = new Vec3();\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const bi = this.bi;\n const bj = this.bj;\n const ri = this.ri;\n const rj = this.rj;\n const rixn = ContactEquation_computeB_temp1;\n const rjxn = ContactEquation_computeB_temp2;\n const vi = bi.velocity;\n const wi = bi.angularVelocity;\n bi.force;\n bi.torque;\n const vj = bj.velocity;\n const wj = bj.angularVelocity;\n bj.force;\n bj.torque;\n const penetrationVec = ContactEquation_computeB_temp3;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n const n = this.ni; // Caluclate cross products\n\n ri.cross(n, rixn);\n rj.cross(n, rjxn); // g = xj+rj -(xi+ri)\n // G = [ -ni -rixn ni rjxn ]\n\n n.negate(GA.spatial);\n rixn.negate(GA.rotational);\n GB.spatial.copy(n);\n GB.rotational.copy(rjxn); // Calculate the penetration vector\n\n penetrationVec.copy(bj.position);\n penetrationVec.vadd(rj, penetrationVec);\n penetrationVec.vsub(bi.position, penetrationVec);\n penetrationVec.vsub(ri, penetrationVec);\n const g = n.dot(penetrationVec); // Compute iteration\n\n const ePlusOne = this.restitution + 1;\n const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n /**\n * Get the current relative velocity in the contact point.\n */\n\n\n getImpactVelocityAlongNormal() {\n const vi = ContactEquation_getImpactVelocityAlongNormal_vi;\n const vj = ContactEquation_getImpactVelocityAlongNormal_vj;\n const xi = ContactEquation_getImpactVelocityAlongNormal_xi;\n const xj = ContactEquation_getImpactVelocityAlongNormal_xj;\n const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;\n this.bi.position.vadd(this.ri, xi);\n this.bj.position.vadd(this.rj, xj);\n this.bi.getVelocityAtWorldPoint(xi, vi);\n this.bj.getVelocityAtWorldPoint(xj, vj);\n vi.vsub(vj, relVel);\n return this.ni.dot(relVel);\n }\n\n}\nconst ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors\n\nconst ContactEquation_computeB_temp2 = new Vec3();\nconst ContactEquation_computeB_temp3 = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();\nconst ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();\n\n/**\n * Connects two bodies at given offset points.\n * @example\n * const bodyA = new Body({ mass: 1 })\n * const bodyB = new Body({ mass: 1 })\n * bodyA.position.set(-1, 0, 0)\n * bodyB.position.set(1, 0, 0)\n * bodyA.addShape(shapeA)\n * bodyB.addShape(shapeB)\n * world.addBody(bodyA)\n * world.addBody(bodyB)\n * const localPivotA = new Vec3(1, 0, 0)\n * const localPivotB = new Vec3(-1, 0, 0)\n * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)\n * world.addConstraint(constraint)\n */\nclass PointToPointConstraint extends Constraint {\n /**\n * Pivot, defined locally in bodyA.\n */\n\n /**\n * Pivot, defined locally in bodyB.\n */\n\n /**\n * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.\n * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.\n * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.\n * @param maxForce The maximum force that should be applied to constrain the bodies.\n */\n constructor(bodyA, pivotA, bodyB, pivotB, maxForce) {\n if (pivotA === void 0) {\n pivotA = new Vec3();\n }\n\n if (pivotB === void 0) {\n pivotB = new Vec3();\n }\n\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB);\n this.pivotA = pivotA.clone();\n this.pivotB = pivotB.clone();\n const x = this.equationX = new ContactEquation(bodyA, bodyB);\n const y = this.equationY = new ContactEquation(bodyA, bodyB);\n const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver\n\n this.equations.push(x, y, z); // Make the equations bidirectional\n\n x.minForce = y.minForce = z.minForce = -maxForce;\n x.maxForce = y.maxForce = z.maxForce = maxForce;\n x.ni.set(1, 0, 0);\n y.ni.set(0, 1, 0);\n z.ni.set(0, 0, 1);\n }\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const x = this.equationX;\n const y = this.equationY;\n const z = this.equationZ; // Rotate the pivots to world space\n\n bodyA.quaternion.vmult(this.pivotA, x.ri);\n bodyB.quaternion.vmult(this.pivotB, x.rj);\n y.ri.copy(x.ri);\n y.rj.copy(x.rj);\n z.ri.copy(x.ri);\n z.rj.copy(x.rj);\n }\n\n}\n\n/**\n * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.\n */\nclass ConeEquation extends Equation {\n /**\n * Local axis in A\n */\n\n /**\n * Local axis in B\n */\n\n /**\n * The \"cone angle\" to keep\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);\n this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const ni = this.axisA;\n const nj = this.axisB;\n const nixnj = tmpVec1$2;\n const njxni = tmpVec2$2;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // Caluclate cross products\n\n ni.cross(nj, nixnj);\n nj.cross(ni, njxni); // The angle between two vector is:\n // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b\n // g = a * b\n // gdot = (b x a) * wi + (a x b) * wj\n // G = [0 bxa 0 axb]\n // W = [vi wi vj wj]\n\n GA.rotational.copy(njxni);\n GB.rotational.copy(nixnj);\n const g = Math.cos(this.angle) - ni.dot(nj);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n\n}\nconst tmpVec1$2 = new Vec3();\nconst tmpVec2$2 = new Vec3();\n\n/**\n * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.\n */\nclass RotationalEquation extends Equation {\n /**\n * World oriented rotational axis.\n */\n\n /**\n * World oriented rotational axis.\n */\n\n /**\n * maxAngle\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);\n this.maxAngle = Math.PI / 2;\n }\n\n computeB(h) {\n const a = this.a;\n const b = this.b;\n const ni = this.axisA;\n const nj = this.axisB;\n const nixnj = tmpVec1$1;\n const njxni = tmpVec2$1;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // Caluclate cross products\n\n ni.cross(nj, nixnj);\n nj.cross(ni, njxni); // g = ni * nj\n // gdot = (nj x ni) * wi + (ni x nj) * wj\n // G = [0 njxni 0 nixnj]\n // W = [vi wi vj wj]\n\n GA.rotational.copy(njxni);\n GB.rotational.copy(nixnj);\n const g = Math.cos(this.maxAngle) - ni.dot(nj);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -g * a - GW * b - h * GiMf;\n return B;\n }\n\n}\nconst tmpVec1$1 = new Vec3();\nconst tmpVec2$1 = new Vec3();\n\n/**\n * A Cone Twist constraint, useful for ragdolls.\n */\nclass ConeTwistConstraint extends PointToPointConstraint {\n /**\n * The axis direction for the constraint of the body A.\n */\n\n /**\n * The axis direction for the constraint of the body B.\n */\n\n /**\n * The aperture angle of the cone.\n */\n\n /**\n * The twist angle of the joint.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between\n\n const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();\n const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();\n super(bodyA, pivotA, bodyB, pivotB, maxForce);\n this.axisA = options.axisA ? options.axisA.clone() : new Vec3();\n this.axisB = options.axisB ? options.axisB.clone() : new Vec3();\n this.collideConnected = !!options.collideConnected;\n this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;\n const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);\n const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);\n this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward\n\n c.maxForce = 0;\n c.minForce = -maxForce; // Make the twist equation add torque toward the initial position\n\n t.maxForce = 0;\n t.minForce = -maxForce;\n this.equations.push(c, t);\n }\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const cone = this.coneEquation;\n const twist = this.twistEquation;\n super.update(); // Update the axes to the cone constraint\n\n bodyA.vectorToWorldFrame(this.axisA, cone.axisA);\n bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint\n\n this.axisA.tangents(twist.axisA, twist.axisA);\n bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);\n this.axisB.tangents(twist.axisB, twist.axisB);\n bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);\n cone.angle = this.angle;\n twist.maxAngle = this.twistAngle;\n }\n\n}\nnew Vec3();\nnew Vec3();\n\n/**\n * Constrains two bodies to be at a constant distance from each others center of mass.\n */\nclass DistanceConstraint extends Constraint {\n /**\n * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB\n */\n\n /**\n * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.\n * @param maxForce The maximum force that should be applied to constrain the bodies.\n */\n constructor(bodyA, bodyB, distance, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB);\n\n if (typeof distance === 'undefined') {\n distance = bodyA.position.distanceTo(bodyB.position);\n }\n\n this.distance = distance;\n const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);\n this.equations.push(eq); // Make it bidirectional\n\n eq.minForce = -maxForce;\n eq.maxForce = maxForce;\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const eq = this.distanceEquation;\n const halfDist = this.distance * 0.5;\n const normal = eq.ni;\n bodyB.position.vsub(bodyA.position, normal);\n normal.normalize();\n normal.scale(halfDist, eq.ri);\n normal.scale(-halfDist, eq.rj);\n }\n\n}\n\n/**\n * Lock constraint. Will remove all degrees of freedom between the bodies.\n */\nclass LockConstraint extends PointToPointConstraint {\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between\n\n const pivotA = new Vec3();\n const pivotB = new Vec3();\n const halfWay = new Vec3();\n bodyA.position.vadd(bodyB.position, halfWay);\n halfWay.scale(0.5, halfWay);\n bodyB.pointToLocalFrame(halfWay, pivotB);\n bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies\n\n super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces\n\n this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);\n this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);\n this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);\n this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);\n this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);\n this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place\n\n const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);\n const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);\n const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);\n this.equations.push(r1, r2, r3);\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n this.motorEquation;\n const r1 = this.rotationalEquation1;\n const r2 = this.rotationalEquation2;\n const r3 = this.rotationalEquation3;\n LockConstraint_update_tmpVec1;\n LockConstraint_update_tmpVec2;\n super.update(); // These vector pairs must be orthogonal\n\n bodyA.vectorToWorldFrame(this.xA, r1.axisA);\n bodyB.vectorToWorldFrame(this.yB, r1.axisB);\n bodyA.vectorToWorldFrame(this.yA, r2.axisA);\n bodyB.vectorToWorldFrame(this.zB, r2.axisB);\n bodyA.vectorToWorldFrame(this.zA, r3.axisA);\n bodyB.vectorToWorldFrame(this.xB, r3.axisB);\n }\n\n}\nconst LockConstraint_update_tmpVec1 = new Vec3();\nconst LockConstraint_update_tmpVec2 = new Vec3();\n\n/**\n * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.\n */\nclass RotationalMotorEquation extends Equation {\n /**\n * World oriented rotational axis.\n */\n\n /**\n * World oriented rotational axis.\n */\n\n /**\n * Motor velocity.\n */\n constructor(bodyA, bodyB, maxForce) {\n if (maxForce === void 0) {\n maxForce = 1e6;\n }\n\n super(bodyA, bodyB, -maxForce, maxForce);\n this.axisA = new Vec3();\n this.axisB = new Vec3();\n this.targetVelocity = 0;\n }\n\n computeB(h) {\n this.a;\n const b = this.b;\n this.bi;\n this.bj;\n const axisA = this.axisA;\n const axisB = this.axisB;\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB; // g = 0\n // gdot = axisA * wi - axisB * wj\n // gdot = G * W = G * [vi wi vj wj]\n // =>\n // G = [0 axisA 0 -axisB]\n\n GA.rotational.copy(axisA);\n axisB.negate(GB.rotational);\n const GW = this.computeGW() - this.targetVelocity;\n const GiMf = this.computeGiMf();\n const B = -GW * b - h * GiMf;\n return B;\n }\n\n}\n\n/**\n * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.\n */\nclass HingeConstraint extends PointToPointConstraint {\n /**\n * Rotation axis, defined locally in bodyA.\n */\n\n /**\n * Rotation axis, defined locally in bodyB.\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;\n const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();\n const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();\n super(bodyA, pivotA, bodyB, pivotB, maxForce);\n const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);\n axisA.normalize();\n const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);\n axisB.normalize();\n this.collideConnected = !!options.collideConnected;\n const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);\n const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);\n const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);\n motor.enabled = false; // Not enabled by default\n // Equations to be fed to the solver\n\n this.equations.push(rotational1, rotational2, motor);\n }\n /**\n * enableMotor\n */\n\n\n enableMotor() {\n this.motorEquation.enabled = true;\n }\n /**\n * disableMotor\n */\n\n\n disableMotor() {\n this.motorEquation.enabled = false;\n }\n /**\n * setMotorSpeed\n */\n\n\n setMotorSpeed(speed) {\n this.motorEquation.targetVelocity = speed;\n }\n /**\n * setMotorMaxForce\n */\n\n\n setMotorMaxForce(maxForce) {\n this.motorEquation.maxForce = maxForce;\n this.motorEquation.minForce = -maxForce;\n }\n /**\n * update\n */\n\n\n update() {\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const motor = this.motorEquation;\n const r1 = this.rotationalEquation1;\n const r2 = this.rotationalEquation2;\n const worldAxisA = HingeConstraint_update_tmpVec1;\n const worldAxisB = HingeConstraint_update_tmpVec2;\n const axisA = this.axisA;\n const axisB = this.axisB;\n super.update(); // Get world axes\n\n bodyA.quaternion.vmult(axisA, worldAxisA);\n bodyB.quaternion.vmult(axisB, worldAxisB);\n worldAxisA.tangents(r1.axisA, r2.axisA);\n r1.axisB.copy(worldAxisB);\n r2.axisB.copy(worldAxisB);\n\n if (this.motorEquation.enabled) {\n bodyA.quaternion.vmult(this.axisA, motor.axisA);\n bodyB.quaternion.vmult(this.axisB, motor.axisB);\n }\n }\n\n}\nconst HingeConstraint_update_tmpVec1 = new Vec3();\nconst HingeConstraint_update_tmpVec2 = new Vec3();\n\n/**\n * Constrains the slipping in a contact along a tangent\n */\nclass FrictionEquation extends Equation {\n // Tangent\n\n /**\n * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g\n */\n constructor(bodyA, bodyB, slipForce) {\n super(bodyA, bodyB, -slipForce, slipForce);\n this.ri = new Vec3();\n this.rj = new Vec3();\n this.t = new Vec3();\n }\n\n computeB(h) {\n this.a;\n const b = this.b;\n this.bi;\n this.bj;\n const ri = this.ri;\n const rj = this.rj;\n const rixt = FrictionEquation_computeB_temp1;\n const rjxt = FrictionEquation_computeB_temp2;\n const t = this.t; // Caluclate cross products\n\n ri.cross(t, rixt);\n rj.cross(t, rjxt); // G = [-t -rixt t rjxt]\n // And remember, this is a pure velocity constraint, g is always zero!\n\n const GA = this.jacobianElementA;\n const GB = this.jacobianElementB;\n t.negate(GA.spatial);\n rixt.negate(GA.rotational);\n GB.spatial.copy(t);\n GB.rotational.copy(rjxt);\n const GW = this.computeGW();\n const GiMf = this.computeGiMf();\n const B = -GW * b - h * GiMf;\n return B;\n }\n\n}\nconst FrictionEquation_computeB_temp1 = new Vec3();\nconst FrictionEquation_computeB_temp2 = new Vec3();\n\n/**\n * Defines what happens when two materials meet.\n * @todo Refactor materials to materialA and materialB\n */\nclass ContactMaterial {\n /**\n * Identifier of this material.\n */\n\n /**\n * Participating materials.\n */\n\n /**\n * Friction coefficient.\n * @default 0.3\n */\n\n /**\n * Restitution coefficient.\n * @default 0.3\n */\n\n /**\n * Stiffness of the produced contact equations.\n * @default 1e7\n */\n\n /**\n * Relaxation time of the produced contact equations.\n * @default 3\n */\n\n /**\n * Stiffness of the produced friction equations.\n * @default 1e7\n */\n\n /**\n * Relaxation time of the produced friction equations\n * @default 3\n */\n constructor(m1, m2, options) {\n options = Utils.defaults(options, {\n friction: 0.3,\n restitution: 0.3,\n contactEquationStiffness: 1e7,\n contactEquationRelaxation: 3,\n frictionEquationStiffness: 1e7,\n frictionEquationRelaxation: 3\n });\n this.id = ContactMaterial.idCounter++;\n this.materials = [m1, m2];\n this.friction = options.friction;\n this.restitution = options.restitution;\n this.contactEquationStiffness = options.contactEquationStiffness;\n this.contactEquationRelaxation = options.contactEquationRelaxation;\n this.frictionEquationStiffness = options.frictionEquationStiffness;\n this.frictionEquationRelaxation = options.frictionEquationRelaxation;\n }\n\n}\nContactMaterial.idCounter = 0;\n\n/**\n * Defines a physics material.\n */\nclass Material {\n /**\n * Material name.\n * If options is a string, name will be set to that string.\n * @todo Deprecate this\n */\n\n /** Material id. */\n\n /**\n * Friction for this material.\n * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.\n */\n\n /**\n * Restitution for this material.\n * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n let name = ''; // Backwards compatibility fix\n\n if (typeof options === 'string') {\n //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)\n name = options;\n options = {};\n }\n\n this.name = name;\n this.id = Material.idCounter++;\n this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;\n this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;\n }\n\n}\nMaterial.idCounter = 0;\n\n/**\n * A spring, connecting two bodies.\n * @example\n * const spring = new Spring(boxBody, sphereBody, {\n * restLength: 0,\n * stiffness: 50,\n * damping: 1,\n * })\n *\n * // Compute the force after each step\n * world.addEventListener('postStep', (event) => {\n * spring.applyForce()\n * })\n */\nclass Spring {\n /**\n * Rest length of the spring. A number > 0.\n * @default 1\n */\n\n /**\n * Stiffness of the spring. A number >= 0.\n * @default 100\n */\n\n /**\n * Damping of the spring. A number >= 0.\n * @default 1\n */\n\n /**\n * First connected body.\n */\n\n /**\n * Second connected body.\n */\n\n /**\n * Anchor for bodyA in local bodyA coordinates.\n * Where to hook the spring to body A, in local body coordinates.\n * @default new Vec3()\n */\n\n /**\n * Anchor for bodyB in local bodyB coordinates.\n * Where to hook the spring to body B, in local body coordinates.\n * @default new Vec3()\n */\n constructor(bodyA, bodyB, options) {\n if (options === void 0) {\n options = {};\n }\n\n this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;\n this.stiffness = options.stiffness || 100;\n this.damping = options.damping || 1;\n this.bodyA = bodyA;\n this.bodyB = bodyB;\n this.localAnchorA = new Vec3();\n this.localAnchorB = new Vec3();\n\n if (options.localAnchorA) {\n this.localAnchorA.copy(options.localAnchorA);\n }\n\n if (options.localAnchorB) {\n this.localAnchorB.copy(options.localAnchorB);\n }\n\n if (options.worldAnchorA) {\n this.setWorldAnchorA(options.worldAnchorA);\n }\n\n if (options.worldAnchorB) {\n this.setWorldAnchorB(options.worldAnchorB);\n }\n }\n /**\n * Set the anchor point on body A, using world coordinates.\n */\n\n\n setWorldAnchorA(worldAnchorA) {\n this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);\n }\n /**\n * Set the anchor point on body B, using world coordinates.\n */\n\n\n setWorldAnchorB(worldAnchorB) {\n this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);\n }\n /**\n * Get the anchor point on body A, in world coordinates.\n * @param result The vector to store the result in.\n */\n\n\n getWorldAnchorA(result) {\n this.bodyA.pointToWorldFrame(this.localAnchorA, result);\n }\n /**\n * Get the anchor point on body B, in world coordinates.\n * @param result The vector to store the result in.\n */\n\n\n getWorldAnchorB(result) {\n this.bodyB.pointToWorldFrame(this.localAnchorB, result);\n }\n /**\n * Apply the spring force to the connected bodies.\n */\n\n\n applyForce() {\n const k = this.stiffness;\n const d = this.damping;\n const l = this.restLength;\n const bodyA = this.bodyA;\n const bodyB = this.bodyB;\n const r = applyForce_r;\n const r_unit = applyForce_r_unit;\n const u = applyForce_u;\n const f = applyForce_f;\n const tmp = applyForce_tmp;\n const worldAnchorA = applyForce_worldAnchorA;\n const worldAnchorB = applyForce_worldAnchorB;\n const ri = applyForce_ri;\n const rj = applyForce_rj;\n const ri_x_f = applyForce_ri_x_f;\n const rj_x_f = applyForce_rj_x_f; // Get world anchors\n\n this.getWorldAnchorA(worldAnchorA);\n this.getWorldAnchorB(worldAnchorB); // Get offset points\n\n worldAnchorA.vsub(bodyA.position, ri);\n worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points\n\n worldAnchorB.vsub(worldAnchorA, r);\n const rlen = r.length();\n r_unit.copy(r);\n r_unit.normalize(); // Compute relative velocity of the anchor points, u\n\n bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity\n\n bodyB.angularVelocity.cross(rj, tmp);\n u.vadd(tmp, u);\n bodyA.angularVelocity.cross(ri, tmp);\n u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )\n\n r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies\n\n bodyA.force.vsub(f, bodyA.force);\n bodyB.force.vadd(f, bodyB.force); // Angular force\n\n ri.cross(f, ri_x_f);\n rj.cross(f, rj_x_f);\n bodyA.torque.vsub(ri_x_f, bodyA.torque);\n bodyB.torque.vadd(rj_x_f, bodyB.torque);\n }\n\n}\nconst applyForce_r = new Vec3();\nconst applyForce_r_unit = new Vec3();\nconst applyForce_u = new Vec3();\nconst applyForce_f = new Vec3();\nconst applyForce_worldAnchorA = new Vec3();\nconst applyForce_worldAnchorB = new Vec3();\nconst applyForce_ri = new Vec3();\nconst applyForce_rj = new Vec3();\nconst applyForce_ri_x_f = new Vec3();\nconst applyForce_rj_x_f = new Vec3();\nconst applyForce_tmp = new Vec3();\n\n/**\n * WheelInfo\n */\nclass WheelInfo {\n /**\n * Max travel distance of the suspension, in meters.\n * @default 1\n */\n\n /**\n * Speed to apply to the wheel rotation when the wheel is sliding.\n * @default -0.1\n */\n\n /**\n * If the customSlidingRotationalSpeed should be used.\n * @default false\n */\n\n /**\n * sliding\n */\n\n /**\n * Connection point, defined locally in the chassis body frame.\n */\n\n /**\n * chassisConnectionPointWorld\n */\n\n /**\n * directionLocal\n */\n\n /**\n * directionWorld\n */\n\n /**\n * axleLocal\n */\n\n /**\n * axleWorld\n */\n\n /**\n * suspensionRestLength\n * @default 1\n */\n\n /**\n * suspensionMaxLength\n * @default 2\n */\n\n /**\n * radius\n * @default 1\n */\n\n /**\n * suspensionStiffness\n * @default 100\n */\n\n /**\n * dampingCompression\n * @default 10\n */\n\n /**\n * dampingRelaxation\n * @default 10\n */\n\n /**\n * frictionSlip\n * @default 10.5\n */\n\n /** forwardAcceleration */\n\n /** sideAcceleration */\n\n /**\n * steering\n * @default 0\n */\n\n /**\n * Rotation value, in radians.\n * @default 0\n */\n\n /**\n * deltaRotation\n * @default 0\n */\n\n /**\n * rollInfluence\n * @default 0.01\n */\n\n /**\n * maxSuspensionForce\n */\n\n /**\n * engineForce\n */\n\n /**\n * brake\n */\n\n /**\n * isFrontWheel\n * @default true\n */\n\n /**\n * clippedInvContactDotSuspension\n * @default 1\n */\n\n /**\n * suspensionRelativeVelocity\n * @default 0\n */\n\n /**\n * suspensionForce\n * @default 0\n */\n\n /**\n * slipInfo\n */\n\n /**\n * skidInfo\n * @default 0\n */\n\n /**\n * suspensionLength\n * @default 0\n */\n\n /**\n * sideImpulse\n */\n\n /**\n * forwardImpulse\n */\n\n /**\n * The result from raycasting.\n */\n\n /**\n * Wheel world transform.\n */\n\n /**\n * isInContact\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n chassisConnectionPointLocal: new Vec3(),\n chassisConnectionPointWorld: new Vec3(),\n directionLocal: new Vec3(),\n directionWorld: new Vec3(),\n axleLocal: new Vec3(),\n axleWorld: new Vec3(),\n suspensionRestLength: 1,\n suspensionMaxLength: 2,\n radius: 1,\n suspensionStiffness: 100,\n dampingCompression: 10,\n dampingRelaxation: 10,\n frictionSlip: 10.5,\n forwardAcceleration: 1,\n sideAcceleration: 1,\n steering: 0,\n rotation: 0,\n deltaRotation: 0,\n rollInfluence: 0.01,\n maxSuspensionForce: Number.MAX_VALUE,\n isFrontWheel: true,\n clippedInvContactDotSuspension: 1,\n suspensionRelativeVelocity: 0,\n suspensionForce: 0,\n slipInfo: 0,\n skidInfo: 0,\n suspensionLength: 0,\n maxSuspensionTravel: 1,\n useCustomSlidingRotationalSpeed: false,\n customSlidingRotationalSpeed: -0.1\n });\n this.maxSuspensionTravel = options.maxSuspensionTravel;\n this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;\n this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;\n this.sliding = false;\n this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();\n this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();\n this.directionLocal = options.directionLocal.clone();\n this.directionWorld = options.directionWorld.clone();\n this.axleLocal = options.axleLocal.clone();\n this.axleWorld = options.axleWorld.clone();\n this.suspensionRestLength = options.suspensionRestLength;\n this.suspensionMaxLength = options.suspensionMaxLength;\n this.radius = options.radius;\n this.suspensionStiffness = options.suspensionStiffness;\n this.dampingCompression = options.dampingCompression;\n this.dampingRelaxation = options.dampingRelaxation;\n this.frictionSlip = options.frictionSlip;\n this.forwardAcceleration = options.forwardAcceleration;\n this.sideAcceleration = options.sideAcceleration;\n this.steering = 0;\n this.rotation = 0;\n this.deltaRotation = 0;\n this.rollInfluence = options.rollInfluence;\n this.maxSuspensionForce = options.maxSuspensionForce;\n this.engineForce = 0;\n this.brake = 0;\n this.isFrontWheel = options.isFrontWheel;\n this.clippedInvContactDotSuspension = 1;\n this.suspensionRelativeVelocity = 0;\n this.suspensionForce = 0;\n this.slipInfo = 0;\n this.skidInfo = 0;\n this.suspensionLength = 0;\n this.sideImpulse = 0;\n this.forwardImpulse = 0;\n this.raycastResult = new RaycastResult();\n this.worldTransform = new Transform();\n this.isInContact = false;\n }\n\n updateWheel(chassis) {\n const raycastResult = this.raycastResult;\n\n if (this.isInContact) {\n const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);\n raycastResult.hitPointWorld.vsub(chassis.position, relpos);\n chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);\n const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);\n\n if (project >= -0.1) {\n this.suspensionRelativeVelocity = 0.0;\n this.clippedInvContactDotSuspension = 1.0 / 0.1;\n } else {\n const inv = -1 / project;\n this.suspensionRelativeVelocity = projVel * inv;\n this.clippedInvContactDotSuspension = inv;\n }\n } else {\n // Not in contact : position wheel in a nice (rest length) position\n raycastResult.suspensionLength = this.suspensionRestLength;\n this.suspensionRelativeVelocity = 0.0;\n raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);\n this.clippedInvContactDotSuspension = 1.0;\n }\n }\n\n}\nconst chassis_velocity_at_contactPoint = new Vec3();\nconst relpos = new Vec3();\n\n/**\n * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.\n */\nclass RaycastVehicle {\n /** The car chassis body. */\n\n /** The wheels. */\n\n /** Will be set to true if the car is sliding. */\n\n /** Index of the right axis. x=0, y=1, z=2 */\n\n /** Index of the forward axis. x=0, y=1, z=2 */\n\n /** Index of the up axis. x=0, y=1, z=2 */\n\n /** The constraints. */\n\n /** Optional pre-step callback. */\n\n /** Number of wheels on the ground. */\n constructor(options) {\n this.chassisBody = options.chassisBody;\n this.wheelInfos = [];\n this.sliding = false;\n this.world = null;\n this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;\n this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;\n this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;\n this.constraints = [];\n\n this.preStepCallback = () => {};\n\n this.currentVehicleSpeedKmHour = 0;\n this.numWheelsOnGround = 0;\n }\n /**\n * Add a wheel. For information about the options, see `WheelInfo`.\n */\n\n\n addWheel(options) {\n if (options === void 0) {\n options = {};\n }\n\n const info = new WheelInfo(options);\n const index = this.wheelInfos.length;\n this.wheelInfos.push(info);\n return index;\n }\n /**\n * Set the steering value of a wheel.\n */\n\n\n setSteeringValue(value, wheelIndex) {\n const wheel = this.wheelInfos[wheelIndex];\n wheel.steering = value;\n }\n /**\n * Set the wheel force to apply on one of the wheels each time step\n */\n\n\n applyEngineForce(value, wheelIndex) {\n this.wheelInfos[wheelIndex].engineForce = value;\n }\n /**\n * Set the braking force of a wheel\n */\n\n\n setBrake(brake, wheelIndex) {\n this.wheelInfos[wheelIndex].brake = brake;\n }\n /**\n * Add the vehicle including its constraints to the world.\n */\n\n\n addToWorld(world) {\n world.addBody(this.chassisBody);\n const that = this;\n\n this.preStepCallback = () => {\n that.updateVehicle(world.dt);\n };\n\n world.addEventListener('preStep', this.preStepCallback);\n this.world = world;\n }\n /**\n * Get one of the wheel axles, world-oriented.\n */\n\n\n getVehicleAxisWorld(axisIndex, result) {\n result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);\n this.chassisBody.vectorToWorldFrame(result, result);\n }\n\n updateVehicle(timeStep) {\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n const chassisBody = this.chassisBody;\n\n for (let i = 0; i < numWheels; i++) {\n this.updateWheelTransform(i);\n }\n\n this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();\n const forwardWorld = new Vec3();\n this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);\n\n if (forwardWorld.dot(chassisBody.velocity) < 0) {\n this.currentVehicleSpeedKmHour *= -1;\n } // simulate suspension\n\n\n for (let i = 0; i < numWheels; i++) {\n this.castRay(wheelInfos[i]);\n }\n\n this.updateSuspension(timeStep);\n const impulse = new Vec3();\n const relpos = new Vec3();\n\n for (let i = 0; i < numWheels; i++) {\n //apply suspension force\n const wheel = wheelInfos[i];\n let suspensionForce = wheel.suspensionForce;\n\n if (suspensionForce > wheel.maxSuspensionForce) {\n suspensionForce = wheel.maxSuspensionForce;\n }\n\n wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);\n wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);\n chassisBody.applyImpulse(impulse, relpos);\n }\n\n this.updateFriction(timeStep);\n const hitNormalWorldScaledWithProj = new Vec3();\n const fwd = new Vec3();\n const vel = new Vec3();\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i]; //const relpos = new Vec3();\n //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);\n\n chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction\n\n let m = 1;\n\n switch (this.indexUpAxis) {\n case 1:\n m = -1;\n break;\n }\n\n if (wheel.isInContact) {\n this.getVehicleAxisWorld(this.indexForwardAxis, fwd);\n const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);\n wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);\n fwd.vsub(hitNormalWorldScaledWithProj, fwd);\n const proj2 = fwd.dot(vel);\n wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;\n }\n\n if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {\n // Apply custom rotation when accelerating and sliding\n wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;\n } // Lock wheels\n\n\n if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {\n wheel.deltaRotation = 0;\n }\n\n wheel.rotation += wheel.deltaRotation; // Use the old value\n\n wheel.deltaRotation *= 0.99; // damping of rotation when not in contact\n }\n }\n\n updateSuspension(deltaTime) {\n const chassisBody = this.chassisBody;\n const chassisMass = chassisBody.mass;\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n\n for (let w_it = 0; w_it < numWheels; w_it++) {\n const wheel = wheelInfos[w_it];\n\n if (wheel.isInContact) {\n let force; // Spring\n\n const susp_length = wheel.suspensionRestLength;\n const current_length = wheel.suspensionLength;\n const length_diff = susp_length - current_length;\n force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper\n\n const projected_rel_vel = wheel.suspensionRelativeVelocity;\n let susp_damping;\n\n if (projected_rel_vel < 0) {\n susp_damping = wheel.dampingCompression;\n } else {\n susp_damping = wheel.dampingRelaxation;\n }\n\n force -= susp_damping * projected_rel_vel;\n wheel.suspensionForce = force * chassisMass;\n\n if (wheel.suspensionForce < 0) {\n wheel.suspensionForce = 0;\n }\n } else {\n wheel.suspensionForce = 0;\n }\n }\n }\n /**\n * Remove the vehicle including its constraints from the world.\n */\n\n\n removeFromWorld(world) {\n this.constraints;\n world.removeBody(this.chassisBody);\n world.removeEventListener('preStep', this.preStepCallback);\n this.world = null;\n }\n\n castRay(wheel) {\n const rayvector = castRay_rayvector;\n const target = castRay_target;\n this.updateWheelTransformWorld(wheel);\n const chassisBody = this.chassisBody;\n let depth = -1;\n const raylen = wheel.suspensionRestLength + wheel.radius;\n wheel.directionWorld.scale(raylen, rayvector);\n const source = wheel.chassisConnectionPointWorld;\n source.vadd(rayvector, target);\n const raycastResult = wheel.raycastResult;\n raycastResult.reset(); // Turn off ray collision with the chassis temporarily\n\n const oldState = chassisBody.collisionResponse;\n chassisBody.collisionResponse = false; // Cast ray against world\n\n this.world.rayTest(source, target, raycastResult);\n chassisBody.collisionResponse = oldState;\n const object = raycastResult.body;\n wheel.raycastResult.groundObject = 0;\n\n if (object) {\n depth = raycastResult.distance;\n wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;\n wheel.isInContact = true;\n const hitDistance = raycastResult.distance;\n wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel\n\n const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;\n const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;\n\n if (wheel.suspensionLength < minSuspensionLength) {\n wheel.suspensionLength = minSuspensionLength;\n }\n\n if (wheel.suspensionLength > maxSuspensionLength) {\n wheel.suspensionLength = maxSuspensionLength;\n wheel.raycastResult.reset();\n }\n\n const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);\n const chassis_velocity_at_contactPoint = new Vec3();\n chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);\n const projVel = wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);\n\n if (denominator >= -0.1) {\n wheel.suspensionRelativeVelocity = 0;\n wheel.clippedInvContactDotSuspension = 1 / 0.1;\n } else {\n const inv = -1 / denominator;\n wheel.suspensionRelativeVelocity = projVel * inv;\n wheel.clippedInvContactDotSuspension = inv;\n }\n } else {\n //put wheel info as in rest position\n wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;\n wheel.suspensionRelativeVelocity = 0.0;\n wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);\n wheel.clippedInvContactDotSuspension = 1.0;\n }\n\n return depth;\n }\n\n updateWheelTransformWorld(wheel) {\n wheel.isInContact = false;\n const chassisBody = this.chassisBody;\n chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);\n chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);\n chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);\n }\n /**\n * Update one of the wheel transform.\n * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.\n * @param wheelIndex The wheel index to update.\n */\n\n\n updateWheelTransform(wheelIndex) {\n const up = tmpVec4;\n const right = tmpVec5;\n const fwd = tmpVec6;\n const wheel = this.wheelInfos[wheelIndex];\n this.updateWheelTransformWorld(wheel);\n wheel.directionLocal.scale(-1, up);\n right.copy(wheel.axleLocal);\n up.cross(right, fwd);\n fwd.normalize();\n right.normalize(); // Rotate around steering over the wheelAxle\n\n const steering = wheel.steering;\n const steeringOrn = new Quaternion();\n steeringOrn.setFromAxisAngle(up, steering);\n const rotatingOrn = new Quaternion();\n rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel\n\n const q = wheel.worldTransform.quaternion;\n this.chassisBody.quaternion.mult(steeringOrn, q);\n q.mult(rotatingOrn, q);\n q.normalize(); // world position of the wheel\n\n const p = wheel.worldTransform.position;\n p.copy(wheel.directionWorld);\n p.scale(wheel.suspensionLength, p);\n p.vadd(wheel.chassisConnectionPointWorld, p);\n }\n /**\n * Get the world transform of one of the wheels\n */\n\n\n getWheelTransformWorld(wheelIndex) {\n return this.wheelInfos[wheelIndex].worldTransform;\n }\n\n updateFriction(timeStep) {\n const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards\n\n const wheelInfos = this.wheelInfos;\n const numWheels = wheelInfos.length;\n const chassisBody = this.chassisBody;\n const forwardWS = updateFriction_forwardWS;\n const axle = updateFriction_axle;\n this.numWheelsOnGround = 0;\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n\n if (groundObject) {\n this.numWheelsOnGround++;\n }\n\n wheel.sideImpulse = 0;\n wheel.forwardImpulse = 0;\n\n if (!forwardWS[i]) {\n forwardWS[i] = new Vec3();\n }\n\n if (!axle[i]) {\n axle[i] = new Vec3();\n }\n }\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n\n if (groundObject) {\n const axlei = axle[i];\n const wheelTrans = this.getWheelTransformWorld(i); // Get world axle\n\n wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);\n const surfNormalWS = wheel.raycastResult.hitNormalWorld;\n const proj = axlei.dot(surfNormalWS);\n surfNormalWS.scale(proj, surfNormalWS_scaled_proj);\n axlei.vsub(surfNormalWS_scaled_proj, axlei);\n axlei.normalize();\n surfNormalWS.cross(axlei, forwardWS[i]);\n forwardWS[i].normalize();\n wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);\n wheel.sideImpulse *= sideFrictionStiffness2;\n }\n }\n\n const sideFactor = 1;\n const fwdFactor = 0.5;\n this.sliding = false;\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const groundObject = wheel.raycastResult.body;\n let rollingFriction = 0;\n wheel.slipInfo = 1;\n\n if (groundObject) {\n const defaultRollingFrictionImpulse = 0;\n const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);\n // rollingFriction = calcRollingFriction(contactPt);\n\n rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);\n rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;\n\n const factor = maxImpulse / rollingFriction;\n wheel.slipInfo *= factor;\n } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)\n\n\n wheel.forwardImpulse = 0;\n wheel.skidInfo = 1;\n\n if (groundObject) {\n wheel.skidInfo = 1;\n const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;\n const maximpSide = maximp;\n const maximpSquared = maximp * maximpSide;\n wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;\n\n const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;\n const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;\n const impulseSquared = x * x + y * y;\n wheel.sliding = false;\n\n if (impulseSquared > maximpSquared) {\n this.sliding = true;\n wheel.sliding = true;\n const factor = maximp / Math.sqrt(impulseSquared);\n wheel.skidInfo *= factor;\n }\n }\n }\n\n if (this.sliding) {\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n\n if (wheel.sideImpulse !== 0) {\n if (wheel.skidInfo < 1) {\n wheel.forwardImpulse *= wheel.skidInfo;\n wheel.sideImpulse *= wheel.skidInfo;\n }\n }\n }\n } // apply the impulses\n\n\n for (let i = 0; i < numWheels; i++) {\n const wheel = wheelInfos[i];\n const rel_pos = new Vec3();\n wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position\n //rel_pos.copy(wheel.raycastResult.hitPointWorld);\n\n if (wheel.forwardImpulse !== 0) {\n const impulse = new Vec3();\n forwardWS[i].scale(wheel.forwardImpulse, impulse);\n chassisBody.applyImpulse(impulse, rel_pos);\n }\n\n if (wheel.sideImpulse !== 0) {\n const groundObject = wheel.raycastResult.body;\n const rel_pos2 = new Vec3();\n wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);\n\n const sideImp = new Vec3();\n axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.\n // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).\n\n chassisBody.vectorToLocalFrame(rel_pos, rel_pos);\n rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;\n chassisBody.vectorToWorldFrame(rel_pos, rel_pos);\n chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground\n\n sideImp.scale(-1, sideImp);\n groundObject.applyImpulse(sideImp, rel_pos2);\n }\n }\n }\n\n}\nnew Vec3();\nnew Vec3();\nnew Vec3();\nconst tmpVec4 = new Vec3();\nconst tmpVec5 = new Vec3();\nconst tmpVec6 = new Vec3();\nnew Ray();\nnew Vec3();\nconst castRay_rayvector = new Vec3();\nconst castRay_target = new Vec3();\nconst directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];\nconst updateFriction_surfNormalWS_scaled_proj = new Vec3();\nconst updateFriction_axle = [];\nconst updateFriction_forwardWS = [];\nconst sideFrictionStiffness2 = 1;\nconst calcRollingFriction_vel1 = new Vec3();\nconst calcRollingFriction_vel2 = new Vec3();\nconst calcRollingFriction_vel = new Vec3();\n\nfunction calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {\n let j1 = 0;\n const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();\n // const rel_pos2 = new Vec3();\n\n const vel1 = calcRollingFriction_vel1;\n const vel2 = calcRollingFriction_vel2;\n const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);\n // contactPosWorld.vsub(body1.position, rel_pos2);\n\n body0.getVelocityAtWorldPoint(contactPosWorld, vel1);\n body1.getVelocityAtWorldPoint(contactPosWorld, vel2);\n vel1.vsub(vel2, vel);\n const vrel = frictionDirectionWorld.dot(vel);\n const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);\n const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);\n const relaxation = 1;\n const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity\n\n j1 = -vrel * jacDiagABInv;\n\n if (maxImpulse < j1) {\n j1 = maxImpulse;\n }\n\n if (j1 < -maxImpulse) {\n j1 = -maxImpulse;\n }\n\n return j1;\n}\n\nconst computeImpulseDenominator_r0 = new Vec3();\nconst computeImpulseDenominator_c0 = new Vec3();\nconst computeImpulseDenominator_vec = new Vec3();\nconst computeImpulseDenominator_m = new Vec3();\n\nfunction computeImpulseDenominator(body, pos, normal) {\n const r0 = computeImpulseDenominator_r0;\n const c0 = computeImpulseDenominator_c0;\n const vec = computeImpulseDenominator_vec;\n const m = computeImpulseDenominator_m;\n pos.vsub(body.position, r0);\n r0.cross(normal, c0);\n body.invInertiaWorld.vmult(c0, m);\n m.cross(r0, vec);\n return body.invMass + normal.dot(vec);\n}\n\nconst resolveSingleBilateral_vel1 = new Vec3();\nconst resolveSingleBilateral_vel2 = new Vec3();\nconst resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects\n\nfunction resolveSingleBilateral(body1, pos1, body2, pos2, normal) {\n const normalLenSqr = normal.lengthSquared();\n\n if (normalLenSqr > 1.1) {\n return 0; // no impulse\n } // const rel_pos1 = new Vec3();\n // const rel_pos2 = new Vec3();\n // pos1.vsub(body1.position, rel_pos1);\n // pos2.vsub(body2.position, rel_pos2);\n\n\n const vel1 = resolveSingleBilateral_vel1;\n const vel2 = resolveSingleBilateral_vel2;\n const vel = resolveSingleBilateral_vel;\n body1.getVelocityAtWorldPoint(pos1, vel1);\n body2.getVelocityAtWorldPoint(pos2, vel2);\n vel1.vsub(vel2, vel);\n const rel_vel = normal.dot(vel);\n const contactDamping = 0.2;\n const massTerm = 1 / (body1.invMass + body2.invMass);\n const impulse = -contactDamping * rel_vel * massTerm;\n return impulse;\n}\n\n/**\n * Spherical shape\n * @example\n * const radius = 1\n * const sphereShape = new CANNON.Sphere(radius)\n * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })\n * world.addBody(sphereBody)\n */\nclass Sphere extends Shape {\n /**\n * The radius of the sphere.\n */\n\n /**\n *\n * @param radius The radius of the sphere, a non-negative number.\n */\n constructor(radius) {\n super({\n type: Shape.types.SPHERE\n });\n this.radius = radius !== undefined ? radius : 1.0;\n\n if (this.radius < 0) {\n throw new Error('The sphere radius cannot be negative.');\n }\n\n this.updateBoundingSphereRadius();\n }\n /** calculateLocalInertia */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n const I = 2.0 * mass * this.radius * this.radius / 5.0;\n target.x = I;\n target.y = I;\n target.z = I;\n return target;\n }\n /** volume */\n\n\n volume() {\n return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = this.radius;\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n const r = this.radius;\n const axes = ['x', 'y', 'z'];\n\n for (let i = 0; i < axes.length; i++) {\n const ax = axes[i];\n min[ax] = pos[ax] - r;\n max[ax] = pos[ax] + r;\n }\n }\n\n}\n\n/**\n * Simple vehicle helper class with spherical rigid body wheels.\n */\nclass RigidVehicle {\n /**\n * The bodies of the wheels.\n */\n\n /**\n * The chassis body.\n */\n\n /**\n * The constraints.\n */\n\n /**\n * The wheel axes.\n */\n\n /**\n * The wheel forces.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.wheelBodies = [];\n this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);\n\n if (options.chassisBody) {\n this.chassisBody = options.chassisBody;\n } else {\n // No chassis body given. Create it!\n this.chassisBody = new Body({\n mass: 1,\n shape: new Box(new Vec3(5, 0.5, 2))\n });\n }\n\n this.constraints = [];\n this.wheelAxes = [];\n this.wheelForces = [];\n }\n /**\n * Add a wheel\n */\n\n\n addWheel(options) {\n if (options === void 0) {\n options = {};\n }\n\n let wheelBody;\n\n if (options.body) {\n wheelBody = options.body;\n } else {\n // No wheel body given. Create it!\n wheelBody = new Body({\n mass: 1,\n shape: new Sphere(1.2)\n });\n }\n\n this.wheelBodies.push(wheelBody);\n this.wheelForces.push(0); // Position constrain wheels\n\n const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis\n\n const worldPosition = new Vec3();\n this.chassisBody.pointToWorldFrame(position, worldPosition);\n wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel\n\n const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);\n this.wheelAxes.push(axis);\n const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {\n pivotA: position,\n axisA: axis,\n pivotB: Vec3.ZERO,\n axisB: axis,\n collideConnected: false\n });\n this.constraints.push(hingeConstraint);\n return this.wheelBodies.length - 1;\n }\n /**\n * Set the steering value of a wheel.\n * @todo check coordinateSystem\n */\n\n\n setSteeringValue(value, wheelIndex) {\n // Set angle of the hinge axis\n const axis = this.wheelAxes[wheelIndex];\n const c = Math.cos(value);\n const s = Math.sin(value);\n const x = axis.x;\n const z = axis.z;\n this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);\n }\n /**\n * Set the target rotational speed of the hinge constraint.\n */\n\n\n setMotorSpeed(value, wheelIndex) {\n const hingeConstraint = this.constraints[wheelIndex];\n hingeConstraint.enableMotor();\n hingeConstraint.motorTargetVelocity = value;\n }\n /**\n * Set the target rotational speed of the hinge constraint.\n */\n\n\n disableMotor(wheelIndex) {\n const hingeConstraint = this.constraints[wheelIndex];\n hingeConstraint.disableMotor();\n }\n /**\n * Set the wheel force to apply on one of the wheels each time step\n */\n\n\n setWheelForce(value, wheelIndex) {\n this.wheelForces[wheelIndex] = value;\n }\n /**\n * Apply a torque on one of the wheels.\n */\n\n\n applyWheelForce(value, wheelIndex) {\n const axis = this.wheelAxes[wheelIndex];\n const wheelBody = this.wheelBodies[wheelIndex];\n const bodyTorque = wheelBody.torque;\n axis.scale(value, torque);\n wheelBody.vectorToWorldFrame(torque, torque);\n bodyTorque.vadd(torque, bodyTorque);\n }\n /**\n * Add the vehicle including its constraints to the world.\n */\n\n\n addToWorld(world) {\n const constraints = this.constraints;\n const bodies = this.wheelBodies.concat([this.chassisBody]);\n\n for (let i = 0; i < bodies.length; i++) {\n world.addBody(bodies[i]);\n }\n\n for (let i = 0; i < constraints.length; i++) {\n world.addConstraint(constraints[i]);\n }\n\n world.addEventListener('preStep', this._update.bind(this));\n }\n\n _update() {\n const wheelForces = this.wheelForces;\n\n for (let i = 0; i < wheelForces.length; i++) {\n this.applyWheelForce(wheelForces[i], i);\n }\n }\n /**\n * Remove the vehicle including its constraints from the world.\n */\n\n\n removeFromWorld(world) {\n const constraints = this.constraints;\n const bodies = this.wheelBodies.concat([this.chassisBody]);\n\n for (let i = 0; i < bodies.length; i++) {\n world.removeBody(bodies[i]);\n }\n\n for (let i = 0; i < constraints.length; i++) {\n world.removeConstraint(constraints[i]);\n }\n }\n /**\n * Get current rotational velocity of a wheel\n */\n\n\n getWheelSpeed(wheelIndex) {\n const axis = this.wheelAxes[wheelIndex];\n const wheelBody = this.wheelBodies[wheelIndex];\n const w = wheelBody.angularVelocity;\n this.chassisBody.vectorToWorldFrame(axis, worldAxis);\n return w.dot(worldAxis);\n }\n\n}\nconst torque = new Vec3();\nconst worldAxis = new Vec3();\n\n/**\n * Smoothed-particle hydrodynamics system\n * @todo Make parameters customizable in the constructor\n */\nclass SPHSystem {\n /**\n * The particles array.\n */\n\n /**\n * Density of the system (kg/m3).\n * @default 1\n */\n\n /**\n * Distance below which two particles are considered to be neighbors.\n * It should be adjusted so there are about 15-20 neighbor particles within this radius.\n * @default 1\n */\n\n /**\n * @default 1\n */\n\n /**\n * Viscosity of the system.\n * @default 0.01\n */\n\n /**\n * @default 0.000001\n */\n constructor() {\n this.particles = [];\n this.density = 1;\n this.smoothingRadius = 1;\n this.speedOfSound = 1;\n this.viscosity = 0.01;\n this.eps = 0.000001; // Stuff Computed per particle\n\n this.pressures = [];\n this.densities = [];\n this.neighbors = [];\n }\n /**\n * Add a particle to the system.\n */\n\n\n add(particle) {\n this.particles.push(particle);\n\n if (this.neighbors.length < this.particles.length) {\n this.neighbors.push([]);\n }\n }\n /**\n * Remove a particle from the system.\n */\n\n\n remove(particle) {\n const idx = this.particles.indexOf(particle);\n\n if (idx !== -1) {\n this.particles.splice(idx, 1);\n\n if (this.neighbors.length > this.particles.length) {\n this.neighbors.pop();\n }\n }\n }\n /**\n * Get neighbors within smoothing volume, save in the array neighbors\n */\n\n\n getNeighbors(particle, neighbors) {\n const N = this.particles.length;\n const id = particle.id;\n const R2 = this.smoothingRadius * this.smoothingRadius;\n const dist = SPHSystem_getNeighbors_dist;\n\n for (let i = 0; i !== N; i++) {\n const p = this.particles[i];\n p.position.vsub(particle.position, dist);\n\n if (id !== p.id && dist.lengthSquared() < R2) {\n neighbors.push(p);\n }\n }\n }\n\n update() {\n const N = this.particles.length;\n const dist = SPHSystem_update_dist;\n const cs = this.speedOfSound;\n const eps = this.eps;\n\n for (let i = 0; i !== N; i++) {\n const p = this.particles[i]; // Current particle\n\n const neighbors = this.neighbors[i]; // Get neighbors\n\n neighbors.length = 0;\n this.getNeighbors(p, neighbors);\n neighbors.push(this.particles[i]); // Add current too\n\n const numNeighbors = neighbors.length; // Accumulate density for the particle\n\n let sum = 0.0;\n\n for (let j = 0; j !== numNeighbors; j++) {\n //printf(\"Current particle has position %f %f %f\\n\",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());\n p.position.vsub(neighbors[j].position, dist);\n const len = dist.length();\n const weight = this.w(len);\n sum += neighbors[j].mass * weight;\n } // Save\n\n\n this.densities[i] = sum;\n this.pressures[i] = cs * cs * (this.densities[i] - this.density);\n } // Add forces\n // Sum to these accelerations\n\n\n const a_pressure = SPHSystem_update_a_pressure;\n const a_visc = SPHSystem_update_a_visc;\n const gradW = SPHSystem_update_gradW;\n const r_vec = SPHSystem_update_r_vec;\n const u = SPHSystem_update_u;\n\n for (let i = 0; i !== N; i++) {\n const particle = this.particles[i];\n a_pressure.set(0, 0, 0);\n a_visc.set(0, 0, 0); // Init vars\n\n let Pij;\n let nabla;\n\n const neighbors = this.neighbors[i];\n const numNeighbors = neighbors.length; //printf(\"Neighbors: \");\n\n for (let j = 0; j !== numNeighbors; j++) {\n const neighbor = neighbors[j]; //printf(\"%d \",nj);\n // Get r once for all..\n\n particle.position.vsub(neighbor.position, r_vec);\n const r = r_vec.length(); // Pressure contribution\n\n Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));\n this.gradw(r_vec, gradW); // Add to pressure acceleration\n\n gradW.scale(Pij, gradW);\n a_pressure.vadd(gradW, a_pressure); // Viscosity contribution\n\n neighbor.velocity.vsub(particle.velocity, u);\n u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);\n nabla = this.nablaw(r);\n u.scale(nabla, u); // Add to viscosity acceleration\n\n a_visc.vadd(u, a_visc);\n } // Calculate force\n\n\n a_visc.scale(particle.mass, a_visc);\n a_pressure.scale(particle.mass, a_pressure); // Add force to particles\n\n particle.force.vadd(a_visc, particle.force);\n particle.force.vadd(a_pressure, particle.force);\n }\n } // Calculate the weight using the W(r) weightfunction\n\n\n w(r) {\n // 315\n const h = this.smoothingRadius;\n return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;\n } // calculate gradient of the weight function\n\n\n gradw(rVec, resultVec) {\n const r = rVec.length();\n const h = this.smoothingRadius;\n rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);\n } // Calculate nabla(W)\n\n\n nablaw(r) {\n const h = this.smoothingRadius;\n const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);\n return nabla;\n }\n\n}\nconst SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation\n\nconst SPHSystem_update_dist = new Vec3(); // Relative velocity\n\nconst SPHSystem_update_a_pressure = new Vec3();\nconst SPHSystem_update_a_visc = new Vec3();\nconst SPHSystem_update_gradW = new Vec3();\nconst SPHSystem_update_r_vec = new Vec3();\nconst SPHSystem_update_u = new Vec3();\n\n/**\n * Cylinder class.\n * @example\n * const radiusTop = 0.5\n * const radiusBottom = 0.5\n * const height = 2\n * const numSegments = 12\n * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)\n * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })\n * world.addBody(cylinderBody)\n */\n\nclass Cylinder extends ConvexPolyhedron {\n /** The radius of the top of the Cylinder. */\n\n /** The radius of the bottom of the Cylinder. */\n\n /** The height of the Cylinder. */\n\n /** The number of segments to build the cylinder out of. */\n\n /**\n * @param radiusTop The radius of the top of the Cylinder.\n * @param radiusBottom The radius of the bottom of the Cylinder.\n * @param height The height of the Cylinder.\n * @param numSegments The number of segments to build the cylinder out of.\n */\n constructor(radiusTop, radiusBottom, height, numSegments) {\n if (radiusTop === void 0) {\n radiusTop = 1;\n }\n\n if (radiusBottom === void 0) {\n radiusBottom = 1;\n }\n\n if (height === void 0) {\n height = 1;\n }\n\n if (numSegments === void 0) {\n numSegments = 8;\n }\n\n if (radiusTop < 0) {\n throw new Error('The cylinder radiusTop cannot be negative.');\n }\n\n if (radiusBottom < 0) {\n throw new Error('The cylinder radiusBottom cannot be negative.');\n }\n\n const N = numSegments;\n const vertices = [];\n const axes = [];\n const faces = [];\n const bottomface = [];\n const topface = [];\n const cos = Math.cos;\n const sin = Math.sin; // First bottom point\n\n vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));\n bottomface.push(0); // First top point\n\n vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));\n topface.push(1);\n\n for (let i = 0; i < N; i++) {\n const theta = 2 * Math.PI / N * (i + 1);\n const thetaN = 2 * Math.PI / N * (i + 0.5);\n\n if (i < N - 1) {\n // Bottom\n vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));\n bottomface.push(2 * i + 2); // Top\n\n vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));\n topface.push(2 * i + 3); // Face\n\n faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);\n } else {\n faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect\n } // Axis: we can cut off half of them if we have even number of segments\n\n\n if (N % 2 === 1 || i < N / 2) {\n axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));\n }\n }\n\n faces.push(bottomface);\n axes.push(new Vec3(0, 1, 0)); // Reorder top face\n\n const temp = [];\n\n for (let i = 0; i < topface.length; i++) {\n temp.push(topface[topface.length - i - 1]);\n }\n\n faces.push(temp);\n super({\n vertices,\n faces,\n axes\n });\n this.type = Shape.types.CYLINDER;\n this.radiusTop = radiusTop;\n this.radiusBottom = radiusBottom;\n this.height = height;\n this.numSegments = numSegments;\n }\n\n}\n\n/**\n * Particle shape.\n * @example\n * const particleShape = new CANNON.Particle()\n * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })\n * world.addBody(particleBody)\n */\nclass Particle extends Shape {\n constructor() {\n super({\n type: Shape.types.PARTICLE\n });\n }\n /**\n * calculateLocalInertia\n */\n\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.set(0, 0, 0);\n return target;\n }\n\n volume() {\n return 0;\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = 0;\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n // Get each axis max\n min.copy(pos);\n max.copy(pos);\n }\n\n}\n\n/**\n * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.\n * @example\n * const planeShape = new CANNON.Plane()\n * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape })\n * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up\n * world.addBody(planeBody)\n */\nclass Plane extends Shape {\n /** worldNormal */\n\n /** worldNormalNeedsUpdate */\n constructor() {\n super({\n type: Shape.types.PLANE\n }); // World oriented normal\n\n this.worldNormal = new Vec3();\n this.worldNormalNeedsUpdate = true;\n this.boundingSphereRadius = Number.MAX_VALUE;\n }\n /** computeWorldNormal */\n\n\n computeWorldNormal(quat) {\n const n = this.worldNormal;\n n.set(0, 0, 1);\n quat.vmult(n, n);\n this.worldNormalNeedsUpdate = false;\n }\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n return target;\n }\n\n volume() {\n return (// The plane is infinite...\n Number.MAX_VALUE\n );\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n // The plane AABB is infinite, except if the normal is pointing along any axis\n tempNormal.set(0, 0, 1); // Default plane normal is z\n\n quat.vmult(tempNormal, tempNormal);\n const maxVal = Number.MAX_VALUE;\n min.set(-maxVal, -maxVal, -maxVal);\n max.set(maxVal, maxVal, maxVal);\n\n if (tempNormal.x === 1) {\n max.x = pos.x;\n } else if (tempNormal.x === -1) {\n min.x = pos.x;\n }\n\n if (tempNormal.y === 1) {\n max.y = pos.y;\n } else if (tempNormal.y === -1) {\n min.y = pos.y;\n }\n\n if (tempNormal.z === 1) {\n max.z = pos.z;\n } else if (tempNormal.z === -1) {\n min.z = pos.z;\n }\n }\n\n updateBoundingSphereRadius() {\n this.boundingSphereRadius = Number.MAX_VALUE;\n }\n\n}\nconst tempNormal = new Vec3();\n\n/**\n * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.\n * @todo Should be possible to use along all axes, not just y\n * @todo should be possible to scale along all axes\n * @todo Refactor elementSize to elementSizeX and elementSizeY\n *\n * @example\n * // Generate some height data (y-values).\n * const data = []\n * for (let i = 0; i < 1000; i++) {\n * const y = 0.5 * Math.cos(0.2 * i)\n * data.push(y)\n * }\n *\n * // Create the heightfield shape\n * const heightfieldShape = new CANNON.Heightfield(data, {\n * elementSize: 1 // Distance between the data points in X and Y directions\n * })\n * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })\n * world.addBody(heightfieldBody)\n */\nclass Heightfield extends Shape {\n /**\n * An array of numbers, or height values, that are spread out along the x axis.\n */\n\n /**\n * Max value of the data points in the data array.\n */\n\n /**\n * Minimum value of the data points in the data array.\n */\n\n /**\n * World spacing between the data points in X and Y direction.\n * @todo elementSizeX and Y\n * @default 1\n */\n\n /**\n * @default true\n */\n\n /**\n * @param data An array of numbers, or height values, that are spread out along the x axis.\n */\n constructor(data, options) {\n if (options === void 0) {\n options = {};\n }\n\n options = Utils.defaults(options, {\n maxValue: null,\n minValue: null,\n elementSize: 1\n });\n super({\n type: Shape.types.HEIGHTFIELD\n });\n this.data = data;\n this.maxValue = options.maxValue;\n this.minValue = options.minValue;\n this.elementSize = options.elementSize;\n\n if (options.minValue === null) {\n this.updateMinValue();\n }\n\n if (options.maxValue === null) {\n this.updateMaxValue();\n }\n\n this.cacheEnabled = true;\n this.pillarConvex = new ConvexPolyhedron();\n this.pillarOffset = new Vec3();\n this.updateBoundingSphereRadius(); // \"i_j_isUpper\" => { convex: ..., offset: ... }\n // for example:\n // _cachedPillars[\"0_2_1\"]\n\n this._cachedPillars = {};\n }\n /**\n * Call whenever you change the data array.\n */\n\n\n update() {\n this._cachedPillars = {};\n }\n /**\n * Update the `minValue` property\n */\n\n\n updateMinValue() {\n const data = this.data;\n let minValue = data[0][0];\n\n for (let i = 0; i !== data.length; i++) {\n for (let j = 0; j !== data[i].length; j++) {\n const v = data[i][j];\n\n if (v < minValue) {\n minValue = v;\n }\n }\n }\n\n this.minValue = minValue;\n }\n /**\n * Update the `maxValue` property\n */\n\n\n updateMaxValue() {\n const data = this.data;\n let maxValue = data[0][0];\n\n for (let i = 0; i !== data.length; i++) {\n for (let j = 0; j !== data[i].length; j++) {\n const v = data[i][j];\n\n if (v > maxValue) {\n maxValue = v;\n }\n }\n }\n\n this.maxValue = maxValue;\n }\n /**\n * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.\n */\n\n\n setHeightValueAtIndex(xi, yi, value) {\n const data = this.data;\n data[xi][yi] = value; // Invalidate cache\n\n this.clearCachedConvexTrianglePillar(xi, yi, false);\n\n if (xi > 0) {\n this.clearCachedConvexTrianglePillar(xi - 1, yi, true);\n this.clearCachedConvexTrianglePillar(xi - 1, yi, false);\n }\n\n if (yi > 0) {\n this.clearCachedConvexTrianglePillar(xi, yi - 1, true);\n this.clearCachedConvexTrianglePillar(xi, yi - 1, false);\n }\n\n if (yi > 0 && xi > 0) {\n this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);\n }\n }\n /**\n * Get max/min in a rectangle in the matrix data\n * @param result An array to store the results in.\n * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.\n */\n\n\n getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result) {\n if (result === void 0) {\n result = [];\n }\n\n // Get max and min of the data\n const data = this.data; // Set first value\n\n let max = this.minValue;\n\n for (let i = iMinX; i <= iMaxX; i++) {\n for (let j = iMinY; j <= iMaxY; j++) {\n const height = data[i][j];\n\n if (height > max) {\n max = height;\n }\n }\n }\n\n result[0] = this.minValue;\n result[1] = max;\n }\n /**\n * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.\n * @param result Two-element array\n * @param clamp If the position should be clamped to the heightfield edge.\n */\n\n\n getIndexOfPosition(x, y, result, clamp) {\n // Get the index of the data points to test against\n const w = this.elementSize;\n const data = this.data;\n let xi = Math.floor(x / w);\n let yi = Math.floor(y / w);\n result[0] = xi;\n result[1] = yi;\n\n if (clamp) {\n // Clamp index to edges\n if (xi < 0) {\n xi = 0;\n }\n\n if (yi < 0) {\n yi = 0;\n }\n\n if (xi >= data.length - 1) {\n xi = data.length - 1;\n }\n\n if (yi >= data[0].length - 1) {\n yi = data[0].length - 1;\n }\n } // Bail out if we are out of the terrain\n\n\n if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {\n return false;\n }\n\n return true;\n }\n\n getTriangleAt(x, y, edgeClamp, a, b, c) {\n const idx = getHeightAt_idx;\n this.getIndexOfPosition(x, y, idx, edgeClamp);\n let xi = idx[0];\n let yi = idx[1];\n const data = this.data;\n\n if (edgeClamp) {\n xi = Math.min(data.length - 2, Math.max(0, xi));\n yi = Math.min(data[0].length - 2, Math.max(0, yi));\n }\n\n const elementSize = this.elementSize;\n const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;\n const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;\n const upper = lowerDist2 > upperDist2;\n this.getTriangle(xi, yi, upper, a, b, c);\n return upper;\n }\n\n getNormalAt(x, y, edgeClamp, result) {\n const a = getNormalAt_a;\n const b = getNormalAt_b;\n const c = getNormalAt_c;\n const e0 = getNormalAt_e0;\n const e1 = getNormalAt_e1;\n this.getTriangleAt(x, y, edgeClamp, a, b, c);\n b.vsub(a, e0);\n c.vsub(a, e1);\n e0.cross(e1, result);\n result.normalize();\n }\n /**\n * Get an AABB of a square in the heightfield\n * @param xi\n * @param yi\n * @param result\n */\n\n\n getAabbAtIndex(xi, yi, _ref) {\n let {\n lowerBound,\n upperBound\n } = _ref;\n const data = this.data;\n const elementSize = this.elementSize;\n lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]);\n upperBound.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);\n }\n /**\n * Get the height in the heightfield at a given position\n */\n\n\n getHeightAt(x, y, edgeClamp) {\n const data = this.data;\n const a = getHeightAt_a;\n const b = getHeightAt_b;\n const c = getHeightAt_c;\n const idx = getHeightAt_idx;\n this.getIndexOfPosition(x, y, idx, edgeClamp);\n let xi = idx[0];\n let yi = idx[1];\n\n if (edgeClamp) {\n xi = Math.min(data.length - 2, Math.max(0, xi));\n yi = Math.min(data[0].length - 2, Math.max(0, yi));\n }\n\n const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);\n barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);\n const w = getHeightAt_weights;\n\n if (upper) {\n // Top triangle verts\n return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;\n } else {\n // Top triangle verts\n return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;\n }\n }\n\n getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) {\n return `${xi}_${yi}_${getUpperTriangle ? 1 : 0}`;\n }\n\n getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {\n return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];\n }\n\n setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) {\n this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {\n convex,\n offset\n };\n }\n\n clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {\n delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];\n }\n /**\n * Get a triangle from the heightfield\n */\n\n\n getTriangle(xi, yi, upper, a, b, c) {\n const data = this.data;\n const elementSize = this.elementSize;\n\n if (upper) {\n // Top triangle verts\n a.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);\n b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);\n c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);\n } else {\n // Top triangle verts\n a.set(xi * elementSize, yi * elementSize, data[xi][yi]);\n b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);\n c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);\n }\n }\n /**\n * Get a triangle in the terrain in the form of a triangular convex shape.\n */\n\n\n getConvexTrianglePillar(xi, yi, getUpperTriangle) {\n let result = this.pillarConvex;\n let offsetResult = this.pillarOffset;\n\n if (this.cacheEnabled) {\n const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);\n\n if (data) {\n this.pillarConvex = data.convex;\n this.pillarOffset = data.offset;\n return;\n }\n\n result = new ConvexPolyhedron();\n offsetResult = new Vec3();\n this.pillarConvex = result;\n this.pillarOffset = offsetResult;\n }\n\n const data = this.data;\n const elementSize = this.elementSize;\n const faces = result.faces; // Reuse verts if possible\n\n result.vertices.length = 6;\n\n for (let i = 0; i < 6; i++) {\n if (!result.vertices[i]) {\n result.vertices[i] = new Vec3();\n }\n } // Reuse faces if possible\n\n\n faces.length = 5;\n\n for (let i = 0; i < 5; i++) {\n if (!faces[i]) {\n faces[i] = [];\n }\n }\n\n const verts = result.vertices;\n const h = (Math.min(data[xi][yi], data[xi + 1][yi], data[xi][yi + 1], data[xi + 1][yi + 1]) - this.minValue) / 2 + this.minValue;\n\n if (!getUpperTriangle) {\n // Center of the triangle pillar - all polygons are given relative to this one\n offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle\n (yi + 0.25) * elementSize, h // vertical center\n ); // Top triangle verts\n\n verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);\n verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);\n verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts\n\n verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);\n verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);\n verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle\n\n faces[0][0] = 0;\n faces[0][1] = 1;\n faces[0][2] = 2; // bottom triangle\n\n faces[1][0] = 5;\n faces[1][1] = 4;\n faces[1][2] = 3; // -x facing quad\n\n faces[2][0] = 0;\n faces[2][1] = 2;\n faces[2][2] = 5;\n faces[2][3] = 3; // -y facing quad\n\n faces[3][0] = 1;\n faces[3][1] = 0;\n faces[3][2] = 3;\n faces[3][3] = 4; // +xy facing quad\n\n faces[4][0] = 4;\n faces[4][1] = 5;\n faces[4][2] = 2;\n faces[4][3] = 1;\n } else {\n // Center of the triangle pillar - all polygons are given relative to this one\n offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle\n (yi + 0.75) * elementSize, h // vertical center\n ); // Top triangle verts\n\n verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);\n verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);\n verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts\n\n verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);\n verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);\n verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle\n\n faces[0][0] = 0;\n faces[0][1] = 1;\n faces[0][2] = 2; // bottom triangle\n\n faces[1][0] = 5;\n faces[1][1] = 4;\n faces[1][2] = 3; // +x facing quad\n\n faces[2][0] = 2;\n faces[2][1] = 5;\n faces[2][2] = 3;\n faces[2][3] = 0; // +y facing quad\n\n faces[3][0] = 3;\n faces[3][1] = 4;\n faces[3][2] = 1;\n faces[3][3] = 0; // -xy facing quad\n\n faces[4][0] = 1;\n faces[4][1] = 4;\n faces[4][2] = 5;\n faces[4][3] = 2;\n }\n\n result.computeNormals();\n result.computeEdges();\n result.updateBoundingSphereRadius();\n this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);\n }\n\n calculateLocalInertia(mass, target) {\n if (target === void 0) {\n target = new Vec3();\n }\n\n target.set(0, 0, 0);\n return target;\n }\n\n volume() {\n return (// The terrain is infinite\n Number.MAX_VALUE\n );\n }\n\n calculateWorldAABB(pos, quat, min, max) {\n /** @TODO do it properly */\n min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n }\n\n updateBoundingSphereRadius() {\n // Use the bounding box of the min/max values\n const data = this.data;\n const s = this.elementSize;\n this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).length();\n }\n /**\n * Sets the height values from an image. Currently only supported in browser.\n */\n\n\n setHeightsFromImage(image, scale) {\n const {\n x,\n z,\n y\n } = scale;\n const canvas = document.createElement('canvas');\n canvas.width = image.width;\n canvas.height = image.height;\n const context = canvas.getContext('2d');\n context.drawImage(image, 0, 0);\n const imageData = context.getImageData(0, 0, image.width, image.height);\n const matrix = this.data;\n matrix.length = 0;\n this.elementSize = Math.abs(x) / imageData.width;\n\n for (let i = 0; i < imageData.height; i++) {\n const row = [];\n\n for (let j = 0; j < imageData.width; j++) {\n const a = imageData.data[(i * imageData.height + j) * 4];\n const b = imageData.data[(i * imageData.height + j) * 4 + 1];\n const c = imageData.data[(i * imageData.height + j) * 4 + 2];\n const height = (a + b + c) / 4 / 255 * z;\n\n if (x < 0) {\n row.push(height);\n } else {\n row.unshift(height);\n }\n }\n\n if (y < 0) {\n matrix.unshift(row);\n } else {\n matrix.push(row);\n }\n }\n\n this.updateMaxValue();\n this.updateMinValue();\n this.update();\n }\n\n}\nconst getHeightAt_idx = [];\nconst getHeightAt_weights = new Vec3();\nconst getHeightAt_a = new Vec3();\nconst getHeightAt_b = new Vec3();\nconst getHeightAt_c = new Vec3();\nconst getNormalAt_a = new Vec3();\nconst getNormalAt_b = new Vec3();\nconst getNormalAt_c = new Vec3();\nconst getNormalAt_e0 = new Vec3();\nconst getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system\n\nfunction barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) {\n result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));\n result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));\n result.z = 1 - result.x - result.y;\n}\n\n/**\n * OctreeNode\n */\nclass OctreeNode {\n /** The root node */\n\n /** Boundary of this node */\n\n /** Contained data at the current node level */\n\n /** Children to this node */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n this.root = options.root || null;\n this.aabb = options.aabb ? options.aabb.clone() : new AABB();\n this.data = [];\n this.children = [];\n }\n /**\n * reset\n */\n\n\n reset() {\n this.children.length = this.data.length = 0;\n }\n /**\n * Insert data into this node\n * @return True if successful, otherwise false\n */\n\n\n insert(aabb, elementData, level) {\n if (level === void 0) {\n level = 0;\n }\n\n const nodeData = this.data; // Ignore objects that do not belong in this node\n\n if (!this.aabb.contains(aabb)) {\n return false; // object cannot be added\n }\n\n const children = this.children;\n const maxDepth = this.maxDepth || this.root.maxDepth;\n\n if (level < maxDepth) {\n // Subdivide if there are no children yet\n let subdivided = false;\n\n if (!children.length) {\n this.subdivide();\n subdivided = true;\n } // add to whichever node will accept it\n\n\n for (let i = 0; i !== 8; i++) {\n if (children[i].insert(aabb, elementData, level + 1)) {\n return true;\n }\n }\n\n if (subdivided) {\n // No children accepted! Might as well just remove em since they contain none\n children.length = 0;\n }\n } // Too deep, or children didnt want it. add it in current node\n\n\n nodeData.push(elementData);\n return true;\n }\n /**\n * Create 8 equally sized children nodes and put them in the `children` array.\n */\n\n\n subdivide() {\n const aabb = this.aabb;\n const l = aabb.lowerBound;\n const u = aabb.upperBound;\n const children = this.children;\n children.push(new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 0, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 0, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 1, 0)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 1, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 1, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 0, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(1, 0, 1)\n })\n }), new OctreeNode({\n aabb: new AABB({\n lowerBound: new Vec3(0, 1, 0)\n })\n }));\n u.vsub(l, halfDiagonal);\n halfDiagonal.scale(0.5, halfDiagonal);\n const root = this.root || this;\n\n for (let i = 0; i !== 8; i++) {\n const child = children[i]; // Set current node as root\n\n child.root = root; // Compute bounds\n\n const lowerBound = child.aabb.lowerBound;\n lowerBound.x *= halfDiagonal.x;\n lowerBound.y *= halfDiagonal.y;\n lowerBound.z *= halfDiagonal.z;\n lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal\n\n lowerBound.vadd(halfDiagonal, child.aabb.upperBound);\n }\n }\n /**\n * Get all data, potentially within an AABB\n * @return The \"result\" object\n */\n\n\n aabbQuery(aabb, result) {\n this.data; // abort if the range does not intersect this node\n // if (!this.aabb.overlaps(aabb)){\n // return result;\n // }\n // Add objects at this level\n // Array.prototype.push.apply(result, nodeData);\n // Add child data\n // @todo unwrap recursion into a queue / loop, that's faster in JS\n\n this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {\n // children[i].aabbQuery(aabb, result);\n // }\n\n const queue = [this];\n\n while (queue.length) {\n const node = queue.pop();\n\n if (node.aabb.overlaps(aabb)) {\n Array.prototype.push.apply(result, node.data);\n }\n\n Array.prototype.push.apply(queue, node.children);\n }\n\n return result;\n }\n /**\n * Get all data, potentially intersected by a ray.\n * @return The \"result\" object\n */\n\n\n rayQuery(ray, treeTransform, result) {\n // Use aabb query for now.\n\n /** @todo implement real ray query which needs less lookups */\n ray.getAABB(tmpAABB);\n tmpAABB.toLocalFrame(treeTransform, tmpAABB);\n this.aabbQuery(tmpAABB, result);\n return result;\n }\n /**\n * removeEmptyNodes\n */\n\n\n removeEmptyNodes() {\n for (let i = this.children.length - 1; i >= 0; i--) {\n this.children[i].removeEmptyNodes();\n\n if (!this.children[i].children.length && !this.children[i].data.length) {\n this.children.splice(i, 1);\n }\n }\n }\n\n}\n/**\n * Octree\n */\n\n\nclass Octree extends OctreeNode {\n /**\n * Maximum subdivision depth\n * @default 8\n */\n\n /**\n * @param aabb The total AABB of the tree\n */\n constructor(aabb, options) {\n if (options === void 0) {\n options = {};\n }\n\n super({\n root: null,\n aabb\n });\n this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;\n }\n\n}\nconst halfDiagonal = new Vec3();\nconst tmpAABB = new AABB();\n\n/**\n * Trimesh.\n * @example\n * // How to make a mesh with a single triangle\n * const vertices = [\n * 0, 0, 0, // vertex 0\n * 1, 0, 0, // vertex 1\n * 0, 1, 0 // vertex 2\n * ]\n * const indices = [\n * 0, 1, 2 // triangle 0\n * ]\n * const trimeshShape = new CANNON.Trimesh(vertices, indices)\n */\nclass Trimesh extends Shape {\n /**\n * vertices\n */\n\n /**\n * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.\n */\n\n /**\n * The normals data.\n */\n\n /**\n * The local AABB of the mesh.\n */\n\n /**\n * References to vertex pairs, making up all unique edges in the trimesh.\n */\n\n /**\n * Local scaling of the mesh. Use .setScale() to set it.\n */\n\n /**\n * The indexed triangles. Use .updateTree() to update it.\n */\n constructor(vertices, indices) {\n super({\n type: Shape.types.TRIMESH\n });\n this.vertices = new Float32Array(vertices);\n this.indices = new Int16Array(indices);\n this.normals = new Float32Array(indices.length);\n this.aabb = new AABB();\n this.edges = null;\n this.scale = new Vec3(1, 1, 1);\n this.tree = new Octree();\n this.updateEdges();\n this.updateNormals();\n this.updateAABB();\n this.updateBoundingSphereRadius();\n this.updateTree();\n }\n /**\n * updateTree\n */\n\n\n updateTree() {\n const tree = this.tree;\n tree.reset();\n tree.aabb.copy(this.aabb);\n const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled\n\n tree.aabb.lowerBound.x *= 1 / scale.x;\n tree.aabb.lowerBound.y *= 1 / scale.y;\n tree.aabb.lowerBound.z *= 1 / scale.z;\n tree.aabb.upperBound.x *= 1 / scale.x;\n tree.aabb.upperBound.y *= 1 / scale.y;\n tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles\n\n const triangleAABB = new AABB();\n const a = new Vec3();\n const b = new Vec3();\n const c = new Vec3();\n const points = [a, b, c];\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n //this.getTriangleVertices(i, a, b, c);\n // Get unscaled triangle verts\n const i3 = i * 3;\n\n this._getUnscaledVertex(this.indices[i3], a);\n\n this._getUnscaledVertex(this.indices[i3 + 1], b);\n\n this._getUnscaledVertex(this.indices[i3 + 2], c);\n\n triangleAABB.setFromPoints(points);\n tree.insert(triangleAABB, i);\n }\n\n tree.removeEmptyNodes();\n }\n /**\n * Get triangles in a local AABB from the trimesh.\n * @param result An array of integers, referencing the queried triangles.\n */\n\n\n getTrianglesInAABB(aabb, result) {\n unscaledAABB.copy(aabb); // Scale it to local\n\n const scale = this.scale;\n const isx = scale.x;\n const isy = scale.y;\n const isz = scale.z;\n const l = unscaledAABB.lowerBound;\n const u = unscaledAABB.upperBound;\n l.x /= isx;\n l.y /= isy;\n l.z /= isz;\n u.x /= isx;\n u.y /= isy;\n u.z /= isz;\n return this.tree.aabbQuery(unscaledAABB, result);\n }\n /**\n * setScale\n */\n\n\n setScale(scale) {\n const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;\n const isUniform = scale.x === scale.y && scale.y === scale.z;\n\n if (!(wasUniform && isUniform)) {\n // Non-uniform scaling. Need to update normals.\n this.updateNormals();\n }\n\n this.scale.copy(scale);\n this.updateAABB();\n this.updateBoundingSphereRadius();\n }\n /**\n * Compute the normals of the faces. Will save in the `.normals` array.\n */\n\n\n updateNormals() {\n const n = computeNormals_n; // Generate normals\n\n const normals = this.normals;\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n const i3 = i * 3;\n const a = this.indices[i3];\n const b = this.indices[i3 + 1];\n const c = this.indices[i3 + 2];\n this.getVertex(a, va);\n this.getVertex(b, vb);\n this.getVertex(c, vc);\n Trimesh.computeNormal(vb, va, vc, n);\n normals[i3] = n.x;\n normals[i3 + 1] = n.y;\n normals[i3 + 2] = n.z;\n }\n }\n /**\n * Update the `.edges` property\n */\n\n\n updateEdges() {\n const edges = {};\n\n const add = (a, b) => {\n const key = a < b ? `${a}_${b}` : `${b}_${a}`;\n edges[key] = true;\n };\n\n for (let i = 0; i < this.indices.length / 3; i++) {\n const i3 = i * 3;\n const a = this.indices[i3];\n const b = this.indices[i3 + 1];\n const c = this.indices[i3 + 2];\n add(a, b);\n add(b, c);\n add(c, a);\n }\n\n const keys = Object.keys(edges);\n this.edges = new Int16Array(keys.length * 2);\n\n for (let i = 0; i < keys.length; i++) {\n const indices = keys[i].split('_');\n this.edges[2 * i] = parseInt(indices[0], 10);\n this.edges[2 * i + 1] = parseInt(indices[1], 10);\n }\n }\n /**\n * Get an edge vertex\n * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.\n * @param vertexStore Where to store the result\n */\n\n\n getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {\n const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];\n this.getVertex(vertexIndex, vertexStore);\n }\n /**\n * Get a vector along an edge.\n */\n\n\n getEdgeVector(edgeIndex, vectorStore) {\n const va = getEdgeVector_va;\n const vb = getEdgeVector_vb;\n this.getEdgeVertex(edgeIndex, 0, va);\n this.getEdgeVertex(edgeIndex, 1, vb);\n vb.vsub(va, vectorStore);\n }\n /**\n * Get face normal given 3 vertices\n */\n\n\n static computeNormal(va, vb, vc, target) {\n vb.vsub(va, ab);\n vc.vsub(vb, cb);\n cb.cross(ab, target);\n\n if (!target.isZero()) {\n target.normalize();\n }\n }\n /**\n * Get vertex i.\n * @return The \"out\" vector object\n */\n\n\n getVertex(i, out) {\n const scale = this.scale;\n\n this._getUnscaledVertex(i, out);\n\n out.x *= scale.x;\n out.y *= scale.y;\n out.z *= scale.z;\n return out;\n }\n /**\n * Get raw vertex i\n * @return The \"out\" vector object\n */\n\n\n _getUnscaledVertex(i, out) {\n const i3 = i * 3;\n const vertices = this.vertices;\n return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);\n }\n /**\n * Get a vertex from the trimesh,transformed by the given position and quaternion.\n * @return The \"out\" vector object\n */\n\n\n getWorldVertex(i, pos, quat, out) {\n this.getVertex(i, out);\n Transform.pointToWorldFrame(pos, quat, out, out);\n return out;\n }\n /**\n * Get the three vertices for triangle i.\n */\n\n\n getTriangleVertices(i, a, b, c) {\n const i3 = i * 3;\n this.getVertex(this.indices[i3], a);\n this.getVertex(this.indices[i3 + 1], b);\n this.getVertex(this.indices[i3 + 2], c);\n }\n /**\n * Compute the normal of triangle i.\n * @return The \"target\" vector object\n */\n\n\n getNormal(i, target) {\n const i3 = i * 3;\n return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);\n }\n /**\n * @return The \"target\" vector object\n */\n\n\n calculateLocalInertia(mass, target) {\n // Approximate with box inertia\n // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it\n this.computeLocalAABB(cli_aabb);\n const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;\n const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;\n const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;\n return target.set(1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x));\n }\n /**\n * Compute the local AABB for the trimesh\n */\n\n\n computeLocalAABB(aabb) {\n const l = aabb.lowerBound;\n const u = aabb.upperBound;\n const n = this.vertices.length;\n this.vertices;\n const v = computeLocalAABB_worldVert;\n this.getVertex(0, v);\n l.copy(v);\n u.copy(v);\n\n for (let i = 0; i !== n; i++) {\n this.getVertex(i, v);\n\n if (v.x < l.x) {\n l.x = v.x;\n } else if (v.x > u.x) {\n u.x = v.x;\n }\n\n if (v.y < l.y) {\n l.y = v.y;\n } else if (v.y > u.y) {\n u.y = v.y;\n }\n\n if (v.z < l.z) {\n l.z = v.z;\n } else if (v.z > u.z) {\n u.z = v.z;\n }\n }\n }\n /**\n * Update the `.aabb` property\n */\n\n\n updateAABB() {\n this.computeLocalAABB(this.aabb);\n }\n /**\n * Will update the `.boundingSphereRadius` property\n */\n\n\n updateBoundingSphereRadius() {\n // Assume points are distributed with local (0,0,0) as center\n let max2 = 0;\n const vertices = this.vertices;\n const v = new Vec3();\n\n for (let i = 0, N = vertices.length / 3; i !== N; i++) {\n this.getVertex(i, v);\n const norm2 = v.lengthSquared();\n\n if (norm2 > max2) {\n max2 = norm2;\n }\n }\n\n this.boundingSphereRadius = Math.sqrt(max2);\n }\n /**\n * calculateWorldAABB\n */\n\n\n calculateWorldAABB(pos, quat, min, max) {\n /*\n const n = this.vertices.length / 3,\n verts = this.vertices;\n const minx,miny,minz,maxx,maxy,maxz;\n const v = tempWorldVertex;\n for(let i=0; i maxx || maxx===undefined){\n maxx = v.x;\n }\n if (v.y < miny || miny===undefined){\n miny = v.y;\n } else if(v.y > maxy || maxy===undefined){\n maxy = v.y;\n }\n if (v.z < minz || minz===undefined){\n minz = v.z;\n } else if(v.z > maxz || maxz===undefined){\n maxz = v.z;\n }\n }\n min.set(minx,miny,minz);\n max.set(maxx,maxy,maxz);\n */\n // Faster approximation using local AABB\n const frame = calculateWorldAABB_frame;\n const result = calculateWorldAABB_aabb;\n frame.position = pos;\n frame.quaternion = quat;\n this.aabb.toWorldFrame(frame, result);\n min.copy(result.lowerBound);\n max.copy(result.upperBound);\n }\n /**\n * Get approximate volume\n */\n\n\n volume() {\n return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;\n }\n /**\n * Create a Trimesh instance, shaped as a torus.\n */\n\n\n static createTorus(radius, tube, radialSegments, tubularSegments, arc) {\n if (radius === void 0) {\n radius = 1;\n }\n\n if (tube === void 0) {\n tube = 0.5;\n }\n\n if (radialSegments === void 0) {\n radialSegments = 8;\n }\n\n if (tubularSegments === void 0) {\n tubularSegments = 6;\n }\n\n if (arc === void 0) {\n arc = Math.PI * 2;\n }\n\n const vertices = [];\n const indices = [];\n\n for (let j = 0; j <= radialSegments; j++) {\n for (let i = 0; i <= tubularSegments; i++) {\n const u = i / tubularSegments * arc;\n const v = j / radialSegments * Math.PI * 2;\n const x = (radius + tube * Math.cos(v)) * Math.cos(u);\n const y = (radius + tube * Math.cos(v)) * Math.sin(u);\n const z = tube * Math.sin(v);\n vertices.push(x, y, z);\n }\n }\n\n for (let j = 1; j <= radialSegments; j++) {\n for (let i = 1; i <= tubularSegments; i++) {\n const a = (tubularSegments + 1) * j + i - 1;\n const b = (tubularSegments + 1) * (j - 1) + i - 1;\n const c = (tubularSegments + 1) * (j - 1) + i;\n const d = (tubularSegments + 1) * j + i;\n indices.push(a, b, d);\n indices.push(b, c, d);\n }\n }\n\n return new Trimesh(vertices, indices);\n }\n\n}\nconst computeNormals_n = new Vec3();\nconst unscaledAABB = new AABB();\nconst getEdgeVector_va = new Vec3();\nconst getEdgeVector_vb = new Vec3();\nconst cb = new Vec3();\nconst ab = new Vec3();\nconst va = new Vec3();\nconst vb = new Vec3();\nconst vc = new Vec3();\nconst cli_aabb = new AABB();\nconst computeLocalAABB_worldVert = new Vec3();\nconst calculateWorldAABB_frame = new Transform();\nconst calculateWorldAABB_aabb = new AABB();\n\n/**\n * Constraint equation solver base class.\n */\nclass Solver {\n /**\n * All equations to be solved\n */\n\n /**\n * @todo remove useless constructor\n */\n constructor() {\n this.equations = [];\n }\n /**\n * Should be implemented in subclasses!\n * @todo use abstract\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n return (// Should return the number of iterations done!\n 0\n );\n }\n /**\n * Add an equation\n */\n\n\n addEquation(eq) {\n if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {\n this.equations.push(eq);\n }\n }\n /**\n * Remove an equation\n */\n\n\n removeEquation(eq) {\n const eqs = this.equations;\n const i = eqs.indexOf(eq);\n\n if (i !== -1) {\n eqs.splice(i, 1);\n }\n }\n /**\n * Add all equations\n */\n\n\n removeAllEquations() {\n this.equations.length = 0;\n }\n\n}\n\n/**\n * Constraint equation Gauss-Seidel solver.\n * @todo The spook parameters should be specified for each constraint, not globally.\n * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf\n */\nclass GSSolver extends Solver {\n /**\n * The number of solver iterations determines quality of the constraints in the world.\n * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.\n */\n\n /**\n * When tolerance is reached, the system is assumed to be converged.\n */\n\n /**\n * @todo remove useless constructor\n */\n constructor() {\n super();\n this.iterations = 10;\n this.tolerance = 1e-7;\n }\n /**\n * Solve\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n let iter = 0;\n const maxIter = this.iterations;\n const tolSquared = this.tolerance * this.tolerance;\n const equations = this.equations;\n const Neq = equations.length;\n const bodies = world.bodies;\n const Nbodies = bodies.length;\n const h = dt;\n let B;\n let invC;\n let deltalambda;\n let deltalambdaTot;\n let GWlambda;\n let lambdaj; // Update solve mass\n\n if (Neq !== 0) {\n for (let i = 0; i !== Nbodies; i++) {\n bodies[i].updateSolveMassProperties();\n }\n } // Things that do not change during iteration can be computed once\n\n\n const invCs = GSSolver_solve_invCs;\n const Bs = GSSolver_solve_Bs;\n const lambda = GSSolver_solve_lambda;\n invCs.length = Neq;\n Bs.length = Neq;\n lambda.length = Neq;\n\n for (let i = 0; i !== Neq; i++) {\n const c = equations[i];\n lambda[i] = 0.0;\n Bs[i] = c.computeB(h);\n invCs[i] = 1.0 / c.computeC();\n }\n\n if (Neq !== 0) {\n // Reset vlambda\n for (let i = 0; i !== Nbodies; i++) {\n const b = bodies[i];\n const vlambda = b.vlambda;\n const wlambda = b.wlambda;\n vlambda.set(0, 0, 0);\n wlambda.set(0, 0, 0);\n } // Iterate over equations\n\n\n for (iter = 0; iter !== maxIter; iter++) {\n // Accumulate the total error for each iteration.\n deltalambdaTot = 0.0;\n\n for (let j = 0; j !== Neq; j++) {\n const c = equations[j]; // Compute iteration\n\n B = Bs[j];\n invC = invCs[j];\n lambdaj = lambda[j];\n GWlambda = c.computeGWlambda();\n deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval\n\n if (lambdaj + deltalambda < c.minForce) {\n deltalambda = c.minForce - lambdaj;\n } else if (lambdaj + deltalambda > c.maxForce) {\n deltalambda = c.maxForce - lambdaj;\n }\n\n lambda[j] += deltalambda;\n deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)\n\n c.addToWlambda(deltalambda);\n } // If the total error is small enough - stop iterate\n\n\n if (deltalambdaTot * deltalambdaTot < tolSquared) {\n break;\n }\n } // Add result to velocity\n\n\n for (let i = 0; i !== Nbodies; i++) {\n const b = bodies[i];\n const v = b.velocity;\n const w = b.angularVelocity;\n b.vlambda.vmul(b.linearFactor, b.vlambda);\n v.vadd(b.vlambda, v);\n b.wlambda.vmul(b.angularFactor, b.wlambda);\n w.vadd(b.wlambda, w);\n } // Set the `.multiplier` property of each equation\n\n\n let l = equations.length;\n const invDt = 1 / h;\n\n while (l--) {\n equations[l].multiplier = lambda[l] * invDt;\n }\n }\n\n return iter;\n }\n\n} // Just temporary number holders that we want to reuse each iteration.\n\nconst GSSolver_solve_lambda = [];\nconst GSSolver_solve_invCs = [];\nconst GSSolver_solve_Bs = [];\n\n/**\n * Splits the equations into islands and solves them independently. Can improve performance.\n */\nclass SplitSolver extends Solver {\n /**\n * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.\n */\n\n /**\n * When tolerance is reached, the system is assumed to be converged.\n */\n\n /** subsolver */\n constructor(subsolver) {\n super();\n this.iterations = 10;\n this.tolerance = 1e-7;\n this.subsolver = subsolver;\n this.nodes = [];\n this.nodePool = []; // Create needed nodes, reuse if possible\n\n while (this.nodePool.length < 128) {\n this.nodePool.push(this.createNode());\n }\n }\n /**\n * createNode\n */\n\n\n createNode() {\n return {\n body: null,\n children: [],\n eqs: [],\n visited: false\n };\n }\n /**\n * Solve the subsystems\n * @return number of iterations performed\n */\n\n\n solve(dt, world) {\n const nodes = SplitSolver_solve_nodes;\n const nodePool = this.nodePool;\n const bodies = world.bodies;\n const equations = this.equations;\n const Neq = equations.length;\n const Nbodies = bodies.length;\n const subsolver = this.subsolver; // Create needed nodes, reuse if possible\n\n while (nodePool.length < Nbodies) {\n nodePool.push(this.createNode());\n }\n\n nodes.length = Nbodies;\n\n for (let i = 0; i < Nbodies; i++) {\n nodes[i] = nodePool[i];\n } // Reset node values\n\n\n for (let i = 0; i !== Nbodies; i++) {\n const node = nodes[i];\n node.body = bodies[i];\n node.children.length = 0;\n node.eqs.length = 0;\n node.visited = false;\n }\n\n for (let k = 0; k !== Neq; k++) {\n const eq = equations[k];\n const i = bodies.indexOf(eq.bi);\n const j = bodies.indexOf(eq.bj);\n const ni = nodes[i];\n const nj = nodes[j];\n ni.children.push(nj);\n ni.eqs.push(eq);\n nj.children.push(ni);\n nj.eqs.push(eq);\n }\n\n let child;\n let n = 0;\n let eqs = SplitSolver_solve_eqs;\n subsolver.tolerance = this.tolerance;\n subsolver.iterations = this.iterations;\n const dummyWorld = SplitSolver_solve_dummyWorld;\n\n while (child = getUnvisitedNode(nodes)) {\n eqs.length = 0;\n dummyWorld.bodies.length = 0;\n bfs(child, visitFunc, dummyWorld.bodies, eqs);\n const Neqs = eqs.length;\n eqs = eqs.sort(sortById);\n\n for (let i = 0; i !== Neqs; i++) {\n subsolver.addEquation(eqs[i]);\n }\n\n subsolver.solve(dt, dummyWorld);\n subsolver.removeAllEquations();\n n++;\n }\n\n return n;\n }\n\n} // Returns the number of subsystems\n\nconst SplitSolver_solve_nodes = []; // All allocated node objects\n\nconst SplitSolver_solve_eqs = []; // Temp array\n\nconst SplitSolver_solve_dummyWorld = {\n bodies: []\n}; // Temp object\n\nconst STATIC = Body.STATIC;\n\nfunction getUnvisitedNode(nodes) {\n const Nnodes = nodes.length;\n\n for (let i = 0; i !== Nnodes; i++) {\n const node = nodes[i];\n\n if (!node.visited && !(node.body.type & STATIC)) {\n return node;\n }\n }\n\n return false;\n}\n\nconst queue = [];\n\nfunction bfs(root, visitFunc, bds, eqs) {\n queue.push(root);\n root.visited = true;\n visitFunc(root, bds, eqs);\n\n while (queue.length) {\n const node = queue.pop(); // Loop over unvisited child nodes\n\n let child;\n\n while (child = getUnvisitedNode(node.children)) {\n child.visited = true;\n visitFunc(child, bds, eqs);\n queue.push(child);\n }\n }\n}\n\nfunction visitFunc(node, bds, eqs) {\n bds.push(node.body);\n const Neqs = node.eqs.length;\n\n for (let i = 0; i !== Neqs; i++) {\n const eq = node.eqs[i];\n\n if (!eqs.includes(eq)) {\n eqs.push(eq);\n }\n }\n}\n\nfunction sortById(a, b) {\n return b.id - a.id;\n}\n\n/**\n * For pooling objects that can be reused.\n */\nclass Pool {\n constructor() {\n this.objects = [];\n this.type = Object;\n }\n\n /**\n * Release an object after use\n */\n release() {\n const Nargs = arguments.length;\n\n for (let i = 0; i !== Nargs; i++) {\n this.objects.push(i < 0 || arguments.length <= i ? undefined : arguments[i]);\n }\n\n return this;\n }\n /**\n * Get an object\n */\n\n\n get() {\n if (this.objects.length === 0) {\n return this.constructObject();\n } else {\n return this.objects.pop();\n }\n }\n /**\n * Construct an object. Should be implemented in each subclass.\n */\n\n\n constructObject() {\n throw new Error('constructObject() not implemented in this Pool subclass yet!');\n }\n /**\n * @return Self, for chaining\n */\n\n\n resize(size) {\n const objects = this.objects;\n\n while (objects.length > size) {\n objects.pop();\n }\n\n while (objects.length < size) {\n objects.push(this.constructObject());\n }\n\n return this;\n }\n\n}\n\n/**\n * Vec3Pool\n */\n\nclass Vec3Pool extends Pool {\n constructor() {\n super(...arguments);\n this.type = Vec3;\n }\n\n /**\n * Construct a vector\n */\n constructObject() {\n return new Vec3();\n }\n\n}\n\n// Naming rule: based of the order in SHAPE_TYPES,\n// the first part of the method is formed by the\n// shape type that comes before, in the second part\n// there is the shape type that comes after in the SHAPE_TYPES list\nconst COLLISION_TYPES = {\n sphereSphere: Shape.types.SPHERE,\n spherePlane: Shape.types.SPHERE | Shape.types.PLANE,\n boxBox: Shape.types.BOX | Shape.types.BOX,\n sphereBox: Shape.types.SPHERE | Shape.types.BOX,\n planeBox: Shape.types.PLANE | Shape.types.BOX,\n convexConvex: Shape.types.CONVEXPOLYHEDRON,\n sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,\n planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,\n boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,\n sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,\n boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,\n convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,\n sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,\n planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,\n boxParticle: Shape.types.BOX | Shape.types.PARTICLE,\n convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,\n cylinderCylinder: Shape.types.CYLINDER,\n sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,\n planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,\n boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,\n convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,\n heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,\n particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,\n sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,\n planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH\n};\n\n/**\n * Helper class for the World. Generates ContactEquations.\n * @todo Sphere-ConvexPolyhedron contacts\n * @todo Contact reduction\n * @todo should move methods to prototype\n */\nclass Narrowphase {\n /**\n * Internal storage of pooled contact points.\n */\n\n /**\n * Pooled vectors.\n */\n get [COLLISION_TYPES.sphereSphere]() {\n return this.sphereSphere;\n }\n\n get [COLLISION_TYPES.spherePlane]() {\n return this.spherePlane;\n }\n\n get [COLLISION_TYPES.boxBox]() {\n return this.boxBox;\n }\n\n get [COLLISION_TYPES.sphereBox]() {\n return this.sphereBox;\n }\n\n get [COLLISION_TYPES.planeBox]() {\n return this.planeBox;\n }\n\n get [COLLISION_TYPES.convexConvex]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.sphereConvex]() {\n return this.sphereConvex;\n }\n\n get [COLLISION_TYPES.planeConvex]() {\n return this.planeConvex;\n }\n\n get [COLLISION_TYPES.boxConvex]() {\n return this.boxConvex;\n }\n\n get [COLLISION_TYPES.sphereHeightfield]() {\n return this.sphereHeightfield;\n }\n\n get [COLLISION_TYPES.boxHeightfield]() {\n return this.boxHeightfield;\n }\n\n get [COLLISION_TYPES.convexHeightfield]() {\n return this.convexHeightfield;\n }\n\n get [COLLISION_TYPES.sphereParticle]() {\n return this.sphereParticle;\n }\n\n get [COLLISION_TYPES.planeParticle]() {\n return this.planeParticle;\n }\n\n get [COLLISION_TYPES.boxParticle]() {\n return this.boxParticle;\n }\n\n get [COLLISION_TYPES.convexParticle]() {\n return this.convexParticle;\n }\n\n get [COLLISION_TYPES.cylinderCylinder]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.sphereCylinder]() {\n return this.sphereConvex;\n }\n\n get [COLLISION_TYPES.planeCylinder]() {\n return this.planeConvex;\n }\n\n get [COLLISION_TYPES.boxCylinder]() {\n return this.boxConvex;\n }\n\n get [COLLISION_TYPES.convexCylinder]() {\n return this.convexConvex;\n }\n\n get [COLLISION_TYPES.heightfieldCylinder]() {\n return this.heightfieldCylinder;\n }\n\n get [COLLISION_TYPES.particleCylinder]() {\n return this.particleCylinder;\n }\n\n get [COLLISION_TYPES.sphereTrimesh]() {\n return this.sphereTrimesh;\n }\n\n get [COLLISION_TYPES.planeTrimesh]() {\n return this.planeTrimesh;\n } // get [COLLISION_TYPES.convexTrimesh]() {\n // return this.convexTrimesh\n // }\n\n\n constructor(world) {\n this.contactPointPool = [];\n this.frictionEquationPool = [];\n this.result = [];\n this.frictionResult = [];\n this.v3pool = new Vec3Pool();\n this.world = world;\n this.currentContactMaterial = world.defaultContactMaterial;\n this.enableFrictionReduction = false;\n }\n /**\n * Make a contact object, by using the internal pool or creating a new one.\n */\n\n\n createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {\n let c;\n\n if (this.contactPointPool.length) {\n c = this.contactPointPool.pop();\n c.bi = bi;\n c.bj = bj;\n } else {\n c = new ContactEquation(bi, bj);\n }\n\n c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;\n const cm = this.currentContactMaterial;\n c.restitution = cm.restitution;\n c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);\n const matA = si.material || bi.material;\n const matB = sj.material || bj.material;\n\n if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {\n c.restitution = matA.restitution * matB.restitution;\n }\n\n c.si = overrideShapeA || si;\n c.sj = overrideShapeB || sj;\n return c;\n }\n\n createFrictionEquationsFromContact(contactEquation, outArray) {\n const bodyA = contactEquation.bi;\n const bodyB = contactEquation.bj;\n const shapeA = contactEquation.si;\n const shapeB = contactEquation.sj;\n const world = this.world;\n const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them\n\n let friction = cm.friction;\n const matA = shapeA.material || bodyA.material;\n const matB = shapeB.material || bodyB.material;\n\n if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {\n friction = matA.friction * matB.friction;\n }\n\n if (friction > 0) {\n // Create 2 tangent equations\n // Users may provide a force different from global gravity to use when computing contact friction.\n const mug = friction * (world.frictionGravity || world.gravity).length();\n let reducedMass = bodyA.invMass + bodyB.invMass;\n\n if (reducedMass > 0) {\n reducedMass = 1 / reducedMass;\n }\n\n const pool = this.frictionEquationPool;\n const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);\n const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);\n c1.bi = c2.bi = bodyA;\n c1.bj = c2.bj = bodyB;\n c1.minForce = c2.minForce = -mug * reducedMass;\n c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors\n\n c1.ri.copy(contactEquation.ri);\n c1.rj.copy(contactEquation.rj);\n c2.ri.copy(contactEquation.ri);\n c2.rj.copy(contactEquation.rj); // Construct tangents\n\n contactEquation.ni.tangents(c1.t, c2.t); // Set spook params\n\n c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);\n c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);\n c1.enabled = c2.enabled = contactEquation.enabled;\n outArray.push(c1, c2);\n return true;\n }\n\n return false;\n }\n /**\n * Take the average N latest contact point on the plane.\n */\n\n\n createFrictionFromAverage(numContacts) {\n // The last contactEquation\n let c = this.result[this.result.length - 1]; // Create the result: two \"average\" friction equations\n\n if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {\n return;\n }\n\n const f1 = this.frictionResult[this.frictionResult.length - 2];\n const f2 = this.frictionResult[this.frictionResult.length - 1];\n averageNormal.setZero();\n averageContactPointA.setZero();\n averageContactPointB.setZero();\n const bodyA = c.bi;\n c.bj;\n\n for (let i = 0; i !== numContacts; i++) {\n c = this.result[this.result.length - 1 - i];\n\n if (c.bi !== bodyA) {\n averageNormal.vadd(c.ni, averageNormal);\n averageContactPointA.vadd(c.ri, averageContactPointA);\n averageContactPointB.vadd(c.rj, averageContactPointB);\n } else {\n averageNormal.vsub(c.ni, averageNormal);\n averageContactPointA.vadd(c.rj, averageContactPointA);\n averageContactPointB.vadd(c.ri, averageContactPointB);\n }\n }\n\n const invNumContacts = 1 / numContacts;\n averageContactPointA.scale(invNumContacts, f1.ri);\n averageContactPointB.scale(invNumContacts, f1.rj);\n f2.ri.copy(f1.ri); // Should be the same\n\n f2.rj.copy(f1.rj);\n averageNormal.normalize();\n averageNormal.tangents(f1.t, f2.t); // return eq;\n }\n /**\n * Generate all contacts between a list of body pairs\n * @param p1 Array of body indices\n * @param p2 Array of body indices\n * @param result Array to store generated contacts\n * @param oldcontacts Optional. Array of reusable contact objects\n */\n\n\n getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {\n // Save old contact objects\n this.contactPointPool = oldcontacts;\n this.frictionEquationPool = frictionPool;\n this.result = result;\n this.frictionResult = frictionResult;\n const qi = tmpQuat1;\n const qj = tmpQuat2;\n const xi = tmpVec1;\n const xj = tmpVec2;\n\n for (let k = 0, N = p1.length; k !== N; k++) {\n // Get current collision bodies\n const bi = p1[k];\n const bj = p2[k]; // Get contact material\n\n let bodyContactMaterial = null;\n\n if (bi.material && bj.material) {\n bodyContactMaterial = world.getContactMaterial(bi.material, bj.material) || null;\n }\n\n const justTest = bi.type & Body.KINEMATIC && bj.type & Body.STATIC || bi.type & Body.STATIC && bj.type & Body.KINEMATIC || bi.type & Body.KINEMATIC && bj.type & Body.KINEMATIC;\n\n for (let i = 0; i < bi.shapes.length; i++) {\n bi.quaternion.mult(bi.shapeOrientations[i], qi);\n bi.quaternion.vmult(bi.shapeOffsets[i], xi);\n xi.vadd(bi.position, xi);\n const si = bi.shapes[i];\n\n for (let j = 0; j < bj.shapes.length; j++) {\n // Compute world transform of shapes\n bj.quaternion.mult(bj.shapeOrientations[j], qj);\n bj.quaternion.vmult(bj.shapeOffsets[j], xj);\n xj.vadd(bj.position, xj);\n const sj = bj.shapes[j];\n\n if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {\n continue;\n }\n\n if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {\n continue;\n } // Get collision material\n\n\n let shapeContactMaterial = null;\n\n if (si.material && sj.material) {\n shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;\n }\n\n this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts\n\n const resolverIndex = si.type | sj.type;\n const resolver = this[resolverIndex];\n\n if (resolver) {\n let retval = false; // TO DO: investigate why sphereParticle and convexParticle\n // resolvers expect si and sj shapes to be in reverse order\n // (i.e. larger integer value type first instead of smaller first)\n\n if (si.type < sj.type) {\n retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n } else {\n retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);\n }\n\n if (retval && justTest) {\n // Register overlap\n world.shapeOverlapKeeper.set(si.id, sj.id);\n world.bodyOverlapKeeper.set(bi.id, bj.id);\n }\n }\n }\n }\n }\n }\n\n sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n if (justTest) {\n return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;\n } // We will have only one contact in this case\n\n\n const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal\n\n xj.vsub(xi, contactEq.ni);\n contactEq.ni.normalize(); // Contact point locations\n\n contactEq.ri.copy(contactEq.ni);\n contactEq.rj.copy(contactEq.ni);\n contactEq.ri.scale(si.radius, contactEq.ri);\n contactEq.rj.scale(-sj.radius, contactEq.rj);\n contactEq.ri.vadd(xi, contactEq.ri);\n contactEq.ri.vsub(bi.position, contactEq.ri);\n contactEq.rj.vadd(xj, contactEq.rj);\n contactEq.rj.vsub(bj.position, contactEq.rj);\n this.result.push(contactEq);\n this.createFrictionEquationsFromContact(contactEq, this.frictionResult);\n }\n\n spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n // We will have one contact in this case\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal\n\n r.ni.set(0, 0, 1);\n qj.vmult(r.ni, r.ni);\n r.ni.negate(r.ni); // body i is the sphere, flip normal\n\n r.ni.normalize(); // Needed?\n // Vector from sphere center to contact point\n\n r.ni.scale(si.radius, r.ri); // Project down sphere on plane\n\n xi.vsub(xj, point_on_plane_to_sphere);\n r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);\n point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane\n\n if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {\n if (justTest) {\n return true;\n } // Make it relative to the body\n\n\n const ri = r.ri;\n const rj = r.rj;\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n sj.convexPolyhedronRepresentation.material = sj.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;\n return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n const v3pool = this.v3pool; // we refer to the box as body j\n\n const sides = sphereBox_sides;\n xi.vsub(xj, box_to_sphere);\n sj.getSideNormals(sides, qj);\n const R = si.radius;\n\n let found = false; // Store the resulting side penetration info\n\n const side_ns = sphereBox_side_ns;\n const side_ns1 = sphereBox_side_ns1;\n const side_ns2 = sphereBox_side_ns2;\n let side_h = null;\n let side_penetrations = 0;\n let side_dot1 = 0;\n let side_dot2 = 0;\n let side_distance = null;\n\n for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {\n // Get the plane side normal (ns)\n const ns = sphereBox_ns;\n ns.copy(sides[idx]);\n const h = ns.length();\n ns.normalize(); // The normal/distance dot product tells which side of the plane we are\n\n const dot = box_to_sphere.dot(ns);\n\n if (dot < h + R && dot > 0) {\n // Intersects plane. Now check the other two dimensions\n const ns1 = sphereBox_ns1;\n const ns2 = sphereBox_ns2;\n ns1.copy(sides[(idx + 1) % 3]);\n ns2.copy(sides[(idx + 2) % 3]);\n const h1 = ns1.length();\n const h2 = ns2.length();\n ns1.normalize();\n ns2.normalize();\n const dot1 = box_to_sphere.dot(ns1);\n const dot2 = box_to_sphere.dot(ns2);\n\n if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {\n const dist = Math.abs(dot - h - R);\n\n if (side_distance === null || dist < side_distance) {\n side_distance = dist;\n side_dot1 = dot1;\n side_dot2 = dot2;\n side_h = h;\n side_ns.copy(ns);\n side_ns1.copy(ns1);\n side_ns2.copy(ns2);\n side_penetrations++;\n\n if (justTest) {\n return true;\n }\n }\n }\n }\n }\n\n if (side_penetrations) {\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n side_ns.scale(-R, r.ri); // Sphere r\n\n r.ni.copy(side_ns);\n r.ni.negate(r.ni); // Normal should be out of sphere\n\n side_ns.scale(side_h, side_ns);\n side_ns1.scale(side_dot1, side_ns1);\n side_ns.vadd(side_ns1, side_ns);\n side_ns2.scale(side_dot2, side_ns2);\n side_ns.vadd(side_ns2, r.rj); // Make relative to bodies\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n } // Check corners\n\n\n let rj = v3pool.get();\n const sphere_to_corner = sphereBox_sphere_to_corner;\n\n for (let j = 0; j !== 2 && !found; j++) {\n for (let k = 0; k !== 2 && !found; k++) {\n for (let l = 0; l !== 2 && !found; l++) {\n rj.set(0, 0, 0);\n\n if (j) {\n rj.vadd(sides[0], rj);\n } else {\n rj.vsub(sides[0], rj);\n }\n\n if (k) {\n rj.vadd(sides[1], rj);\n } else {\n rj.vsub(sides[1], rj);\n }\n\n if (l) {\n rj.vadd(sides[2], rj);\n } else {\n rj.vsub(sides[2], rj);\n } // World position of corner\n\n\n xj.vadd(rj, sphere_to_corner);\n sphere_to_corner.vsub(xi, sphere_to_corner);\n\n if (sphere_to_corner.lengthSquared() < R * R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ri.copy(sphere_to_corner);\n r.ri.normalize();\n r.ni.copy(r.ri);\n r.ri.scale(R, r.ri);\n r.rj.copy(rj); // Make relative to bodies\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n }\n\n v3pool.release(rj);\n rj = null; // Check edges\n\n const edgeTangent = v3pool.get();\n const edgeCenter = v3pool.get();\n const r = v3pool.get(); // r = edge center to sphere center\n\n const orthogonal = v3pool.get();\n const dist = v3pool.get();\n const Nsides = sides.length;\n\n for (let j = 0; j !== Nsides && !found; j++) {\n for (let k = 0; k !== Nsides && !found; k++) {\n if (j % 3 !== k % 3) {\n // Get edge tangent\n sides[k].cross(sides[j], edgeTangent);\n edgeTangent.normalize();\n sides[j].vadd(sides[k], edgeCenter);\n r.copy(xi);\n r.vsub(edgeCenter, r);\n r.vsub(xj, r);\n const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction\n\n edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction\n // Find the third side orthogonal to this one\n\n let l = 0;\n\n while (l === j % 3 || l === k % 3) {\n l++;\n } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent\n\n\n dist.copy(xi);\n dist.vsub(orthogonal, dist);\n dist.vsub(edgeCenter, dist);\n dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it\n\n const tdist = Math.abs(orthonorm);\n const ndist = dist.length();\n\n if (tdist < sides[l].length() && ndist < R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n edgeCenter.vadd(orthogonal, res.rj); // box rj\n\n res.rj.copy(res.rj);\n dist.negate(res.ni);\n res.ni.normalize();\n res.ri.copy(res.rj);\n res.ri.vadd(xj, res.ri);\n res.ri.vsub(xi, res.ri);\n res.ri.normalize();\n res.ri.scale(R, res.ri); // Make relative to bodies\n\n res.ri.vadd(xi, res.ri);\n res.ri.vsub(bi.position, res.ri);\n res.rj.vadd(xj, res.rj);\n res.rj.vsub(bj.position, res.rj);\n this.result.push(res);\n this.createFrictionEquationsFromContact(res, this.frictionResult);\n }\n }\n }\n }\n\n v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);\n }\n\n planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n sj.convexPolyhedronRepresentation.material = sj.material;\n sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;\n sj.convexPolyhedronRepresentation.id = sj.id;\n return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {\n const sepAxis = convexConvex_sepAxis;\n\n if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {\n return;\n }\n\n if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {\n const res = [];\n const q = convexConvex_q;\n si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res);\n let numContacts = 0;\n\n for (let j = 0; j !== res.length; j++) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n const ri = r.ri;\n const rj = r.rj;\n sepAxis.negate(r.ni);\n res[j].normal.negate(q);\n q.scale(res[j].depth, q);\n res[j].point.vadd(q, ri);\n rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative\n\n ri.vsub(xi, ri);\n rj.vsub(xj, rj); // Make relative to bodies\n\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n numContacts++;\n\n if (!this.enableFrictionReduction) {\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n if (this.enableFrictionReduction && numContacts) {\n this.createFrictionFromAverage(numContacts);\n }\n }\n }\n\n sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n const v3pool = this.v3pool;\n xi.vsub(xj, convex_to_sphere);\n const normals = sj.faceNormals;\n const faces = sj.faces;\n const verts = sj.vertices;\n const R = si.radius;\n // return;\n // }\n\n let found = false; // Check corners\n\n for (let i = 0; i !== verts.length; i++) {\n const v = verts[i]; // World position of corner\n\n const worldCorner = sphereConvex_worldCorner;\n qj.vmult(v, worldCorner);\n xj.vadd(worldCorner, worldCorner);\n const sphere_to_corner = sphereConvex_sphereToCorner;\n worldCorner.vsub(xi, sphere_to_corner);\n\n if (sphere_to_corner.lengthSquared() < R * R) {\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ri.copy(sphere_to_corner);\n r.ri.normalize();\n r.ni.copy(r.ri);\n r.ri.scale(R, r.ri);\n worldCorner.vsub(xj, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n return;\n }\n } // Check side (plane) intersections\n\n\n for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {\n const normal = normals[i];\n const face = faces[i]; // Get world-transformed normal of the face\n\n const worldNormal = sphereConvex_worldNormal;\n qj.vmult(normal, worldNormal); // Get a world vertex from the face\n\n const worldPoint = sphereConvex_worldPoint;\n qj.vmult(verts[face[0]], worldPoint);\n worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal\n\n const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;\n worldNormal.scale(-R, worldSpherePointClosestToPlane);\n xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere\n\n const penetrationVec = sphereConvex_penetrationVec;\n worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.\n\n const penetration = penetrationVec.dot(worldNormal);\n const worldPointToSphere = sphereConvex_sphereToWorldPoint;\n xi.vsub(worldPoint, worldPointToSphere);\n\n if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {\n // Intersects plane. Now check if the sphere is inside the face polygon\n const faceVerts = []; // Face vertices, in world coords\n\n for (let j = 0, Nverts = face.length; j !== Nverts; j++) {\n const worldVertex = v3pool.get();\n qj.vmult(verts[face[j]], worldVertex);\n xj.vadd(worldVertex, worldVertex);\n faceVerts.push(worldVertex);\n }\n\n if (pointInPolygon(faceVerts, worldNormal, xi)) {\n // Is the sphere center in the face polygon?\n if (justTest) {\n return true;\n }\n\n found = true;\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact\n\n worldNormal.negate(r.ni); // Normal pointing out of sphere\n\n const penetrationVec2 = v3pool.get();\n worldNormal.scale(-penetration, penetrationVec2);\n const penetrationSpherePoint = v3pool.get();\n worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);\n\n xi.vsub(xj, r.rj);\n r.rj.vadd(penetrationSpherePoint, r.rj);\n r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n v3pool.release(penetrationVec2);\n v3pool.release(penetrationSpherePoint);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n\n return; // We only expect *one* face contact\n } else {\n // Edge?\n for (let j = 0; j !== face.length; j++) {\n // Get two world transformed vertices\n const v1 = v3pool.get();\n const v2 = v3pool.get();\n qj.vmult(verts[face[(j + 1) % face.length]], v1);\n qj.vmult(verts[face[(j + 2) % face.length]], v2);\n xj.vadd(v1, v1);\n xj.vadd(v2, v2); // Construct edge vector\n\n const edge = sphereConvex_edge;\n v2.vsub(v1, edge); // Construct the same vector, but normalized\n\n const edgeUnit = sphereConvex_edgeUnit;\n edge.unit(edgeUnit); // p is xi projected onto the edge\n\n const p = v3pool.get();\n const v1_to_xi = v3pool.get();\n xi.vsub(v1, v1_to_xi);\n const dot = v1_to_xi.dot(edgeUnit);\n edgeUnit.scale(dot, p);\n p.vadd(v1, p); // Compute a vector from p to the center of the sphere\n\n const xi_to_p = v3pool.get();\n p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius\n // AND if p is in between v1 and v2\n\n if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {\n // Collision if the edge-sphere distance is less than the radius\n // Edge contact!\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n p.vsub(xj, r.rj);\n p.vsub(xi, r.ni);\n r.ni.normalize();\n r.ni.scale(R, r.ri); // Should be relative to the body.\n\n r.rj.vadd(xj, r.rj);\n r.rj.vsub(bj.position, r.rj); // Should be relative to the body.\n\n r.ri.vadd(xi, r.ri);\n r.ri.vsub(bi.position, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n\n v3pool.release(v1);\n v3pool.release(v2);\n v3pool.release(p);\n v3pool.release(xi_to_p);\n v3pool.release(v1_to_xi);\n return;\n }\n\n v3pool.release(v1);\n v3pool.release(v2);\n v3pool.release(p);\n v3pool.release(xi_to_p);\n v3pool.release(v1_to_xi);\n }\n } // Release world vertices\n\n\n for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {\n v3pool.release(faceVerts[j]);\n }\n }\n }\n }\n\n planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {\n // Simply return the points behind the plane.\n const worldVertex = planeConvex_v;\n const worldNormal = planeConvex_normal;\n worldNormal.set(0, 0, 1);\n planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation\n\n let numContacts = 0;\n const relpos = planeConvex_relpos;\n\n for (let i = 0; i !== convexShape.vertices.length; i++) {\n // Get world convex vertex\n worldVertex.copy(convexShape.vertices[i]);\n convexQuat.vmult(worldVertex, worldVertex);\n convexPosition.vadd(worldVertex, worldVertex);\n worldVertex.vsub(planePosition, relpos);\n const dot = worldNormal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane\n\n const projected = planeConvex_projected;\n worldNormal.scale(worldNormal.dot(relpos), projected);\n worldVertex.vsub(projected, projected);\n projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane\n\n r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane\n // rj is now just the vector from the convex center to the vertex\n\n worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body\n\n r.ri.vadd(planePosition, r.ri);\n r.ri.vsub(planeBody.position, r.ri);\n r.rj.vadd(convexPosition, r.rj);\n r.rj.vsub(convexBody.position, r.rj);\n this.result.push(r);\n numContacts++;\n\n if (!this.enableFrictionReduction) {\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n\n if (this.enableFrictionReduction && numContacts) {\n this.createFrictionFromAverage(numContacts);\n }\n }\n\n boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {\n const data = hfShape.data;\n const radius = sphereShape.radius;\n const w = hfShape.elementSize;\n const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!\n\n const localSpherePos = sphereHeightfield_tmp1;\n Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against\n\n let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;\n let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;\n let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;\n let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain\n\n if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {\n return;\n } // Clamp index to edges\n\n\n if (iMinX < 0) {\n iMinX = 0;\n }\n\n if (iMaxX < 0) {\n iMaxX = 0;\n }\n\n if (iMinY < 0) {\n iMinY = 0;\n }\n\n if (iMaxY < 0) {\n iMaxY = 0;\n }\n\n if (iMinX >= data.length) {\n iMinX = data.length - 1;\n }\n\n if (iMaxX >= data.length) {\n iMaxX = data.length - 1;\n }\n\n if (iMaxY >= data[0].length) {\n iMaxY = data[0].length - 1;\n }\n\n if (iMinY >= data[0].length) {\n iMinY = data[0].length - 1;\n }\n\n const minMax = [];\n hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);\n const min = minMax[0];\n const max = minMax[1]; // Bail out if we can't touch the bounding height box\n\n if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {\n return;\n }\n\n const result = this.result;\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n const numContactsBefore = result.length;\n let intersecting = false; // Lower triangle\n\n hfShape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {\n intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);\n }\n\n if (justTest && intersecting) {\n return true;\n } // Upper triangle\n\n\n hfShape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {\n intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);\n }\n\n if (justTest && intersecting) {\n return true;\n }\n\n const numContacts = result.length - numContactsBefore;\n\n if (numContacts > 2) {\n return;\n }\n /*\n // Skip all but 1\n for (let k = 0; k < numContacts - 1; k++) {\n result.pop();\n }\n */\n\n }\n }\n }\n\n boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexHeightfield(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest) {\n const data = hfShape.data;\n const w = hfShape.elementSize;\n const radius = convexShape.boundingSphereRadius;\n const worldPillarOffset = convexHeightfield_tmp2;\n const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!\n\n const localConvexPos = convexHeightfield_tmp1;\n Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against\n\n let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;\n let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;\n let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;\n let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain\n\n if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {\n return;\n } // Clamp index to edges\n\n\n if (iMinX < 0) {\n iMinX = 0;\n }\n\n if (iMaxX < 0) {\n iMaxX = 0;\n }\n\n if (iMinY < 0) {\n iMinY = 0;\n }\n\n if (iMaxY < 0) {\n iMaxY = 0;\n }\n\n if (iMinX >= data.length) {\n iMinX = data.length - 1;\n }\n\n if (iMaxX >= data.length) {\n iMaxX = data.length - 1;\n }\n\n if (iMaxY >= data[0].length) {\n iMaxY = data[0].length - 1;\n }\n\n if (iMinY >= data[0].length) {\n iMinY = data[0].length - 1;\n }\n\n const minMax = [];\n hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);\n const min = minMax[0];\n const max = minMax[1]; // Bail out if we're cant touch the bounding height box\n\n if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {\n return;\n }\n\n for (let i = iMinX; i < iMaxX; i++) {\n for (let j = iMinY; j < iMaxY; j++) {\n let intersecting = false; // Lower triangle\n\n hfShape.getConvexTrianglePillar(i, j, false);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {\n intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);\n }\n\n if (justTest && intersecting) {\n return true;\n } // Upper triangle\n\n\n hfShape.getConvexTrianglePillar(i, j, true);\n Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);\n\n if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {\n intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);\n }\n\n if (justTest && intersecting) {\n return true;\n }\n }\n }\n }\n\n sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n // The normal is the unit vector from sphere center to particle center\n const normal = particleSphere_normal;\n normal.set(0, 0, 1);\n xi.vsub(xj, normal);\n const lengthSquared = normal.lengthSquared();\n\n if (lengthSquared <= sj.radius * sj.radius) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n normal.normalize();\n r.rj.copy(normal);\n r.rj.scale(sj.radius, r.rj);\n r.ni.copy(normal); // Contact normal\n\n r.ni.negate(r.ni);\n r.ri.set(0, 0, 0); // Center of particle\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n const normal = particlePlane_normal;\n normal.set(0, 0, 1);\n bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation\n\n const relpos = particlePlane_relpos;\n xi.vsub(bj.position, relpos);\n const dot = normal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n r.ni.copy(normal); // Contact normal is the plane normal\n\n r.ni.negate(r.ni);\n r.ri.set(0, 0, 0); // Center of particle\n // Get particle position projected on plane\n\n const projected = particlePlane_projected;\n normal.scale(normal.dot(xi), projected);\n xi.vsub(projected, projected); //projected.vadd(bj.position,projected);\n // rj is now the projected world position minus plane position\n\n r.rj.copy(projected);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n si.convexPolyhedronRepresentation.material = si.material;\n si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;\n return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);\n }\n\n convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {\n let penetratedFaceIndex = -1;\n const penetratedFaceNormal = convexParticle_penetratedFaceNormal;\n const worldPenetrationVec = convexParticle_worldPenetrationVec;\n let minPenetration = null;\n\n const local = convexParticle_local;\n local.copy(xi);\n local.vsub(xj, local); // Convert position to relative the convex origin\n\n qj.conjugate(cqj);\n cqj.vmult(local, local);\n\n if (sj.pointIsInside(local)) {\n if (sj.worldVerticesNeedsUpdate) {\n sj.computeWorldVertices(xj, qj);\n }\n\n if (sj.worldFaceNormalsNeedsUpdate) {\n sj.computeWorldFaceNormals(qj);\n } // For each world polygon in the polyhedra\n\n\n for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {\n // Construct world face vertices\n const verts = [sj.worldVertices[sj.faces[i][0]]];\n const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.\n\n xi.vsub(verts[0], convexParticle_vertexToParticle);\n const penetration = -normal.dot(convexParticle_vertexToParticle);\n\n if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {\n if (justTest) {\n return true;\n }\n\n minPenetration = penetration;\n penetratedFaceIndex = i;\n penetratedFaceNormal.copy(normal);\n }\n }\n\n if (penetratedFaceIndex !== -1) {\n // Setup contact\n const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);\n penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face\n\n worldPenetrationVec.vadd(xi, worldPenetrationVec);\n worldPenetrationVec.vsub(xj, worldPenetrationVec);\n r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);\n //projectedToFace.copy(r.rj);\n //qj.vmult(r.rj,r.rj);\n\n penetratedFaceNormal.negate(r.ni); // Contact normal\n\n r.ri.set(0, 0, 0); // Center of particle\n\n const ri = r.ri;\n const rj = r.rj; // Make relative to bodies\n\n ri.vadd(xi, ri);\n ri.vsub(bi.position, ri);\n rj.vadd(xj, rj);\n rj.vsub(bj.position, rj);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n } else {\n console.warn('Point found inside convex, but did not find penetrating face!');\n }\n }\n }\n\n heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {\n return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);\n }\n\n particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {\n return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);\n }\n\n sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {\n const edgeVertexA = sphereTrimesh_edgeVertexA;\n const edgeVertexB = sphereTrimesh_edgeVertexB;\n const edgeVector = sphereTrimesh_edgeVector;\n const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;\n const localSpherePos = sphereTrimesh_localSpherePos;\n const tmp = sphereTrimesh_tmp;\n const localSphereAABB = sphereTrimesh_localSphereAABB;\n const v2 = sphereTrimesh_v2;\n const relpos = sphereTrimesh_relpos;\n const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh\n\n Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh\n\n const sphereRadius = sphereShape.radius;\n localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);\n localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);\n trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All\n // Vertices\n\n const v = sphereTrimesh_v;\n const radiusSquared = sphereShape.radius * sphereShape.radius;\n\n for (let i = 0; i < triangles.length; i++) {\n for (let j = 0; j < 3; j++) {\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere\n\n v.vsub(localSpherePos, relpos);\n\n if (relpos.lengthSquared() <= radiusSquared) {\n // Safe up\n v2.copy(v);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);\n v.vsub(spherePos, relpos);\n\n if (justTest) {\n return true;\n }\n\n let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n r.ni.copy(relpos);\n r.ni.normalize(); // ri is the vector from sphere center to the sphere surface\n\n r.ri.copy(r.ni);\n r.ri.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n r.rj.copy(v);\n r.rj.vsub(trimeshBody.position, r.rj); // Store result\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n } // Check all edges\n\n\n for (let i = 0; i < triangles.length; i++) {\n for (let j = 0; j < 3; j++) {\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);\n trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);\n edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge\n\n localSpherePos.vsub(edgeVertexB, tmp);\n const positionAlongEdgeB = tmp.dot(edgeVector);\n localSpherePos.vsub(edgeVertexA, tmp);\n let positionAlongEdgeA = tmp.dot(edgeVector);\n\n if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {\n // Now check the orthogonal distance from edge to sphere center\n localSpherePos.vsub(edgeVertexA, tmp);\n edgeVectorUnit.copy(edgeVector);\n edgeVectorUnit.normalize();\n positionAlongEdgeA = tmp.dot(edgeVectorUnit);\n edgeVectorUnit.scale(positionAlongEdgeA, tmp);\n tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame\n\n const dist = tmp.distanceTo(localSpherePos);\n\n if (dist < sphereShape.radius) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n tmp.vsub(localSpherePos, r.ni);\n r.ni.normalize();\n r.ni.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);\n tmp.vsub(trimeshBody.position, r.rj);\n Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);\n Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n }\n } // Triangle faces\n\n\n const va = sphereTrimesh_va;\n const vb = sphereTrimesh_vb;\n const vc = sphereTrimesh_vc;\n const normal = sphereTrimesh_normal;\n\n for (let i = 0, N = triangles.length; i !== N; i++) {\n trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);\n trimeshShape.getNormal(triangles[i], normal);\n localSpherePos.vsub(va, tmp);\n let dist = tmp.dot(normal);\n normal.scale(dist, tmp);\n localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane\n\n dist = tmp.distanceTo(localSpherePos);\n\n if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {\n if (justTest) {\n return true;\n }\n\n let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);\n tmp.vsub(localSpherePos, r.ni);\n r.ni.normalize();\n r.ni.scale(sphereShape.radius, r.ri);\n r.ri.vadd(spherePos, r.ri);\n r.ri.vsub(sphereBody.position, r.ri);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);\n tmp.vsub(trimeshBody.position, r.rj);\n Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);\n Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n\n triangles.length = 0;\n }\n\n planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {\n // Make contacts!\n const v = new Vec3();\n const normal = planeTrimesh_normal;\n normal.set(0, 0, 1);\n planeQuat.vmult(normal, normal); // Turn normal according to plane\n\n for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {\n // Get world vertex from trimesh\n trimeshShape.getVertex(i, v); // Safe up\n\n const v2 = new Vec3();\n v2.copy(v);\n Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side\n\n const relpos = planeTrimesh_relpos;\n v.vsub(planePos, relpos);\n const dot = normal.dot(relpos);\n\n if (dot <= 0.0) {\n if (justTest) {\n return true;\n }\n\n const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);\n r.ni.copy(normal); // Contact normal is the plane normal\n // Get vertex position projected on plane\n\n const projected = planeTrimesh_projected;\n normal.scale(relpos.dot(normal), projected);\n v.vsub(projected, projected); // ri is the projected world position minus plane position\n\n r.ri.copy(projected);\n r.ri.vsub(planeBody.position, r.ri);\n r.rj.copy(v);\n r.rj.vsub(trimeshBody.position, r.rj); // Store result\n\n this.result.push(r);\n this.createFrictionEquationsFromContact(r, this.frictionResult);\n }\n }\n } // convexTrimesh(\n // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,\n // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,\n // faceListA?: number[] | null, faceListB?: number[] | null,\n // ) {\n // const sepAxis = convexConvex_sepAxis;\n // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){\n // return;\n // }\n // // Construct a temp hull for each triangle\n // const hullB = new ConvexPolyhedron();\n // hullB.faces = [[0,1,2]];\n // const va = new Vec3();\n // const vb = new Vec3();\n // const vc = new Vec3();\n // hullB.vertices = [\n // va,\n // vb,\n // vc\n // ];\n // for (let i = 0; i < sj.indices.length / 3; i++) {\n // const triangleNormal = new Vec3();\n // sj.getNormal(i, triangleNormal);\n // hullB.faceNormals = [triangleNormal];\n // sj.getTriangleVertices(i, va, vb, vc);\n // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);\n // if(!d){\n // triangleNormal.scale(-1, triangleNormal);\n // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);\n // if(!d){\n // continue;\n // }\n // }\n // const res: ConvexPolyhedronContactPoint[] = [];\n // const q = convexConvex_q;\n // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);\n // for(let j = 0; j !== res.length; j++){\n // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),\n // ri = r.ri,\n // rj = r.rj;\n // r.ni.copy(triangleNormal);\n // r.ni.negate(r.ni);\n // res[j].normal.negate(q);\n // q.mult(res[j].depth, q);\n // res[j].point.vadd(q, ri);\n // rj.copy(res[j].point);\n // // Contact points are in world coordinates. Transform back to relative\n // ri.vsub(xi,ri);\n // rj.vsub(xj,rj);\n // // Make relative to bodies\n // ri.vadd(xi, ri);\n // ri.vsub(bi.position, ri);\n // rj.vadd(xj, rj);\n // rj.vsub(bj.position, rj);\n // result.push(r);\n // }\n // }\n // }\n\n\n}\nconst averageNormal = new Vec3();\nconst averageContactPointA = new Vec3();\nconst averageContactPointB = new Vec3();\nconst tmpVec1 = new Vec3();\nconst tmpVec2 = new Vec3();\nconst tmpQuat1 = new Quaternion();\nconst tmpQuat2 = new Quaternion();\n\nconst planeTrimesh_normal = new Vec3();\nconst planeTrimesh_relpos = new Vec3();\nconst planeTrimesh_projected = new Vec3();\nconst sphereTrimesh_normal = new Vec3();\nconst sphereTrimesh_relpos = new Vec3();\nnew Vec3();\nconst sphereTrimesh_v = new Vec3();\nconst sphereTrimesh_v2 = new Vec3();\nconst sphereTrimesh_edgeVertexA = new Vec3();\nconst sphereTrimesh_edgeVertexB = new Vec3();\nconst sphereTrimesh_edgeVector = new Vec3();\nconst sphereTrimesh_edgeVectorUnit = new Vec3();\nconst sphereTrimesh_localSpherePos = new Vec3();\nconst sphereTrimesh_tmp = new Vec3();\nconst sphereTrimesh_va = new Vec3();\nconst sphereTrimesh_vb = new Vec3();\nconst sphereTrimesh_vc = new Vec3();\nconst sphereTrimesh_localSphereAABB = new AABB();\nconst sphereTrimesh_triangles = [];\nconst point_on_plane_to_sphere = new Vec3();\nconst plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html\n\nconst pointInPolygon_edge = new Vec3();\nconst pointInPolygon_edge_x_normal = new Vec3();\nconst pointInPolygon_vtp = new Vec3();\n\nfunction pointInPolygon(verts, normal, p) {\n let positiveResult = null;\n const N = verts.length;\n\n for (let i = 0; i !== N; i++) {\n const v = verts[i]; // Get edge to the next vertex\n\n const edge = pointInPolygon_edge;\n verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge\n\n const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();\n\n edge.cross(normal, edge_x_normal); // Get vector between point and current vertex\n\n const vertex_to_p = pointInPolygon_vtp;\n p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is\n\n const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.\n\n if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {\n if (positiveResult === null) {\n positiveResult = r > 0;\n }\n\n continue;\n } else {\n return false; // Encountered some other sign. Exit.\n }\n } // If we got here, all dot products were of the same sign.\n\n\n return true;\n}\n\nconst box_to_sphere = new Vec3();\nconst sphereBox_ns = new Vec3();\nconst sphereBox_ns1 = new Vec3();\nconst sphereBox_ns2 = new Vec3();\nconst sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];\nconst sphereBox_sphere_to_corner = new Vec3();\nconst sphereBox_side_ns = new Vec3();\nconst sphereBox_side_ns1 = new Vec3();\nconst sphereBox_side_ns2 = new Vec3();\nconst convex_to_sphere = new Vec3();\nconst sphereConvex_edge = new Vec3();\nconst sphereConvex_edgeUnit = new Vec3();\nconst sphereConvex_sphereToCorner = new Vec3();\nconst sphereConvex_worldCorner = new Vec3();\nconst sphereConvex_worldNormal = new Vec3();\nconst sphereConvex_worldPoint = new Vec3();\nconst sphereConvex_worldSpherePointClosestToPlane = new Vec3();\nconst sphereConvex_penetrationVec = new Vec3();\nconst sphereConvex_sphereToWorldPoint = new Vec3();\nnew Vec3();\nnew Vec3();\nconst planeConvex_v = new Vec3();\nconst planeConvex_normal = new Vec3();\nconst planeConvex_relpos = new Vec3();\nconst planeConvex_projected = new Vec3();\nconst convexConvex_sepAxis = new Vec3();\nconst convexConvex_q = new Vec3();\nconst particlePlane_normal = new Vec3();\nconst particlePlane_relpos = new Vec3();\nconst particlePlane_projected = new Vec3();\nconst particleSphere_normal = new Vec3(); // WIP\n\nconst cqj = new Quaternion();\nconst convexParticle_local = new Vec3();\nnew Vec3();\nconst convexParticle_penetratedFaceNormal = new Vec3();\nconst convexParticle_vertexToParticle = new Vec3();\nconst convexParticle_worldPenetrationVec = new Vec3();\nconst convexHeightfield_tmp1 = new Vec3();\nconst convexHeightfield_tmp2 = new Vec3();\nconst convexHeightfield_faceList = [0];\nconst sphereHeightfield_tmp1 = new Vec3();\nconst sphereHeightfield_tmp2 = new Vec3();\n\nclass OverlapKeeper {\n /**\n * @todo Remove useless constructor\n */\n constructor() {\n this.current = [];\n this.previous = [];\n }\n /**\n * getKey\n */\n\n\n getKey(i, j) {\n if (j < i) {\n const temp = j;\n j = i;\n i = temp;\n }\n\n return i << 16 | j;\n }\n /**\n * set\n */\n\n\n set(i, j) {\n // Insertion sort. This way the diff will have linear complexity.\n const key = this.getKey(i, j);\n const current = this.current;\n let index = 0;\n\n while (key > current[index]) {\n index++;\n }\n\n if (key === current[index]) {\n return; // Pair was already added\n }\n\n for (let j = current.length - 1; j >= index; j--) {\n current[j + 1] = current[j];\n }\n\n current[index] = key;\n }\n /**\n * tick\n */\n\n\n tick() {\n const tmp = this.current;\n this.current = this.previous;\n this.previous = tmp;\n this.current.length = 0;\n }\n /**\n * getDiff\n */\n\n\n getDiff(additions, removals) {\n const a = this.current;\n const b = this.previous;\n const al = a.length;\n const bl = b.length;\n let j = 0;\n\n for (let i = 0; i < al; i++) {\n let found = false;\n const keyA = a[i];\n\n while (keyA > b[j]) {\n j++;\n }\n\n found = keyA === b[j];\n\n if (!found) {\n unpackAndPush(additions, keyA);\n }\n }\n\n j = 0;\n\n for (let i = 0; i < bl; i++) {\n let found = false;\n const keyB = b[i];\n\n while (keyB > a[j]) {\n j++;\n }\n\n found = a[j] === keyB;\n\n if (!found) {\n unpackAndPush(removals, keyB);\n }\n }\n }\n\n}\n\nfunction unpackAndPush(array, key) {\n array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);\n}\n\nconst getKey = (i, j) => i < j ? `${i}-${j}` : `${j}-${i}`;\n/**\n * TupleDictionary\n */\n\n\nclass TupleDictionary {\n constructor() {\n this.data = {\n keys: []\n };\n }\n\n /** get */\n get(i, j) {\n const key = getKey(i, j);\n return this.data[key];\n }\n /** set */\n\n\n set(i, j, value) {\n const key = getKey(i, j); // Check if key already exists\n\n if (!this.get(i, j)) {\n this.data.keys.push(key);\n }\n\n this.data[key] = value;\n }\n /** delete */\n\n\n delete(i, j) {\n const key = getKey(i, j);\n const index = this.data.keys.indexOf(key);\n\n if (index !== -1) {\n this.data.keys.splice(index, 1);\n }\n\n delete this.data[key];\n }\n /** reset */\n\n\n reset() {\n const data = this.data;\n const keys = data.keys;\n\n while (keys.length > 0) {\n const key = keys.pop();\n delete data[key];\n }\n }\n\n}\n\n/**\n * The physics world\n */\nclass World extends EventTarget {\n /**\n * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is \"fresh\" inside event callbacks.\n */\n\n /**\n * Makes bodies go to sleep when they've been inactive.\n * @default false\n */\n\n /**\n * All the current contacts (instances of ContactEquation) in the world.\n */\n\n /**\n * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).\n * @default 0\n */\n\n /**\n * Set to true to use fast quaternion normalization. It is often enough accurate to use.\n * If bodies tend to explode, set to false.\n * @default false\n */\n\n /**\n * The wall-clock time since simulation start.\n */\n\n /**\n * Number of timesteps taken since start.\n */\n\n /**\n * Default and last timestep sizes.\n */\n\n /**\n * The gravity of the world.\n */\n\n /**\n * Gravity to use when approximating the friction max force (mu*mass*gravity).\n * If undefined, global gravity will be used.\n * Use to enable friction in a World with a null gravity vector (no gravity).\n */\n\n /**\n * The broadphase algorithm to use.\n * @default NaiveBroadphase\n */\n\n /**\n * All bodies in this world\n */\n\n /**\n * True if any bodies are not sleeping, false if every body is sleeping.\n */\n\n /**\n * The solver algorithm to use.\n * @default GSSolver\n */\n\n /**\n * collisionMatrix\n */\n\n /**\n * CollisionMatrix from the previous step.\n */\n\n /**\n * All added contactmaterials.\n */\n\n /**\n * Used to look up a ContactMaterial given two instances of Material.\n */\n\n /**\n * The default material of the bodies.\n */\n\n /**\n * This contact material is used if no suitable contactmaterial is found for a contact.\n */\n\n /**\n * Time accumulator for interpolation.\n * @see https://gafferongames.com/game-physics/fix-your-timestep/\n */\n\n /**\n * Dispatched after a body has been added to the world.\n */\n\n /**\n * Dispatched after a body has been removed from the world.\n */\n constructor(options) {\n if (options === void 0) {\n options = {};\n }\n\n super();\n this.dt = -1;\n this.allowSleep = !!options.allowSleep;\n this.contacts = [];\n this.frictionEquations = [];\n this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;\n this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;\n this.time = 0.0;\n this.stepnumber = 0;\n this.default_dt = 1 / 60;\n this.nextId = 0;\n this.gravity = new Vec3();\n\n if (options.gravity) {\n this.gravity.copy(options.gravity);\n }\n\n if (options.frictionGravity) {\n this.frictionGravity = new Vec3();\n this.frictionGravity.copy(options.frictionGravity);\n }\n\n this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();\n this.bodies = [];\n this.hasActiveBodies = false;\n this.solver = options.solver !== undefined ? options.solver : new GSSolver();\n this.constraints = [];\n this.narrowphase = new Narrowphase(this);\n this.collisionMatrix = new ArrayCollisionMatrix();\n this.collisionMatrixPrevious = new ArrayCollisionMatrix();\n this.bodyOverlapKeeper = new OverlapKeeper();\n this.shapeOverlapKeeper = new OverlapKeeper();\n this.contactmaterials = [];\n this.contactMaterialTable = new TupleDictionary();\n this.defaultMaterial = new Material('default');\n this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {\n friction: 0.3,\n restitution: 0.0\n });\n this.doProfiling = false;\n this.profile = {\n solve: 0,\n makeContactConstraints: 0,\n broadphase: 0,\n integrate: 0,\n narrowphase: 0\n };\n this.accumulator = 0;\n this.subsystems = [];\n this.addBodyEvent = {\n type: 'addBody',\n body: null\n };\n this.removeBodyEvent = {\n type: 'removeBody',\n body: null\n };\n this.idToBodyMap = {};\n this.broadphase.setWorld(this);\n }\n /**\n * Get the contact material between materials m1 and m2\n * @return The contact material if it was found.\n */\n\n\n getContactMaterial(m1, m2) {\n return this.contactMaterialTable.get(m1.id, m2.id);\n }\n /**\n * Store old collision state info\n */\n\n\n collisionMatrixTick() {\n const temp = this.collisionMatrixPrevious;\n this.collisionMatrixPrevious = this.collisionMatrix;\n this.collisionMatrix = temp;\n this.collisionMatrix.reset();\n this.bodyOverlapKeeper.tick();\n this.shapeOverlapKeeper.tick();\n }\n /**\n * Add a constraint to the simulation.\n */\n\n\n addConstraint(c) {\n this.constraints.push(c);\n }\n /**\n * Removes a constraint\n */\n\n\n removeConstraint(c) {\n const idx = this.constraints.indexOf(c);\n\n if (idx !== -1) {\n this.constraints.splice(idx, 1);\n }\n }\n /**\n * Raycast test\n * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.\n */\n\n\n rayTest(from, to, result) {\n if (result instanceof RaycastResult) {\n // Do raycastClosest\n this.raycastClosest(from, to, {\n skipBackfaces: true\n }, result);\n } else {\n // Do raycastAll\n this.raycastAll(from, to, {\n skipBackfaces: true\n }, result);\n }\n }\n /**\n * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.\n * @return True if any body was hit.\n */\n\n\n raycastAll(from, to, options, callback) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.ALL;\n options.from = from;\n options.to = to;\n options.callback = callback;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.\n * @return True if any body was hit.\n */\n\n\n raycastAny(from, to, options, result) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.ANY;\n options.from = from;\n options.to = to;\n options.result = result;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Ray cast, and return information of the closest hit.\n * @return True if any body was hit.\n */\n\n\n raycastClosest(from, to, options, result) {\n if (options === void 0) {\n options = {};\n }\n\n options.mode = Ray.CLOSEST;\n options.from = from;\n options.to = to;\n options.result = result;\n return tmpRay.intersectWorld(this, options);\n }\n /**\n * Add a rigid body to the simulation.\n * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.\n * @todo Adding an array of bodies should be possible. This would save some loops too\n */\n\n\n addBody(body) {\n if (this.bodies.includes(body)) {\n return;\n }\n\n body.index = this.bodies.length;\n this.bodies.push(body);\n body.world = this;\n body.initPosition.copy(body.position);\n body.initVelocity.copy(body.velocity);\n body.timeLastSleepy = this.time;\n\n if (body instanceof Body) {\n body.initAngularVelocity.copy(body.angularVelocity);\n body.initQuaternion.copy(body.quaternion);\n }\n\n this.collisionMatrix.setNumObjects(this.bodies.length);\n this.addBodyEvent.body = body;\n this.idToBodyMap[body.id] = body;\n this.dispatchEvent(this.addBodyEvent);\n }\n /**\n * Remove a rigid body from the simulation.\n */\n\n\n removeBody(body) {\n body.world = null;\n const n = this.bodies.length - 1;\n const bodies = this.bodies;\n const idx = bodies.indexOf(body);\n\n if (idx !== -1) {\n bodies.splice(idx, 1); // Todo: should use a garbage free method\n // Recompute index\n\n for (let i = 0; i !== bodies.length; i++) {\n bodies[i].index = i;\n }\n\n this.collisionMatrix.setNumObjects(n);\n this.removeBodyEvent.body = body;\n delete this.idToBodyMap[body.id];\n this.dispatchEvent(this.removeBodyEvent);\n }\n }\n\n getBodyById(id) {\n return this.idToBodyMap[id];\n }\n /**\n * @todo Make a faster map\n */\n\n\n getShapeById(id) {\n const bodies = this.bodies;\n\n for (let i = 0; i < bodies.length; i++) {\n const shapes = bodies[i].shapes;\n\n for (let j = 0; j < shapes.length; j++) {\n const shape = shapes[j];\n\n if (shape.id === id) {\n return shape;\n }\n }\n }\n\n return null;\n }\n /**\n * Adds a contact material to the World\n */\n\n\n addContactMaterial(cmat) {\n // Add contact material\n this.contactmaterials.push(cmat); // Add current contact material to the material table\n\n this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);\n }\n /**\n * Removes a contact material from the World.\n */\n\n\n removeContactMaterial(cmat) {\n const idx = this.contactmaterials.indexOf(cmat);\n\n if (idx === -1) {\n return;\n }\n\n this.contactmaterials.splice(idx, 1);\n this.contactMaterialTable.delete(cmat.materials[0].id, cmat.materials[1].id);\n }\n /**\n * Step the simulation forward keeping track of last called time\n * to be able to step the world at a fixed rate, independently of framerate.\n *\n * @param dt The fixed time step size to use (default: 1 / 60).\n * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).\n * @see https://gafferongames.com/post/fix_your_timestep/\n * @example\n * // Run the simulation independently of framerate every 1 / 60 ms\n * world.fixedStep()\n */\n\n\n fixedStep(dt, maxSubSteps) {\n if (dt === void 0) {\n dt = 1 / 60;\n }\n\n if (maxSubSteps === void 0) {\n maxSubSteps = 10;\n }\n\n const time = performance.now() / 1000; // seconds\n\n if (!this.lastCallTime) {\n this.step(dt, undefined, maxSubSteps);\n } else {\n const timeSinceLastCalled = time - this.lastCallTime;\n this.step(dt, timeSinceLastCalled, maxSubSteps);\n }\n\n this.lastCallTime = time;\n }\n /**\n * Step the physics world forward in time.\n *\n * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.\n *\n * @param dt The fixed time step size to use.\n * @param timeSinceLastCalled The time elapsed since the function was last called.\n * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).\n * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F\n * @example\n * // fixed timestepping without interpolation\n * world.step(1 / 60)\n */\n\n\n step(dt, timeSinceLastCalled, maxSubSteps) {\n if (maxSubSteps === void 0) {\n maxSubSteps = 10;\n }\n\n if (timeSinceLastCalled === undefined) {\n // Fixed, simple stepping\n this.internalStep(dt); // Increment time\n\n this.time += dt;\n } else {\n this.accumulator += timeSinceLastCalled;\n const t0 = performance.now();\n let substeps = 0;\n\n while (this.accumulator >= dt && substeps < maxSubSteps) {\n // Do fixed steps to catch up\n this.internalStep(dt);\n this.accumulator -= dt;\n substeps++;\n\n if (performance.now() - t0 > dt * 1000) {\n // The framerate is not interactive anymore.\n // We are below the target framerate.\n // Better bail out.\n break;\n }\n } // Remove the excess accumulator, since we may not\n // have had enough substeps available to catch up\n\n\n this.accumulator = this.accumulator % dt;\n const t = this.accumulator / dt;\n\n for (let j = 0; j !== this.bodies.length; j++) {\n const b = this.bodies[j];\n b.previousPosition.lerp(b.position, t, b.interpolatedPosition);\n b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);\n b.previousQuaternion.normalize();\n }\n\n this.time += timeSinceLastCalled;\n }\n }\n\n internalStep(dt) {\n this.dt = dt;\n const contacts = this.contacts;\n const p1 = World_step_p1;\n const p2 = World_step_p2;\n const N = this.bodies.length;\n const bodies = this.bodies;\n const solver = this.solver;\n const gravity = this.gravity;\n const doProfiling = this.doProfiling;\n const profile = this.profile;\n const DYNAMIC = Body.DYNAMIC;\n let profilingStart = -Infinity;\n const constraints = this.constraints;\n const frictionEquationPool = World_step_frictionEquationPool;\n gravity.length();\n const gx = gravity.x;\n const gy = gravity.y;\n const gz = gravity.z;\n let i = 0;\n\n if (doProfiling) {\n profilingStart = performance.now();\n } // Add gravity to all objects\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.type === DYNAMIC) {\n // Only for dynamic bodies\n const f = bi.force;\n const m = bi.mass;\n f.x += m * gx;\n f.y += m * gy;\n f.z += m * gz;\n }\n } // Update subsystems\n\n\n for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {\n this.subsystems[i].update();\n } // Collision detection\n\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n p1.length = 0; // Clean up pair arrays from last step\n\n p2.length = 0;\n this.broadphase.collisionPairs(this, p1, p2);\n\n if (doProfiling) {\n profile.broadphase = performance.now() - profilingStart;\n } // Remove constrained pairs with collideConnected == false\n\n\n let Nconstraints = constraints.length;\n\n for (i = 0; i !== Nconstraints; i++) {\n const c = constraints[i];\n\n if (!c.collideConnected) {\n for (let j = p1.length - 1; j >= 0; j -= 1) {\n if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {\n p1.splice(j, 1);\n p2.splice(j, 1);\n }\n }\n }\n }\n\n this.collisionMatrixTick(); // Generate contacts\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n const oldcontacts = World_step_oldContacts;\n const NoldContacts = contacts.length;\n\n for (i = 0; i !== NoldContacts; i++) {\n oldcontacts.push(contacts[i]);\n }\n\n contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse\n\n const NoldFrictionEquations = this.frictionEquations.length;\n\n for (i = 0; i !== NoldFrictionEquations; i++) {\n frictionEquationPool.push(this.frictionEquations[i]);\n }\n\n this.frictionEquations.length = 0;\n this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused\n this.frictionEquations, frictionEquationPool);\n\n if (doProfiling) {\n profile.narrowphase = performance.now() - profilingStart;\n } // Loop over all collisions\n\n\n if (doProfiling) {\n profilingStart = performance.now();\n } // Add all friction eqs\n\n\n for (i = 0; i < this.frictionEquations.length; i++) {\n solver.addEquation(this.frictionEquations[i]);\n }\n\n const ncontacts = contacts.length;\n\n for (let k = 0; k !== ncontacts; k++) {\n // Current contact\n const c = contacts[k]; // Get current collision indeces\n\n const bi = c.bi;\n const bj = c.bj;\n const si = c.si;\n const sj = c.sj; // Get collision properties\n\n let cm;\n\n if (bi.material && bj.material) {\n cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;\n } else {\n cm = this.defaultContactMaterial;\n } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;\n\n\n cm.friction; // c.restitution = cm.restitution;\n // If friction or restitution were specified in the material, use them\n\n if (bi.material && bj.material) {\n if (bi.material.friction >= 0 && bj.material.friction >= 0) {\n bi.material.friction * bj.material.friction;\n }\n\n if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {\n c.restitution = bi.material.restitution * bj.material.restitution;\n }\n } // c.setSpookParams(\n // cm.contactEquationStiffness,\n // cm.contactEquationRelaxation,\n // dt\n // );\n\n\n solver.addEquation(c); // // Add friction constraint equation\n // if(mu > 0){\n // \t// Create 2 tangent equations\n // \tconst mug = mu * gnorm;\n // \tconst reducedMass = (bi.invMass + bj.invMass);\n // \tif(reducedMass > 0){\n // \t\treducedMass = 1/reducedMass;\n // \t}\n // \tconst pool = frictionEquationPool;\n // \tconst c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);\n // \tconst c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);\n // \tthis.frictionEquations.push(c1, c2);\n // \tc1.bi = c2.bi = bi;\n // \tc1.bj = c2.bj = bj;\n // \tc1.minForce = c2.minForce = -mug*reducedMass;\n // \tc1.maxForce = c2.maxForce = mug*reducedMass;\n // \t// Copy over the relative vectors\n // \tc1.ri.copy(c.ri);\n // \tc1.rj.copy(c.rj);\n // \tc2.ri.copy(c.ri);\n // \tc2.rj.copy(c.rj);\n // \t// Construct tangents\n // \tc.ni.tangents(c1.t, c2.t);\n // // Set spook params\n // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);\n // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);\n // c1.enabled = c2.enabled = c.enabled;\n // \t// Add equations to solver\n // \tsolver.addEquation(c1);\n // \tsolver.addEquation(c2);\n // }\n\n if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {\n const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();\n const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;\n\n if (speedSquaredB >= speedLimitSquaredB * 2) {\n bi.wakeUpAfterNarrowphase = true;\n }\n }\n\n if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {\n const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();\n const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;\n\n if (speedSquaredA >= speedLimitSquaredA * 2) {\n bj.wakeUpAfterNarrowphase = true;\n }\n } // Now we know that i and j are in contact. Set collision matrix state\n\n\n this.collisionMatrix.set(bi, bj, true);\n\n if (!this.collisionMatrixPrevious.get(bi, bj)) {\n // First contact!\n // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.\n World_step_collideEvent.body = bj;\n World_step_collideEvent.contact = c;\n bi.dispatchEvent(World_step_collideEvent);\n World_step_collideEvent.body = bi;\n bj.dispatchEvent(World_step_collideEvent);\n }\n\n this.bodyOverlapKeeper.set(bi.id, bj.id);\n this.shapeOverlapKeeper.set(si.id, sj.id);\n }\n\n this.emitContactEvents();\n\n if (doProfiling) {\n profile.makeContactConstraints = performance.now() - profilingStart;\n profilingStart = performance.now();\n } // Wake up bodies\n\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.wakeUpAfterNarrowphase) {\n bi.wakeUp();\n bi.wakeUpAfterNarrowphase = false;\n }\n } // Add user-added constraints\n\n\n Nconstraints = constraints.length;\n\n for (i = 0; i !== Nconstraints; i++) {\n const c = constraints[i];\n c.update();\n\n for (let j = 0, Neq = c.equations.length; j !== Neq; j++) {\n const eq = c.equations[j];\n solver.addEquation(eq);\n }\n } // Solve the constrained system\n\n\n solver.solve(dt, this);\n\n if (doProfiling) {\n profile.solve = performance.now() - profilingStart;\n } // Remove all contacts from solver\n\n\n solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details\n\n const pow = Math.pow;\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n\n if (bi.type & DYNAMIC) {\n // Only for dynamic bodies\n const ld = pow(1.0 - bi.linearDamping, dt);\n const v = bi.velocity;\n v.scale(ld, v);\n const av = bi.angularVelocity;\n\n if (av) {\n const ad = pow(1.0 - bi.angularDamping, dt);\n av.scale(ad, av);\n }\n }\n }\n\n this.dispatchEvent(World_step_preStepEvent); // Leap frog\n // vnew = v + h*f/m\n // xnew = x + h*vnew\n\n if (doProfiling) {\n profilingStart = performance.now();\n }\n\n const stepnumber = this.stepnumber;\n const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;\n const quatNormalizeFast = this.quatNormalizeFast;\n\n for (i = 0; i !== N; i++) {\n bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);\n }\n\n this.clearForces();\n this.broadphase.dirty = true;\n\n if (doProfiling) {\n profile.integrate = performance.now() - profilingStart;\n } // Update step number\n\n\n this.stepnumber += 1;\n this.dispatchEvent(World_step_postStepEvent); // Sleeping update\n\n let hasActiveBodies = true;\n\n if (this.allowSleep) {\n hasActiveBodies = false;\n\n for (i = 0; i !== N; i++) {\n const bi = bodies[i];\n bi.sleepTick(this.time);\n\n if (bi.sleepState !== Body.SLEEPING) {\n hasActiveBodies = true;\n }\n }\n }\n\n this.hasActiveBodies = hasActiveBodies;\n }\n\n emitContactEvents() {\n const hasBeginContact = this.hasAnyEventListener('beginContact');\n const hasEndContact = this.hasAnyEventListener('endContact');\n\n if (hasBeginContact || hasEndContact) {\n this.bodyOverlapKeeper.getDiff(additions, removals);\n }\n\n if (hasBeginContact) {\n for (let i = 0, l = additions.length; i < l; i += 2) {\n beginContactEvent.bodyA = this.getBodyById(additions[i]);\n beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);\n this.dispatchEvent(beginContactEvent);\n }\n\n beginContactEvent.bodyA = beginContactEvent.bodyB = null;\n }\n\n if (hasEndContact) {\n for (let i = 0, l = removals.length; i < l; i += 2) {\n endContactEvent.bodyA = this.getBodyById(removals[i]);\n endContactEvent.bodyB = this.getBodyById(removals[i + 1]);\n this.dispatchEvent(endContactEvent);\n }\n\n endContactEvent.bodyA = endContactEvent.bodyB = null;\n }\n\n additions.length = removals.length = 0;\n const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');\n const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');\n\n if (hasBeginShapeContact || hasEndShapeContact) {\n this.shapeOverlapKeeper.getDiff(additions, removals);\n }\n\n if (hasBeginShapeContact) {\n for (let i = 0, l = additions.length; i < l; i += 2) {\n const shapeA = this.getShapeById(additions[i]);\n const shapeB = this.getShapeById(additions[i + 1]);\n beginShapeContactEvent.shapeA = shapeA;\n beginShapeContactEvent.shapeB = shapeB;\n if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;\n if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;\n this.dispatchEvent(beginShapeContactEvent);\n }\n\n beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;\n }\n\n if (hasEndShapeContact) {\n for (let i = 0, l = removals.length; i < l; i += 2) {\n const shapeA = this.getShapeById(removals[i]);\n const shapeB = this.getShapeById(removals[i + 1]);\n endShapeContactEvent.shapeA = shapeA;\n endShapeContactEvent.shapeB = shapeB;\n if (shapeA) endShapeContactEvent.bodyA = shapeA.body;\n if (shapeB) endShapeContactEvent.bodyB = shapeB.body;\n this.dispatchEvent(endShapeContactEvent);\n }\n\n endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;\n }\n }\n /**\n * Sets all body forces in the world to zero.\n */\n\n\n clearForces() {\n const bodies = this.bodies;\n const N = bodies.length;\n\n for (let i = 0; i !== N; i++) {\n const b = bodies[i];\n b.force;\n b.torque;\n b.force.set(0, 0, 0);\n b.torque.set(0, 0, 0);\n }\n }\n\n} // Temp stuff\n\nnew AABB();\nconst tmpRay = new Ray(); // performance.now() fallback on Date.now()\n\nconst performance = globalThis.performance || {};\n\nif (!performance.now) {\n let nowOffset = Date.now();\n\n if (performance.timing && performance.timing.navigationStart) {\n nowOffset = performance.timing.navigationStart;\n }\n\n performance.now = () => Date.now() - nowOffset;\n}\n\nnew Vec3(); // Dispatched after the world has stepped forward in time.\n// Reusable event objects to save memory.\n\nconst World_step_postStepEvent = {\n type: 'postStep'\n}; // Dispatched before the world steps forward in time.\n\nconst World_step_preStepEvent = {\n type: 'preStep'\n};\nconst World_step_collideEvent = {\n type: Body.COLLIDE_EVENT_NAME,\n body: null,\n contact: null\n}; // Pools for unused objects\n\nconst World_step_oldContacts = [];\nconst World_step_frictionEquationPool = []; // Reusable arrays for collision pairs\n\nconst World_step_p1 = [];\nconst World_step_p2 = []; // Stuff for emitContactEvents\n\nconst additions = [];\nconst removals = [];\nconst beginContactEvent = {\n type: 'beginContact',\n bodyA: null,\n bodyB: null\n};\nconst endContactEvent = {\n type: 'endContact',\n bodyA: null,\n bodyB: null\n};\nconst beginShapeContactEvent = {\n type: 'beginShapeContact',\n bodyA: null,\n bodyB: null,\n shapeA: null,\n shapeB: null\n};\nconst endShapeContactEvent = {\n type: 'endShapeContact',\n bodyA: null,\n bodyB: null,\n shapeA: null,\n shapeB: null\n};\n\nexport { AABB, ArrayCollisionMatrix, BODY_SLEEP_STATES, BODY_TYPES, Body, Box, Broadphase, COLLISION_TYPES, ConeTwistConstraint, Constraint, ContactEquation, ContactMaterial, ConvexPolyhedron, Cylinder, DistanceConstraint, Equation, EventTarget, FrictionEquation, GSSolver, GridBroadphase, Heightfield, HingeConstraint, JacobianElement, LockConstraint, Mat3, Material, NaiveBroadphase, Narrowphase, ObjectCollisionMatrix, Particle, Plane, PointToPointConstraint, Pool, Quaternion, RAY_MODES, Ray, RaycastResult, RaycastVehicle, RigidVehicle, RotationalEquation, RotationalMotorEquation, SAPBroadphase, SHAPE_TYPES, SPHSystem, Shape, Solver, Sphere, SplitSolver, Spring, Transform, Trimesh, Vec3, Vec3Pool, WheelInfo, World };\n","// ===== tuples.ts ======================================================\n// Types & helpers for 3-tuples, used for positions, vectors and colours\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { vec3 } from 'gl-matrix'\nimport * as CANNON from 'cannon-es'\n\n/** A simple 3D position or vector tuple */\nexport type XYZ = [number, number, number]\n\n/** A simple 4D position or vector tuple */\nexport type XYZW = [number, number, number, number]\n\n/** A simple RGB colour tuple */\nexport type RGB = [number, number, number]\n\n/** A simple RGBA colour tuple */\nexport type RGBA = [number, number, number, number]\n\n// ============================================================================\n// Tuple helpers\n// ============================================================================\n\n/**\n * Normalizes a 3-tuple to a unit vector.\n * @param tuple The tuple to normalize\n */\nfunction normalize(tuple: XYZ | RGB | number[]) {\n const [x, y, z] = tuple\n const len = Math.sqrt(x * x + y * y + z * z)\n\n return tuple.map((v) => v / len) as XYZ\n}\n\n/**\n * Scales a 3-tuple by a scalar.\n * @param tuple The tuple to scale\n * @param scale The scalar to scale by\n */\nfunction scale(tuple: XYZ | RGB | RGBA | number[], amount: number) {\n return tuple.map((v) => v * amount) as XYZ\n}\n\n/**\n * Scales a 3-tuple by a scalar, clamping the result to 0-1.\n * @param tuple The tuple to scale\n * @param scale The scalar to scale by\n */\nfunction scaleClamped(colour: RGB | RGBA, amount: number) {\n scale(colour, amount)\n\n // Clamp to 0-1\n return colour.map((v) => Math.min(Math.max(v, 0), 1)) as RGB | RGBA\n}\n\n/**\n * Converts a 3-tuple to a gl-matrix vec3\n * @param tuple The tuple to convert\n */\nfunction toVec3(tuple: XYZ) {\n return vec3.fromValues(tuple[0], tuple[1], tuple[2])\n}\n\n/**\n * Calculates the distance between two 3-tuples\n * @param a First tuple\n * @param b Second tuple\n */\nfunction distance(a: XYZ, b: XYZ) {\n return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)\n}\n\nfunction add(a: XYZ, b: XYZ) {\n return [a[0] + b[0], a[1] + b[1], a[2] + b[2]] as XYZ\n}\n\n/**\n * Converts a Cannon.js vector or quaternion to a tuple\n * @param value The Cannon.js vector or quaternion to convert\n */\nfunction fromCannon(value: CANNON.Vec3 | CANNON.Quaternion) {\n if (value instanceof CANNON.Vec3) {\n return [value.x, value.y, value.z] as XYZ\n }\n\n return [value.x, value.y, value.z, value.w] as XYZW\n}\n\n// ============================================================================\n// Colour helpers\n// ============================================================================\n\n/**\n * Creates a RGB 3-tuple from 0-255 values.\n * @param r Red value (0-255)\n * @param g Green value (0-255)\n * @param b Blue value (0-255)\n */\nfunction rgbColour255(r: number, g: number, b: number) {\n return [r / 255, g / 255, b / 255] as RGB\n}\n\n/**\n * Converts a hex string to an RGB 3-tuple.\n * @param hexString\n */\nfunction rgbColourHex(hexString: string) {\n const hex = hexString.replace('#', '')\n const r = parseInt(hex.substring(0, 2), 16)\n const g = parseInt(hex.substring(2, 4), 16)\n const b = parseInt(hex.substring(4, 6), 16)\n\n return rgbColour255(r, g, b)\n}\n\n/**\n * A set of common colours as RGB tuples\n */\nexport const Colours = {\n RED: [1, 0, 0] as RGB,\n GREEN: [0, 1, 0] as RGB,\n BLUE: [0, 0, 1] as RGB,\n YELLOW: [1, 1, 0] as RGB,\n CYAN: [0, 1, 1] as RGB,\n MAGENTA: [1, 0, 1] as RGB,\n BLACK: [0, 0, 0] as RGB,\n WHITE: [1, 1, 1] as RGB,\n}\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport const Tuples = {\n normalize,\n scale,\n scaleClamped,\n rgbColour255,\n rgbColourHex,\n toVec3,\n distance,\n fromCannon,\n add,\n}\n","// ===== cache.ts =============================================================\n// Caches and managers for models and textures\n// Ben Coleman, 2023\n// ============================================================================\n\nimport log from 'loglevel'\nimport { Model } from '../renderable/model.ts'\nimport { ProgramInfo, createTexture } from 'twgl.js'\n\n/** @ignore */\nexport const PROG_DEFAULT = 'phong'\n/** @ignore */\nexport const PROG_BILLBOARD = 'billboard'\n\n/**\n * A singleton cache for parsed and loaded models, indexed by name\n */\nexport class ModelCache {\n private cache: Map\n private static _instance: ModelCache\n\n private constructor() {\n this.cache = new Map()\n }\n\n /**\n * Return the singleton instance of the model cache\n */\n static get instance() {\n if (!ModelCache._instance) {\n ModelCache._instance = new ModelCache()\n }\n\n return ModelCache._instance\n }\n\n /**\n * Return a model from the cache by name\n * @param name Name of model without extension\n * @param warn If true, log a warning if model not found\n */\n get(name: string, warn = true) {\n if (!this.cache.has(name) && warn) {\n log.warn(`⚠️ Model '${name}' not found, please load it first`)\n return undefined\n }\n\n return this.cache.get(name)\n }\n\n /**\n * Add a model to the cache, using the model name as key\n */\n add(model: Model) {\n log.debug(`🧰 Adding model '${model.name}' to cache`)\n\n this.cache.set(model.name, model)\n }\n}\n\n/**\n * A caching texture manager\n * It is instantiated with a WebGL context and then used to load and cache textures\n */\nexport class TextureCache {\n private cache: Map\n private gl: WebGL2RenderingContext\n private static _instance: TextureCache\n private static initialized = false\n private defaultWhite: WebGLTexture\n private defaultRand: WebGLTexture\n\n private constructor() {\n this.cache = new Map()\n this.gl = {} as WebGL2RenderingContext\n this.defaultWhite = {} as WebGLTexture\n this.defaultRand = {} as WebGLTexture\n }\n\n // Create a new texture cache\n static init(gl: WebGL2RenderingContext, randSize = 512) {\n this._instance = new TextureCache()\n this._instance.gl = gl\n\n // 1 pixel white texture used as base for materials\n const white1pixel = createTexture(gl, {\n min: gl.NEAREST,\n mag: gl.NEAREST,\n src: [255, 255, 255, 255],\n })\n\n // Random RGB texture, used for pseudo random number generation\n const randArray = new Uint8Array(randSize * randSize * 4)\n for (let i = 0; i < randSize * randSize * 4; i++) {\n randArray[i] = Math.floor(Math.random() * 255)\n }\n const randomRGB = createTexture(gl, {\n min: gl.NEAREST,\n mag: gl.NEAREST,\n src: randArray,\n width: randSize,\n height: randSize,\n wrap: gl.REPEAT,\n })\n\n this._instance.defaultWhite = white1pixel\n this._instance.defaultRand = randomRGB\n\n TextureCache.initialized = true\n }\n\n /**\n * Return the singleton instance of the texture cache\n */\n static get instance() {\n if (!TextureCache.initialized) {\n throw new Error('💥 TextureCache not initialized, call TextureCache.init() first')\n }\n\n return this._instance\n }\n\n /**\n * Return a texture from the cache by name\n * @param key Key of texture, this is usually the URL or filename path\n */\n get(key: string) {\n if (!this.cache.has(key)) {\n log.warn(`💥 Texture ${key} not found in cache`)\n return undefined\n }\n\n log.trace(`👍 Returning texture '${key}' from cache, nice!`)\n return this.cache.get(key)\n }\n\n /**\n * Add a texture to the cache\n * @param key Key of texture, this is usually the URL or filename path\n * @param texture WebGL texture\n */\n add(key: string, texture: WebGLTexture) {\n if (this.cache.has(key)) {\n log.warn(`🤔 Texture '${key}' already in cache, not adding again`)\n return\n }\n\n log.debug(`🧰 Adding texture '${key}' to cache`)\n\n this.cache.set(key, texture)\n }\n\n /**\n * Create or return a texture from the cache by name\n * @param src URL or filename path of texture image, or ArrayBufferView holding texture\n * @param filter Enable texture filtering and mipmaps (default true)\n * @param flipY Flip the texture vertically (default true)\n */\n getCreate(src: string | ArrayBufferView, filter = true, flipY = false, textureKey = '') {\n let key = ''\n\n if (typeof src === 'string') {\n key = src\n } else {\n if (textureKey === '') {\n throw new Error('💥 ArrayBuffer textures need a unique key')\n }\n\n key = textureKey\n }\n\n // Check if texture already exists, if so return it\n if (this.cache.has(key)) {\n log.trace(`👍 Returning texture '${key}' from cache, nice!`, flipY)\n return this.get(key)\n }\n\n // Create texture and add to cache\n // NOTE. Catching errors here is very hard, as twgl.createTexture() doesn't throw errors\n const texture = createTexture(\n this.gl,\n {\n min: filter ? this.gl.LINEAR_MIPMAP_LINEAR : this.gl.NEAREST,\n mag: filter ? this.gl.LINEAR : this.gl.NEAREST,\n src,\n flipY: flipY ? 1 : 0,\n },\n (err) => {\n if (err) {\n // There's not much we can do here, but log the error\n log.error('💥 Error loading texture', err)\n }\n },\n )\n\n this.add(key, texture)\n return texture\n }\n\n /**\n * Return the default white 1x1 texture\n */\n static get defaultWhite() {\n return this.instance.defaultWhite\n }\n\n /**\n * Return the default random RGB texture\n */\n static get defaultRand() {\n return this.instance.defaultRand\n }\n\n /**\n * Return the number of textures in the cache\n */\n static get size() {\n return this.instance.cache.size\n }\n\n /**\n * Clear the texture cache\n */\n static clear() {\n this.instance.cache.clear()\n }\n}\n\n/**\n * Singleton cache for parsed and loaded GL programs, indexed by name\n */\nexport class ProgramCache {\n private cache: Map\n private _default: ProgramInfo\n private static _instance: ProgramCache\n private static initialized = false\n\n public static PROG_PHONG = 'phong'\n public static PROG_BILLBOARD = 'billboard'\n public static PROG_SHADOWMAP = 'shadowmap'\n\n /**\n * Create a new program cache, can't be used until init() is called\n */\n private constructor() {\n this.cache = new Map()\n // This is pretty nasty, but we really trust people to call init() first\n this._default = {} as ProgramInfo\n }\n\n /**\n * Initialise the program cache with a default program.\n * This MUST be called before using the cache\n * @param defaultProg The default program that can be used by most things\n */\n public static init(defaultProg: ProgramInfo) {\n if (ProgramCache._instance) {\n log.warn('🤔 Program cache already initialised, not doing it again')\n return\n }\n\n ProgramCache._instance = new ProgramCache()\n ProgramCache._instance._default = defaultProg\n ProgramCache.initialized = true\n }\n\n /**\n * Return the singleton instance of the program cache\n */\n static get instance() {\n if (!ProgramCache.initialized) {\n throw new Error('💥 Program cache not initialised, call init() first')\n }\n\n return ProgramCache._instance\n }\n\n /**\n * Return a program from the cache by name\n * @param name Name of program\n */\n get(name: string): ProgramInfo {\n const prog = this.cache.get(name)\n\n if (!prog) {\n log.warn(`⚠️ Program '${name}' not found, returning default`)\n return this._default\n }\n\n return prog\n }\n\n add(name: string, program: ProgramInfo) {\n log.debug(`🧰 Adding program '${name}' to cache`)\n\n this.cache.set(name, program)\n }\n\n get default() {\n return this._default\n }\n}\n","// ===== camera.ts ============================================================\n// Represents a camera in 3D space\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4, vec3 } from 'gl-matrix'\nimport { XYZ } from './tuples.ts'\nimport { getGl } from '../core/gl.ts'\n\nimport log from 'loglevel'\n\nexport enum CameraType {\n PERSPECTIVE,\n ORTHOGRAPHIC,\n}\n\nexport class Camera {\n /** Camera position */\n public position: XYZ\n\n /** Camera look at point, default: [0, 0, 0] */\n public lookAt: XYZ\n\n /** Field of view in degrees, default: 45 */\n public fov: number\n\n /** Near clipping plane, default: 0.1 */\n public near: number\n\n /** Far clipping plane, default: 100 */\n public far: number\n\n /** Camera up vector, default: [0, 1, 0] */\n public up: XYZ\n\n /** Change camera projection, default: CameraType.PERSPECTIVE */\n public type: CameraType\n\n /** Is this camera active, default: true */\n public active: boolean\n\n /** Orthographic zoom level, only used when type is orthographic, default: 20 */\n public orthoZoom: number\n\n /** Is this camera used for a dynamic environment map, default: false */\n public usedForEnvMap: boolean\n\n /** Is this camera used for a shadow map, default: false */\n public usedForShadowMap: boolean\n\n /** Aspect ratio of the camera, default: 1 */\n public aspectRatio: number\n\n // Used for first person mode\n private fpAngleY: number\n private fpAngleX: number\n private fpMode: boolean\n private fpHandlersAdded: boolean\n private fpTurnSpeed: number\n private fpMoveSpeed: number\n\n // Used to clamp first person up/down angle\n private maxAngleUp: number = Math.PI / 2 - 0.01\n private maxAngleDown: number = -Math.PI / 2 + 0.01\n\n // Used to track keys pressed in FP mode for better movement\n private keysDown: Set\n private touches: Touch[] = []\n\n /**\n * Create a new default camera\n */\n constructor(type = CameraType.PERSPECTIVE, aspectRatio = 1) {\n this.type = type\n this.active = true\n\n this.position = [0, 0, 30]\n this.lookAt = [0, 0, 0]\n this.up = [0, 1, 0]\n this.near = 0.1\n this.far = 100\n this.fov = 45\n this.aspectRatio = aspectRatio\n this.orthoZoom = 20\n this.usedForEnvMap = false\n this.usedForShadowMap = false\n\n this.fpMode = false\n this.fpAngleY = 0\n this.fpAngleX = 0\n this.fpTurnSpeed = 0.001\n this.fpMoveSpeed = 1.0\n this.fpHandlersAdded = false\n\n this.keysDown = new Set()\n }\n\n /**\n * Get the current view matrix for the camera\n */\n get matrix() {\n // Standard view matrix with position and lookAt for non-FPS camera\n if (!this.fpMode) {\n const camView = mat4.targetTo(mat4.create(), this.position, this.lookAt, this.up)\n return camView\n }\n\n // FPS camera is handled different, we need to rotate the camera around the Y axis\n const camView = mat4.targetTo(mat4.create(), [0, 0, 0], [0, 0, -1], this.up)\n mat4.translate(camView, camView, this.position)\n mat4.rotateY(camView, camView, this.fpAngleY)\n mat4.rotateX(camView, camView, this.fpAngleX)\n\n return camView\n }\n\n /**\n * Get the projection matrix for this camera\n * @param aspectRatio Aspect ratio of the canvas\n */\n get projectionMatrix() {\n if (this.type === CameraType.ORTHOGRAPHIC) {\n const camProj = mat4.ortho(\n mat4.create(),\n -this.aspectRatio * this.orthoZoom,\n this.aspectRatio * this.orthoZoom,\n -this.orthoZoom,\n this.orthoZoom,\n this.near,\n this.far,\n )\n\n return camProj\n } else {\n const camProj = mat4.perspective(mat4.create(), this.fov * (Math.PI / 180), this.aspectRatio, this.near, this.far)\n return camProj\n }\n }\n\n /**\n * Get the corners of the view frustum for this camera in world space\n * @param scaleFar Scale the far plane to bring the frustum closer, default: 1\n */\n frustumCornersWorld(scaleFar = 1) {\n const far = this.far * scaleFar\n const nearHeight = Math.tan((this.fov * (Math.PI / 180)) / 2) * this.near\n const nearWidth = nearHeight * this.aspectRatio\n\n const farHeight = Math.tan((this.fov * (Math.PI / 180)) / 2) * far\n const farWidth = farHeight * this.aspectRatio\n\n const nearTopLeft = vec3.fromValues(nearWidth, nearHeight, -this.near)\n const nearTopRight = vec3.fromValues(-nearWidth, nearHeight, -this.near)\n const nearBottomLeft = vec3.fromValues(nearWidth, -nearHeight, -this.near)\n const nearBottomRight = vec3.fromValues(-nearWidth, -nearHeight, -this.near)\n\n const farTopLeft = vec3.fromValues(farWidth, farHeight, -far)\n const farTopRight = vec3.fromValues(-farWidth, farHeight, -far)\n const farBottomLeft = vec3.fromValues(farWidth, -farHeight, -far)\n const farBottomRight = vec3.fromValues(-farWidth, -farHeight, -far)\n\n const nearTopLeftWorld = vec3.transformMat4(vec3.create(), nearTopLeft, this.matrix)\n const nearTopRightWorld = vec3.transformMat4(vec3.create(), nearTopRight, this.matrix)\n const nearBottomLeftWorld = vec3.transformMat4(vec3.create(), nearBottomLeft, this.matrix)\n const nearBottomRightWorld = vec3.transformMat4(vec3.create(), nearBottomRight, this.matrix)\n\n const farTopLeftWorld = vec3.transformMat4(vec3.create(), farTopLeft, this.matrix)\n const farTopRightWorld = vec3.transformMat4(vec3.create(), farTopRight, this.matrix)\n const farBottomLeftWorld = vec3.transformMat4(vec3.create(), farBottomLeft, this.matrix)\n const farBottomRightWorld = vec3.transformMat4(vec3.create(), farBottomRight, this.matrix)\n\n // calculate the center of the frustum\n const center = vec3.create()\n vec3.add(center, nearTopLeftWorld, nearTopRightWorld)\n vec3.add(center, center, nearBottomLeftWorld)\n vec3.add(center, center, nearBottomRightWorld)\n vec3.add(center, center, farTopLeftWorld)\n vec3.add(center, center, farTopRightWorld)\n vec3.add(center, center, farBottomLeftWorld)\n vec3.add(center, center, farBottomRightWorld)\n vec3.scale(center, center, 1 / 8)\n\n return {\n nearTopLeftWorld,\n nearTopRightWorld,\n nearBottomLeftWorld,\n nearBottomRightWorld,\n farTopLeftWorld,\n farTopRightWorld,\n farBottomLeftWorld,\n farBottomRightWorld,\n center,\n }\n }\n\n /**\n * Get the camera position as a string for debugging\n */\n toString() {\n const pos = this.position.map((p) => p.toFixed(2))\n return `position: [${pos}]`\n }\n\n /**\n * Switches the camera to first person mode, where the camera is controlled by\n * the mouse and keyboard. The mouse controls look direction and the keyboard\n * controls movement.\n * @param angleY Starting look up/down angle in radians, default 0\n * @param angleX Starting look left/right angle in radians, default 0\n * @param turnSpeed Speed of looking in radians, default 0.001\n * @param moveSpeed Speed of moving in units, default 1.0\n */\n enableFPControls(angleY = 0, angleX = 0, turnSpeed = 0.001, moveSpeed = 1.0) {\n this.fpMode = true\n this.fpAngleY = angleY\n this.fpAngleX = angleX\n this.fpTurnSpeed = turnSpeed\n this.fpMoveSpeed = moveSpeed\n\n if (this.fpHandlersAdded) return // Prevent multiple event listeners being added\n\n // Handle enable/disable for pointer lock on main canvas\n // See: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API\n const gl = getGl()\n gl?.canvas.addEventListener('click', async () => {\n if (!this.fpMode || !this.active) return\n\n if (document.pointerLockElement) {\n document.exitPointerLock()\n } else {\n await (gl?.canvas).requestPointerLock()\n }\n })\n\n // Handle mouse movement for looking around\n window.addEventListener('mousemove', (e) => {\n if (!document.pointerLockElement) {\n return\n }\n\n if (!this.fpMode || !this.active) return\n this.fpAngleY += e.movementX * -this.fpTurnSpeed\n this.fpAngleX += e.movementY * -this.fpTurnSpeed\n\n // Clamp up/down angle\n if (this.fpAngleX > this.maxAngleUp) this.fpAngleX = this.maxAngleUp\n if (this.fpAngleX < this.maxAngleDown) this.fpAngleX = this.maxAngleDown\n\n // update the lookAt point\n const dZ = -Math.cos(this.fpAngleY) * 1\n const dX = -Math.sin(this.fpAngleY) * 1\n const dY = Math.sin(this.fpAngleX) * 1\n\n this.lookAt = [this.position[0] + dX, this.position[1] + dY, this.position[2] + dZ]\n })\n\n // Track keys pressed for movement\n window.addEventListener('keydown', (e) => {\n if (!this.fpMode || !this.active) return\n this.keysDown.add(e.key)\n })\n\n window.addEventListener('keyup', (e) => {\n if (!this.fpMode || !this.active) return\n this.keysDown.delete(e.key)\n })\n\n window.addEventListener('touchstart', (e) => {\n if (!this.fpMode || !this.active) return\n\n // If the touch is on the right side of the screen, it's for looking\n if (e.touches[0].clientX > window.innerWidth / 2) {\n this.touches[0] = e.touches[0]\n }\n\n // If the touch is on the left side of the screen, it's for moving\n if (e.touches[0].clientX < window.innerWidth / 2) {\n // Top half of screen is forward, bottom half is backward\n if (e.touches[0].clientY < window.innerHeight / 2) {\n this.keysDown.add('w')\n }\n if (e.touches[0].clientY > window.innerHeight / 2) {\n this.keysDown.add('s')\n }\n }\n })\n\n window.addEventListener('touchend', () => {\n if (!this.fpMode || !this.active) return\n\n this.touches = []\n this.keysDown.clear()\n })\n\n window.addEventListener('touchmove', (e) => {\n if (!this.fpMode || !this.active) return\n\n if (this.touches.length === 0) return\n\n const touch = e.touches[0]\n\n const dx = touch.clientX - this.touches[0].clientX\n const dy = touch.clientY - this.touches[0].clientY\n\n this.fpAngleY += dx * -this.fpTurnSpeed * touch.force * 4\n this.fpAngleX += dy * -this.fpTurnSpeed * touch.force * 4\n\n // Clamp up/down angle\n if (this.fpAngleX > this.maxAngleUp) this.fpAngleX = this.maxAngleUp\n if (this.fpAngleX < this.maxAngleDown) this.fpAngleX = this.maxAngleDown\n\n this.touches[0] = touch\n })\n\n this.fpHandlersAdded = true\n log.info('🎥 Camera: first person mode & controls enabled')\n }\n\n /**\n * Disable FP mode\n */\n disableFPControls() {\n this.fpMode = false\n document.exitPointerLock()\n log.debug('🎥 Camera: FPS mode disabled')\n }\n\n /**\n * Get FP mode state\n */\n get fpModeEnabled() {\n return this.fpMode\n }\n\n /**\n * Called every frame to update the camera, currently only used for movement in FP mode\n */\n update() {\n if (!this.fpMode || !this.active) return\n if (this.keysDown.size === 0) return\n\n // Use fpAngleY to calculate the direction we are facing\n const dZ = -Math.cos(this.fpAngleY) * this.fpMoveSpeed\n const dX = -Math.sin(this.fpAngleY) * this.fpMoveSpeed\n\n // Use keysDown to move the camera\n for (const key of this.keysDown.values()) {\n switch (key) {\n case 'ArrowUp':\n case 'w':\n this.position[0] += dX\n this.position[2] += dZ\n this.lookAt[0] += dX\n this.lookAt[2] += dZ\n break\n\n case 'ArrowDown':\n case 's':\n this.position[0] -= dX\n this.position[2] -= dZ\n this.lookAt[0] -= dX\n this.lookAt[2] -= dZ\n break\n\n case 'ArrowLeft':\n case 'a':\n this.position[0] += dZ\n this.position[2] -= dX\n this.lookAt[0] += dZ\n this.lookAt[2] -= dX\n break\n\n case 'ArrowRight':\n case 'd':\n // Move right\n this.position[0] -= dZ\n this.position[2] += dX\n this.lookAt[0] -= dZ\n this.lookAt[2] += dX\n break\n\n case ']':\n // Move up\n this.position[1] += this.fpMoveSpeed * 0.75\n this.lookAt[1] += this.fpMoveSpeed * 0.75\n break\n\n case '[':\n // Move down\n this.position[1] -= this.fpMoveSpeed * 0.75\n this.lookAt[1] -= this.fpMoveSpeed * 0.75\n break\n }\n }\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Shadow map fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nvoid main() {\n // Yeah I don't understand this either, but it works\n}\n","#version 300 es\n\n// ============================================================================\n// Shadow map vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\n\nuniform mat4 u_worldViewProjection;\n\nvoid main() {\n gl_Position = u_worldViewProjection * position;\n}\n","// ===== light.ts =============================================================\n// All light types, including directional and point\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport * as twgl from 'twgl.js'\n\nimport { UniformSet, getGl } from '../core/gl.ts'\nimport { Camera, CameraType } from './camera.ts'\nimport { Colours, Tuples, XYZ, RGB } from './tuples.ts'\n\nimport fragShaderShadow from '../../shaders/shadowmap/glsl.frag'\nimport vertShaderShadow from '../../shaders/shadowmap/glsl.vert'\n\n/**\n * Options to configure how shadows are calculated & rendered\n */\nexport type ShadowOptions = {\n /** Size of the shadow map texture. Default: 512 */\n mapSize: number\n\n /** Zoom level of the shadow map camera, larger will cover more of the scene, but results in more blocky shadows. Default 120 */\n zoom: number\n\n /** Far clipping pane of shadow map camera, default 1000 */\n distance: number\n\n /** Blur the edges of shadows, higher values them more random, default 0.2 */\n // scatter: number\n\n /** Offset used to reduce shadow acne especially when self shadowing */\n polygonOffset: number\n}\n\n/**\n * A directional light source, typically global with the context having only a single instance\n * Having multiple directional lights is not supported\n */\nexport class LightDirectional {\n private _direction: XYZ\n private _shadowMapProgram?: twgl.ProgramInfo\n private _shadowMapFB?: twgl.FramebufferInfo\n private _shadowMapTex?: WebGLTexture\n private _shadowOptions?: ShadowOptions\n\n /** Colour of the light, used for both diffuse and specular. Default: [0, 0, 0] */\n public colour: RGB\n\n /** Ambient colour of the light. Default: [0, 0, 0] */\n public ambient: RGB\n\n /** Is this light enabled. Default: true */\n public enabled: boolean\n\n /** Create a default directional light, pointing downward */\n constructor() {\n this._direction = [0, -1, 0]\n this.colour = Colours.WHITE\n this.ambient = Colours.BLACK\n this.enabled = true\n\n const gl = getGl()\n if (!gl) {\n throw new Error('💥 LightDirectional: Cannot create shadow map shader, no GL context')\n }\n\n this._shadowMapProgram = twgl.createProgramInfo(gl, [vertShaderShadow, fragShaderShadow], ['shadowProgram'])\n }\n\n /**\n * Set the direction of the light ensuring it is normalized\n * @param direction - Direction vector\n */\n set direction(direction: XYZ) {\n // Ensure direction is normalized\n this._direction = Tuples.normalize(direction)\n }\n\n /**\n * Get the direction of the light\n */\n get direction() {\n return this._direction\n }\n\n /**\n * Convenience method allows setting the direction as a point relative to the world origin\n * Values are always converted to a normalized unit direction vector\n * @param x - X position\n * @param y - Y position\n * @param z - Z position\n */\n setAsPosition(x: number, y: number, z: number) {\n this._direction = Tuples.normalize([0 - x, 0 - y, 0 - z])\n }\n\n /**\n * Return the base set of uniforms for this light\n */\n get uniforms() {\n return {\n direction: this.direction,\n colour: this.enabled ? this.colour : [0, 0, 0],\n ambient: this.ambient ? this.ambient : [0, 0, 0],\n } as UniformSet\n }\n\n /**\n * Enable shadows for this light, this will create a shadow map texture and framebuffer\n * There is no way to disabled shadows once enabled\n * @param options A set of ShadowOptions to configure how shadows are calculated\n */\n enableShadows(options?: ShadowOptions) {\n this._shadowOptions = options ?? ({} as ShadowOptions)\n if (!this._shadowOptions.mapSize) {\n this._shadowOptions.mapSize = 512\n }\n if (!this._shadowOptions.zoom) {\n this._shadowOptions.zoom = 120\n }\n if (!this._shadowOptions.distance) {\n this._shadowOptions.distance = 1000\n }\n // if (!this._shadowOptions.scatter) {\n // this._shadowOptions.scatter = 0.22\n // }\n if (!this._shadowOptions.polygonOffset) {\n this._shadowOptions.polygonOffset = 0\n }\n\n const gl = getGl()\n if (!gl) {\n throw new Error('💥 LightDirectional: Cannot create shadow map, no GL context')\n }\n\n // This is a special type of texture, used for depth comparison and shadow mapping\n this._shadowMapTex = twgl.createTexture(gl, {\n width: this._shadowOptions.mapSize,\n height: this._shadowOptions.mapSize,\n internalFormat: gl.DEPTH_COMPONENT32F, // Makes this a depth texture\n compareMode: gl.COMPARE_REF_TO_TEXTURE, // Becomes a shadow map, e.g. sampler2DShadow\n minMag: gl.LINEAR, // Can be linear sampled only if compare mode is set\n })\n\n // Framebuffer to render the shadow map into\n this._shadowMapFB = twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._shadowMapTex, attachmentPoint: gl.DEPTH_ATTACHMENT }],\n this._shadowOptions.mapSize,\n this._shadowOptions.mapSize,\n )\n }\n\n /**\n * Get a virtual camera that can be used to render a shadow map for this light\n * @param viewCam - The main camera used to view the scene, needed to get a good shadow view\n */\n getShadowCamera(viewCam: Camera) {\n if (!this._shadowOptions) {\n return undefined\n }\n\n // Get view frustum corners & center to calculate a good shadow map view\n const corners = viewCam.frustumCornersWorld(this._shadowOptions.zoom / viewCam.far)\n const viewFrustumCenter = corners.center as XYZ\n\n // Create a virtual camera to render the shadow map\n const cam = new Camera(CameraType.ORTHOGRAPHIC, 1)\n cam.usedForShadowMap = true\n cam.position = [\n viewFrustumCenter[0] + -this.direction[0] * this._shadowOptions.distance,\n viewFrustumCenter[1] + -this.direction[1] * this._shadowOptions.distance,\n viewFrustumCenter[2] + -this.direction[2] * this._shadowOptions.distance,\n ]\n\n cam.lookAt = viewFrustumCenter\n cam.far = this._shadowOptions.distance * 2\n cam.orthoZoom = this._shadowOptions.zoom\n\n return cam\n }\n\n /**\n * Get the forward view matrix for the virtual camera used to render the shadow map.\n * Returns undefined if shadows are not enabled\n * @param viewCam - The main camera used to view the scene, needed to get a good shadow view\n */\n getShadowMatrix(viewCam: Camera) {\n if (!this._shadowOptions) {\n return undefined\n }\n\n const shadowCam = this.getShadowCamera(viewCam)\n if (!shadowCam) {\n return undefined\n }\n\n const shadowMat = mat4.multiply(\n mat4.create(),\n shadowCam.projectionMatrix,\n mat4.invert(mat4.create(), shadowCam.matrix),\n )\n\n return shadowMat\n }\n\n /**\n * Are shadows enabled for this light?\n */\n get shadowsEnabled() {\n return this._shadowOptions !== undefined\n }\n\n /**\n * Get the shadow map program, will be undefined if shadows are not enabled\n */\n get shadowMapProgram() {\n return this._shadowMapProgram\n }\n\n /**\n * Get the shadow map framebuffer, will be undefined if shadows are not enabled\n */\n get shadowMapFrameBufffer() {\n return this._shadowMapFB\n }\n\n /**\n * Get the shadow map texture, will be undefined if shadows are not enabled\n */\n get shadowMapTexture() {\n return this._shadowMapTex\n }\n\n /**\n * Get the shadow map options, will be undefined if shadows are not enabled\n */\n get shadowMapOptions() {\n return this._shadowOptions\n }\n}\n\n/*\n * A point light source, doesn't cast shadows but does attenuate with distance\n */\nexport class LightPoint {\n /** Position of the light in world space. */\n public position: XYZ\n\n /** Colour of the light. Default: [1, 1, 1] */\n public colour: RGB\n\n /** Ambient colour of the light. Normally none for point lights. Default [0, 0, 0] */\n public ambient: RGB\n\n /** Light attenuation parameter for constant drop off rate. Default: 0.5 */\n public constant: number\n\n /** Light attenuation parameter for linear drop off rate. Default: 0.018 */\n public linear: number\n\n /** Light attenuation parameter for quadratic drop off rate. Default: 0.0003 */\n public quad: number\n\n /** Is this light enabled? Default: true */\n public enabled: boolean\n\n /**\n * Create a default point light, positioned at the world origin\n * @param position - Position of the light in world space\n * @param colour - Colour of the light\n * @param constant - Attenuation constant drop off rate, default 0.5\n * @param linear - Attenuation linear drop off rate, default 0.018\n * @param quad - Attenuation quadratic drop off rate, default 0.0003\n */\n constructor(position: XYZ, colour: RGB, constant = 0.5, linear = 0.018, quad = 0.0003) {\n this.position = position\n this.colour = colour\n this.constant = constant\n this.linear = linear\n this.quad = quad\n\n // No ambient contribution by default, this can get messy otherwise\n this.ambient = Colours.BLACK\n this.enabled = true\n }\n\n /**\n * Return the base set of uniforms for this light\n */\n public get uniforms() {\n return {\n enabled: this.enabled,\n quad: this.quad,\n position: this.position,\n colour: this.colour,\n ambient: this.ambient,\n constant: this.constant,\n linear: this.linear,\n } as UniformSet\n }\n}\n","// ===== envmap.ts ==========================================================\n// EnvironmentMap class, for rendering reflections\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { mat4 } from 'gl-matrix'\nimport log from 'loglevel'\n\nimport { Camera, CameraType } from './camera.ts'\nimport { XYZ } from './tuples.ts'\n\nimport fragShaderEnvmap from '../../shaders/envmap/glsl.frag'\nimport vertShaderEnvmap from '../../shaders/envmap/glsl.vert'\nimport { Stats } from '../core/stats.ts'\nimport { Context } from '../core/context.ts'\n\nexport class EnvironmentMap {\n private programInfo: twgl.ProgramInfo\n private gl: WebGL2RenderingContext\n private _texture: WebGLTexture\n private cube: twgl.BufferInfo\n\n /**\n * Render the environment map as a background, like a skybox\n */\n public renderAsBackground: boolean\n\n /**\n * Create a new environment map with 6 textures for each side\n * @param gl GL context\n * @param textureURLs Array of 6 texture URLs, in order: +x, -x, +y, -y, +z, -z\n */\n constructor(gl: WebGL2RenderingContext, textureURLs: string[]) {\n this.gl = gl\n\n // Create shader program for special envmap rendering\n this.programInfo = twgl.createProgramInfo(gl, [vertShaderEnvmap, fragShaderEnvmap])\n\n // Create the cube\n this.cube = twgl.primitives.createCubeBufferInfo(gl, 1)\n this.renderAsBackground = true\n\n log.info(`🏔️ EnvironmentMap created!`)\n\n // Don't go via the texture cache, as cube maps are a special case\n if (textureURLs.length !== 6) {\n throw new Error('💥 Cubemap requires 6 textures')\n }\n\n this._texture = twgl.createTexture(gl, {\n target: gl.TEXTURE_CUBE_MAP,\n src: textureURLs,\n min: gl.LINEAR_MIPMAP_LINEAR,\n mag: gl.LINEAR,\n cubeFaceOrder: [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ],\n flipY: 0,\n })\n }\n\n /**\n * Render this envmap as a cube around the given camera & matrices\n * This is used for rendering the envmap as a background and skybox around the scene\n * @param viewMatrix View matrix\n * @param projMatrix Projection matrix\n * @param camera Camera\n */\n render(viewMatrix: mat4, projMatrix: mat4, camera: Camera) {\n if (!this.renderAsBackground) return\n\n this.gl.useProgram(this.programInfo.program)\n // Note: Disable depth test so envmap is always drawn behind everything else\n this.gl.disable(this.gl.DEPTH_TEST)\n\n const uniforms = {\n u_envMapTex: this._texture,\n u_worldViewProjection: mat4.create(),\n }\n\n const world = mat4.create()\n // Envmap magic 1 - translate envmap is always centered on camera\n mat4.translate(world, world, camera.position)\n // Envmap magic 2 - scale the envmap to be the same size as the camera far plane\n // This means it will always be drawn\n mat4.scale(world, world, [camera.far, camera.far, camera.far])\n\n // Create worldView matrix, used for positioning\n const worldView = mat4.multiply(mat4.create(), viewMatrix, world)\n\n mat4.multiply(uniforms.u_worldViewProjection, projMatrix, worldView)\n\n twgl.setBuffersAndAttributes(this.gl, this.programInfo, this.cube)\n twgl.setUniforms(this.programInfo, uniforms)\n twgl.drawBufferInfo(this.gl, this.cube)\n Stats.drawCallsPerFrame++\n\n this.gl.enable(this.gl.DEPTH_TEST)\n }\n\n get texture(): WebGLTexture {\n return this._texture\n }\n}\n\n/**\n * Used for rendering a dynamic environment map, to create realtime reflections\n * For performance reasons, there is only one dynamic envmap per scene context\n */\nexport class DynamicEnvironmentMap {\n private _texture: WebGLTexture\n private facings: DynamicEnvMapFace[] = []\n private camera: Camera\n\n /**\n * Create a new dynamic environment map\n * @param gl GL context\n * @param size Size of each face of the cube map\n * @param position Position of the center of the cube map, reflections will be rendered from here\n */\n constructor(gl: WebGL2RenderingContext, size: number, position: XYZ, far: number) {\n // The main texture cubemap\n this._texture = twgl.createTexture(gl, {\n target: gl.TEXTURE_CUBE_MAP,\n width: size,\n height: size,\n minMag: gl.LINEAR,\n cubeFaceOrder: [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ],\n })\n\n // This array holds the 6 faces of the cube map and the framebuffer info plus direction\n this.facings = [\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n direction: [1, 0, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_X }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n direction: [-1, 0, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_X }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n direction: [0, 1, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_Y }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n direction: [0, -1, 0],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n direction: [0, 0, 1],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_POSITIVE_Z }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n {\n face: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n direction: [0, 0, -1],\n buffer: twgl.createFramebufferInfo(\n gl,\n [{ attachment: this._texture, target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z }, { format: gl.DEPTH_COMPONENT16 }],\n size,\n size,\n ),\n },\n ]\n\n this.camera = new Camera(CameraType.PERSPECTIVE)\n this.camera.position = position\n this.camera.fov = 90 // 90 degree FOV for cubemap to work properly\n\n // IMPORTANT: Mark this as a special camera used for envmaps\n this.camera.usedForEnvMap = true\n\n this.camera.far = far\n }\n\n /** Get the texture of the environment cubemap */\n get texture(): WebGLTexture {\n return this._texture\n }\n\n /**\n * This is used to position the camera for creating the reflection map\n * @param position Position of the center of the cube map\n */\n set position(pos: XYZ) {\n this.camera.position = pos\n }\n\n /**\n * Update the environment map, by rendering the scene from the given position into the cubemap texture\n * @param ctx GSOTS Context\n */\n update(gl: WebGL2RenderingContext, ctx: Context) {\n // Render each face of the cubemap into the texture & framebuffer\n // NOTE: This requires SIX calls to renderWithCamera!\n for (const facing of this.facings) {\n // Update the camera to look in the direction of the face\n this.camera.lookAt = [\n this.camera.position[0] + facing.direction[0],\n this.camera.position[1] + facing.direction[1],\n this.camera.position[2] + facing.direction[2],\n ]\n\n // Stops the camera from flipping upside down and other weirdness\n this.camera.up = [0, -1, 0]\n if (facing.face === gl.TEXTURE_CUBE_MAP_NEGATIVE_Y) {\n this.camera.up = [0, 0, -1]\n }\n if (facing.face === gl.TEXTURE_CUBE_MAP_POSITIVE_Y) {\n this.camera.up = [0, 0, 1]\n }\n\n twgl.bindFramebufferInfo(gl, facing.buffer)\n ctx.renderWithCamera(this.camera)\n }\n }\n}\n\n/**\n * Internal type for storing a dynamic envmap facing info\n */\ntype DynamicEnvMapFace = {\n face: number\n direction: XYZ\n buffer: twgl.FramebufferInfo\n}\n","#version 300 es\n\n// ============================================================================\n// Environment map fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec3 v_texCoord;\n\nuniform samplerCube u_envMapTex;\n\nout vec4 outColour;\n\nvoid main() {\n // Use the texture cube map as the colour\n // Note: We don't need to do any lighting calculations here\n outColour = texture(u_envMapTex, v_texCoord);\n}\n","#version 300 es\n\n// ============================================================================\n// Environment map vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\n\nuniform mat4 u_worldViewProjection;\n\nout vec3 v_texCoord;\n\nvoid main() {\n // This essentially is what makes the envmap work, texCoords\n // are taken from the vertex position\n v_texCoord = position.xyz;\n\n gl_Position = u_worldViewProjection * position;\n}\n","// ===== stats.ts =======================================================\n// Global singleton for keeping track of stats, timers performance\n// Ben Coleman, 2023\n// ======================================================================\n\nexport const Stats = {\n drawCallsPerFrame: 0,\n instances: 0,\n triangles: 0,\n\n prevTime: 0,\n deltaTime: 0,\n totalTime: 0,\n frameCount: 0,\n fpsBucket: [] as number[],\n\n resetPerFrame() {\n Stats.drawCallsPerFrame = 0\n },\n\n updateTime(now: number) {\n Stats.deltaTime = now * 0.001 - Stats.prevTime // Get smoothed time difference\n Stats.prevTime = now * 0.001\n Stats.totalTime += Stats.deltaTime\n\n Stats.fpsBucket.push(Stats.deltaTime)\n if (Stats.fpsBucket.length > 10) {\n Stats.fpsBucket.shift()\n }\n },\n\n get FPS() {\n const sum = Stats.fpsBucket.reduce((a, b) => a + b, 0)\n return Math.round(1 / (sum / Stats.fpsBucket.length))\n },\n\n get totalTimeRound() {\n return Math.round(Stats.totalTime)\n },\n}\n","// ===== node.ts ===============================================================================\n// Node in the scene used to position, rotate and scale them, with a parent/child relationship\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport { mat4, quat } from 'gl-matrix'\nimport { Tuples, XYZ, XYZW } from './tuples.ts'\n\nimport log from 'loglevel'\nimport * as CANNON from 'cannon-es'\n\nconst EVENT_POSITION = 'position'\n\n/** Event triggered when a node position, rotation or scale changes */\nexport type NodeEvent = {\n position: XYZ\n rotation: XYZW\n scale: XYZ\n nodeId: string\n}\n\n/**\n * A Node with position, rotation, scale, all Instances extend this class.\n * But Nodes also be created to group instances and simplify transformations.\n */\nexport class Node {\n /** Unique ID for this node */\n public readonly id: string\n\n /** Position of this Node in world space, relative to any parent nodes (if any) */\n public position: XYZ\n\n /** Scale of this Node in world space, relative to any parent nodes (if any) */\n public scale: XYZ\n\n /** Rotation quaternion of this Node in world space, relative to any parent nodes (if any) */\n public quaternion: quat\n\n /** Metadata is a key/value store for any extra data you want to store on a node */\n public metadata: Record\n\n // Private properties with getters/setters\n private _receiveShadow: boolean\n private _castShadow: boolean\n private _enabled: boolean\n private _parent?: Node\n private _children: Node[] = []\n private _physicsBody?: CANNON.Body\n\n // Event handlers\n private eventHandlers: Map void)[]>\n\n /** Create a default node, at origin with scale of [1,1,1] and no rotation */\n constructor() {\n this.id = uniqueId()\n this.metadata = {}\n this.eventHandlers = new Map()\n this.eventHandlers.set(EVENT_POSITION, [])\n\n this.position = [0, 0, 0]\n this.scale = [1, 1, 1]\n this.quaternion = quat.create()\n\n this._enabled = true\n this._receiveShadow = true\n this._castShadow = true\n this._physicsBody = undefined\n\n log.debug(`📍 Node created with id ${this.id}`)\n }\n\n /** Rotate this instance around the X, Y and Z axis in radians */\n rotate(ax: number, ay: number, az: number) {\n quat.rotateX(this.quaternion, this.quaternion, ax)\n quat.rotateY(this.quaternion, this.quaternion, ay)\n quat.rotateZ(this.quaternion, this.quaternion, az)\n }\n\n /** Rotate this instance around the X axis*/\n rotateX(angle: number) {\n quat.rotateX(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the Y axis*/\n rotateY(angle: number) {\n quat.rotateY(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the Z axis, in radians*/\n rotateZ(angle: number) {\n quat.rotateZ(this.quaternion, this.quaternion, angle)\n }\n\n /** Rotate this instance around the X axis by a given angle in degrees */\n rotateZDeg(angle: number) {\n this.rotateZ((angle * Math.PI) / 180)\n }\n\n /** Rotate this instance around the Y axis by a given angle in degrees */\n rotateYDeg(angle: number) {\n this.rotateY((angle * Math.PI) / 180)\n }\n\n /** Rotate this instance around the Z axis by a given angle in degrees */\n rotateXDeg(angle: number) {\n this.rotateX((angle * Math.PI) / 180)\n }\n\n /** Set the rotation quaternion directly, normally users should use the rotate methods.\n * This method is for advanced uses, like integration with an external physics system */\n setQuaternion(quatArray: XYZW) {\n this.quaternion = quat.fromValues(quatArray[0], quatArray[1], quatArray[2], quatArray[3])\n }\n\n /** Get the rotation quaternion as a XYZW 4-tuple */\n getQuaternion(): XYZW {\n return [this.quaternion[0], this.quaternion[1], this.quaternion[2], this.quaternion[3]]\n }\n\n /**\n * Return the world or model matrix for this node, this is the matrix that places this node in the world.\n * This will be in relation to the parent node, if there is one.\n */\n get modelMatrix(): mat4 {\n const modelMatrix = mat4.fromRotationTranslationScale(mat4.create(), this.quaternion, this.position, this.scale)\n\n if (!this.parent) {\n return modelMatrix\n }\n\n mat4.multiply(modelMatrix, this.parent.modelMatrix ?? mat4.create(), modelMatrix)\n\n return modelMatrix\n }\n\n /** Convenience method to make another Node a child of this one */\n addChild(node: Node) {\n node._parent = this\n\n this._children.push(node)\n }\n\n /** Convenience method to remove a child Node */\n removeChild(node: Node) {\n node._parent = undefined\n\n this._children = this._children.filter((child) => child.id !== node.id)\n }\n\n /** Convenience method to remove all child Nodes */\n removeAllChildren() {\n this._children.forEach((child) => {\n child._parent = undefined\n })\n\n this._children = []\n }\n\n /** Sets the parent this Node, to the provided Node */\n set parent(node: Node | undefined) {\n // remove from old parent if there is one\n if (this._parent) {\n this._parent.removeChild(this)\n }\n\n // Add to new parent if there is one\n if (node) {\n node.addChild(this)\n }\n }\n\n /** Fetch all child Nodes of this Node */\n get children(): Node[] {\n return this._children\n }\n\n /** Get current parent of this Node */\n get parent(): Node | undefined {\n return this._parent\n }\n\n /** Is this Node enabled. Disabled nodes will not be rendered */\n get enabled(): boolean {\n return this._enabled\n }\n\n /** Set enabled state of this Node, this will also set all child nodes */\n set enabled(enabled: boolean) {\n this._enabled = enabled\n\n this._children.forEach((child) => {\n child.enabled = enabled\n })\n }\n\n /** Does this Node cast shadows, default true */\n public get castShadow(): boolean {\n return this._castShadow\n }\n\n /** Set will this Node cast shadows, this will also set all child nodes */\n public set castShadow(value: boolean) {\n this._castShadow = value\n\n this._children.forEach((child) => {\n child.castShadow = value\n })\n }\n\n /** Does this Node receive shadows, default true */\n public get receiveShadow(): boolean {\n return this._receiveShadow\n }\n\n /** Set will this Node receive shadows, this will also set all child nodes */\n public set receiveShadow(value: boolean) {\n this._receiveShadow = value\n\n this._children.forEach((child) => {\n child.receiveShadow = value\n })\n }\n\n /** Get the physics body for this Node, if there is one */\n public get physicsBody(): CANNON.Body | undefined {\n return this._physicsBody\n }\n\n /** Set the physics body for this Node */\n public set physicsBody(body: CANNON.Body | undefined) {\n this._physicsBody = body\n }\n\n /**\n * Updates the position & rotation of this node to match it's linked physics Body\n * This is called automatically by the engine, but can be called manually if needed\n */\n public updateFromPhysicsBody() {\n if (!this._physicsBody) return\n\n this.position = Tuples.fromCannon(this._physicsBody.position) as XYZ\n this.setQuaternion(Tuples.fromCannon(this._physicsBody.quaternion) as XYZW)\n\n // Trigger position event handlers\n for (const handler of this.eventHandlers.get(EVENT_POSITION) ?? []) {\n handler({\n position: this.position,\n rotation: this.getQuaternion(),\n scale: this.scale,\n nodeId: this.id,\n })\n }\n }\n\n /**\n * Add an event handler to listen for node changes\n * @param event NodeEvent type, one of 'position', 'rotation', 'scale'\n * @param handler Function to call when event is triggered\n */\n addEventHandler(event: string, handler: (event: NodeEvent) => void) {\n this.eventHandlers.get(event)?.push(handler)\n }\n}\n\n/** Generate a unique ID for a node */\nfunction uniqueId() {\n const dateString = Date.now().toString(36).substring(0, 5)\n const randomness = Math.random().toString(36).substring(0, 5)\n return dateString + randomness\n}\n","// ===== instance.ts ==========================================================\n// Instance class, holds position, rotation, scale etc for a renderable\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4 } from 'gl-matrix'\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { XYZ } from '../engine/tuples.ts'\nimport { ProgramInfo } from 'twgl.js'\nimport { Node } from '../engine/node.ts'\n\n/**\n * An instance of thing in the world to be rendered, with position, rotation, scale etc\n */\nexport class Instance extends Node {\n /** Main renderable thing this instance represents */\n public readonly renderable: Renderable | undefined\n\n /** Flip all textures on this instance on the X axis */\n public flipTextureX = false\n\n /** Flip all textures on this instance on the Y axis */\n public flipTextureY = false\n\n /** Material override. This will override the renderable's material.\n * This is only useful on simple models that probably consist of one surface */\n public material?: Material\n\n /**\n * Create a new instace of a renderable thing\n * @param {Renderable} renderable - Renderable to use for this instance\n */\n constructor(renderable: Renderable) {\n super()\n this.renderable = renderable\n }\n\n setPosition(x: number | XYZ, y?: number, z?: number) {\n if (x instanceof Array) {\n this.position = x\n return\n }\n\n if (y === undefined || z === undefined) throw new Error('setPosition requires either an array or 3 numbers')\n\n this.position = [x, y, z]\n }\n\n /**\n * Render this instance in the world, called internally by the context when rendering\n * @param {WebGL2RenderingContext} gl - WebGL context to render into\n * @param {UniformSet} uniforms - Map of uniforms to pass to shader\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet, programOverride?: ProgramInfo) {\n if (!this.enabled) return\n if (!this.renderable) return\n if (!gl) return\n\n // HACK: As programOverride is CURRENTLY only used for shadow map rendering\n // We need a better way to to know if we are rendering a shadow map!!\n if (programOverride && !this.castShadow) {\n return\n }\n\n const world = this.modelMatrix\n\n // Populate u_world - used for normals & shading\n uniforms.u_world = world\n\n // Populate u_worldInverseTranspose - used for normals & shading\n mat4.invert(uniforms.u_worldInverseTranspose, world)\n mat4.transpose(uniforms.u_worldInverseTranspose, uniforms.u_worldInverseTranspose)\n\n // Create worldView matrix, used for positioning\n const worldView = mat4.multiply(mat4.create(), uniforms.u_view, world)\n\n // Finally populate u_worldViewProjection used for rendering\n mat4.multiply(uniforms.u_worldViewProjection, uniforms.u_proj, worldView)\n\n // Apply per instance uniforms for the shader\n uniforms.u_flipTextureX = this.flipTextureX\n uniforms.u_flipTextureY = this.flipTextureY\n uniforms.u_receiveShadow = this.receiveShadow\n\n // Render the renderable thing wrapped by this instance\n this.renderable.render(gl, uniforms, this.material, programOverride)\n }\n}\n","// ===== billboard.ts =========================================================\n// For drawing 2D billboards, like trees, grass, etc\n// Ben Coleman, 2023\n// ============================================================================\n\nimport { mat4, vec3 } from 'gl-matrix'\nimport * as twgl from 'twgl.js'\n\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/** Billboarding modes, most things will ue NONE */\nexport enum BillboardType {\n SPHERICAL,\n CYLINDRICAL,\n}\n\n/**\n * A simple 2D billboard, like a tree or grass. These are square by default, but can be scaled XY if needed.\n * Both cylindrical and spherical billboards are supported. You must assign material with a texture\n * to be rendered as a sprite on the billboard\n * @see http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/billboards/\n */\nexport class Billboard implements Renderable {\n protected bufferInfo: twgl.BufferInfo\n private programInfo: twgl.ProgramInfo\n public material: Material\n public type: BillboardType = BillboardType.CYLINDRICAL\n\n /** Creates a square billboard */\n constructor(gl: WebGL2RenderingContext, type: BillboardType, material: Material, size: number) {\n this.material = material\n this.type = type\n\n // Create quad vertices\n const verts = twgl.primitives.createXYQuadVertices(size, 0, size / 2)\n\n // Flip Y axis, so texture is not upside down\n for (let i = 1; i < verts.texcoord.length; i += 2) {\n verts.texcoord[i] = 1 - verts.texcoord[i]\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n\n // Use the billboard shader for this renderable\n this.programInfo = ProgramCache.instance.get(ProgramCache.PROG_BILLBOARD)\n }\n\n /**\n * Render is used draw this billboard, this is called from the Instance that wraps\n * this renderable\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet, materialOverride?: Material): void {\n // We ignore programOverride here, as we always use the billboard shader\n const programInfo = this.programInfo\n\n gl.useProgram(programInfo.program)\n\n if (materialOverride === undefined) {\n this.material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n // We're doubling up on work done in the Instance class here, hard to get around this\n const worldView = mat4.multiply(mat4.create(), uniforms.u_view, uniforms.u_world)\n\n // Extract scale from worldView matrix, before we zap it\n const scale = mat4.getScaling(vec3.create(), worldView)\n\n // For CYLINDRICAL billboarding, we need to remove some parts of the worldView matrix\n // See: https://www.geeks3d.com/20140807/billboarding-vertex-shader-glsl/\n worldView[0] = scale[0]\n worldView[1] = 0\n worldView[2] = 0\n worldView[8] = 0\n worldView[9] = 0\n worldView[10] = scale[2]\n\n if (this.type == BillboardType.SPHERICAL) {\n // For SPHERICAL billboarding, we remove some more\n worldView[4] = 0\n worldView[5] = scale[1]\n worldView[6] = 0\n }\n\n // We're doubling up on work again :/\n mat4.multiply(uniforms.u_worldViewProjection, uniforms.u_proj, worldView)\n\n twgl.setBuffersAndAttributes(gl, programInfo, this.bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, this.bufferInfo)\n Stats.drawCallsPerFrame++\n }\n}\n","// ===== material.ts ==========================================================\n// Represents a material, with all the properties from the MTL file\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { RGB } from './tuples.ts'\nimport { MtlMaterial } from '../parsers/mtl-parser.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { TextureCache } from '../core/cache.ts'\n\nexport class Material {\n /**\n * Ambient colour will be multiplied with the ambient light level & colour\n */\n public ambient: RGB\n\n /**\n * Diffuse colour will be multiplied with the diffuse texture\n * @default [1, 1, 1]\n */\n public diffuse: RGB\n\n /**\n * Specular colour will be multiplied with the specular texture\n * @default [0, 0, 0]\n */\n public specular: RGB\n\n /**\n * Emissive colour will be added to the final colour, use for glowing materials\n */\n public emissive: RGB\n\n /**\n * Shininess, for size of specular highlights\n * @default 20\n */\n public shininess: number\n\n /**\n * Opacity, 0.0 to 1.0\n * @default 1.0\n */\n public opacity: number\n\n /**\n * Reflectivity, 0.0 to 1.0\n * @default 0.0\n */\n public reflectivity: number\n\n /**\n * Diffuse texture map\n * @default \"1 pixel white texture\"\n */\n public diffuseTex?: WebGLTexture\n\n /**\n * Specular texture map\n * @default \"1 pixel white texture\"\n */\n public specularTex?: WebGLTexture\n\n /**\n * Normal texture map\n * @default \"1 pixel white texture\"\n */\n public normalTex?: WebGLTexture\n\n /**\n * Don't apply any lighting or shading to this material\n * @default false\n */\n public unshaded: boolean\n\n /**\n * Create a new default material with diffuse white colour, all all default properties\n */\n constructor() {\n this.ambient = [1, 1, 1]\n this.diffuse = [1, 1, 1]\n this.specular = [0, 0, 0]\n this.emissive = [0, 0, 0]\n\n this.shininess = 20\n this.opacity = 1.0\n this.reflectivity = 0.0\n\n this.unshaded = false\n\n // 1 pixel white texture is used for solid colour & flat materials\n // A trick to avoid having multiple shaders for textured & non-textured materials\n this.diffuseTex = TextureCache.defaultWhite\n this.specularTex = TextureCache.defaultWhite\n }\n\n /**\n * Create a new material from a raw MTL material. Users are not expected to call this directly as it is used internally by the OBJ parser\n * @param rawMtl Raw MTL material\n * @param basePath Base path for locating & loading textures in MTL file\n * @param filter Apply texture filtering to textures, default: true\n * @param flipY Flip the Y axis of textures, default: false\n */\n static fromMtl(rawMtl: MtlMaterial, basePath: string, filter = true, flipY = false) {\n const m = new Material()\n\n m.ambient = rawMtl.ka ? rawMtl.ka : [1, 1, 1]\n m.diffuse = rawMtl.kd ? rawMtl.kd : [1, 1, 1]\n m.specular = rawMtl.ks ? rawMtl.ks : [0, 0, 0]\n m.emissive = rawMtl.ke ? rawMtl.ke : [0, 0, 0]\n m.shininess = rawMtl.ns ? rawMtl.ns : 0\n m.opacity = rawMtl.d ? rawMtl.d : 1.0\n\n if (rawMtl.texDiffuse) {\n m.diffuseTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texDiffuse}`, filter, flipY)\n }\n\n if (rawMtl.texSpecular) {\n m.specularTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texSpecular}`, filter, flipY)\n }\n\n if (rawMtl.texNormal) {\n m.normalTex = TextureCache.instance.getCreate(`${basePath}/${rawMtl.texNormal}`, filter, flipY)\n }\n\n // This is a kludge, a guess; if illum is 3 or more and Ks is set, then we have\n // A reflective material of some kind\n if (rawMtl.illum && rawMtl.illum > 2) {\n m.reflectivity = (m.specular[0] + m.specular[1] + m.specular[2]) / 3\n }\n\n return m\n }\n\n /**\n * Create a basic Material with a solid/flat diffuse colour\n * @param r Red component, 0.0 to 1.0\n * @param g Green component, 0.0 to 1.0\n * @param b Blue component, 0.0 to 1.0\n */\n static createSolidColour(r: number, g: number, b: number) {\n const m = new Material()\n m.diffuse = [r, g, b]\n\n return m\n }\n\n /**\n * Create a new Material with a texture map loaded from a URL/filepath or Buffer\n * @param src URL or filename path of texture image, or ArrayBufferView holding texture\n * @param filter Enable texture filtering and mipmaps (default true)\n * @param flipY Flip the texture vertically (default false)\n */\n static createBasicTexture(src: string | ArrayBufferView, filter = true, flipY = false) {\n const m = new Material()\n\n if (typeof src === 'string') {\n m.diffuseTex = TextureCache.instance.getCreate(src, filter, flipY)\n } else {\n // Invent a unique key for this texture\n const key = `arraybuffer_${TextureCache.size}`\n m.diffuseTex = TextureCache.instance.getCreate(src, filter, flipY, key)\n }\n\n return m\n }\n\n /**\n * Add a specular texture map to existing material, probably created with createBasicTexture\n * @param url\n * @param filter\n */\n addSpecularTexture(url: string, filter = true, flipY = false) {\n this.specularTex = TextureCache.instance.getCreate(url, filter, flipY)\n this.specular = [1, 1, 1]\n this.shininess = 20\n }\n\n /**\n * Add a normal texture map to existing material, probably created with createBasicTexture\n * @param url\n * @param filter\n */\n addNormalTexture(url: string, filter = true, flipY = false) {\n this.normalTex = TextureCache.instance.getCreate(url, filter, flipY)\n }\n\n /** Create a simple diffuse red Material */\n static get RED() {\n return Material.createSolidColour(1.0, 0.0, 0.0)\n }\n\n /** Create a simple diffuse green Material */\n static get GREEN() {\n return Material.createSolidColour(0.0, 1.0, 0.0)\n }\n\n /** Create a simple diffuse blue Material */\n static get BLUE() {\n return Material.createSolidColour(0.0, 0.0, 1.0)\n }\n\n /** Create a simple diffuse white Material */\n static get WHITE() {\n return Material.createSolidColour(1.0, 1.0, 1.0)\n }\n\n /** Create a simple diffuse black Material */\n static get BLACK() {\n return Material.createSolidColour(0.0, 0.0, 0.0)\n }\n\n /** Create a simple diffuse yellow Material */\n static get YELLOW() {\n return Material.createSolidColour(1.0, 1.0, 0.0)\n }\n\n /** Create a simple diffuse magenta Material */\n static get MAGENTA() {\n return Material.createSolidColour(1.0, 0.0, 1.0)\n }\n\n /** Create a simple diffuse cyan Material */\n static get CYAN() {\n return Material.createSolidColour(0.0, 1.0, 1.0)\n }\n\n /**\n * Adds this material to a program, as a set of uniforms\n * @param programInfo ProgramInfo object to update with uniforms\n * @param uniformSuffix Optional suffix to add to uniform names\n */\n apply(programInfo: twgl.ProgramInfo, uniformSuffix = '') {\n const uni = {\n [`u_mat${uniformSuffix}`]: this.uniforms,\n }\n\n twgl.setUniforms(programInfo, uni)\n }\n\n /**\n * Return the base set of uniforms for this material\n * @returns UniformSet object with all material properties\n */\n get uniforms(): UniformSet {\n return {\n ambient: this.ambient,\n diffuse: this.diffuse,\n specular: this.specular,\n emissive: this.emissive,\n shininess: this.shininess,\n opacity: this.opacity,\n reflectivity: this.reflectivity,\n diffuseTex: this.diffuseTex ? this.diffuseTex : null,\n specularTex: this.specularTex ? this.specularTex : null,\n normalTex: this.normalTex ? this.normalTex : null,\n hasNormalTex: this.normalTex ? true : false,\n unshaded: this.unshaded,\n } as UniformSet\n }\n\n /**\n * Clone this material, returns a new material with the same properties\n */\n clone() {\n const m = new Material()\n m.ambient = this.ambient\n m.diffuse = this.diffuse\n m.specular = this.specular\n m.emissive = this.emissive\n m.shininess = this.shininess\n m.opacity = this.opacity\n m.reflectivity = this.reflectivity\n m.diffuseTex = this.diffuseTex\n m.specularTex = this.specularTex\n m.normalTex = this.normalTex\n\n return m\n }\n}\n","// ======== primitive.ts ======================================================\n// Main model class, holds a list of parts, each with a material\n// Models are parsed from OBJ files\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Material } from '../engine/material.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/**\n * A simple primitive 3D object, like a sphere or cube\n */\nexport abstract class Primitive implements Renderable {\n protected bufferInfo: twgl.BufferInfo | undefined\n private programInfo: twgl.ProgramInfo\n public material: Material\n protected triangles: number\n\n constructor() {\n this.material = new Material()\n this.triangles = 0\n this.programInfo = ProgramCache.instance.default\n }\n\n get triangleCount(): number {\n return this.triangles\n }\n\n /**\n * Render is used draw this primitive, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ) {\n if (!this.bufferInfo) return\n\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n if (materialOverride === undefined) {\n this.material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, this.bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n // If cylinder without caps, disable culling\n let disableCulling = false\n\n if (this instanceof PrimitiveCylinder && !this.caps) {\n gl.disable(gl.CULL_FACE)\n disableCulling = true\n }\n\n twgl.drawBufferInfo(gl, this.bufferInfo)\n\n if (disableCulling) {\n gl.enable(gl.CULL_FACE)\n }\n\n Stats.drawCallsPerFrame++\n }\n}\n\n/**\n * A simple sphere primitive with a given radius and subdivisions\n */\nexport class PrimitiveSphere extends Primitive {\n readonly radius: number\n\n /**\n * Create a new sphere primitive\n * @param gl WebGL2RenderingContext\n * @param radius Radius of the sphere\n * @param subdivisionsH Number of horizontal subdivisions\n * @param subdivisionsV Number of vertical subdivisions\n */\n constructor(gl: WebGL2RenderingContext, radius: number, subdivisionsH: number, subdivisionsV: number) {\n super()\n\n this.bufferInfo = twgl.primitives.createSphereBufferInfo(gl, radius, subdivisionsH, subdivisionsV)\n this.triangles += this.bufferInfo.numElements / 3\n this.radius = radius\n }\n}\n\n/**\n * A simple cube primitive with a given size\n */\nexport class PrimitiveCube extends Primitive {\n readonly size: number\n\n /**\n * Create a new cube primitive\n * @param gl WebGL2RenderingContext\n * @param size Size of the cube\n */\n constructor(gl: WebGL2RenderingContext, size: number, tilingFactor?: number) {\n super()\n\n const verts = twgl.primitives.createCubeVertices(size)\n\n // Mutate the texture coords to tile the texture\n if (tilingFactor) {\n for (let i = 0; i < verts.texcoord.length; i++) {\n verts.texcoord[i] = verts.texcoord[i] * tilingFactor\n }\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n\n this.triangles += this.bufferInfo.numElements / 3\n this.size = size\n }\n}\n\n/**\n * A simple plane primitive with a given size, subdivisions & tiling factor\n */\nexport class PrimitivePlane extends Primitive {\n /**\n * Create a new plane primitive\n * @param gl WebGL2RenderingContext\n * @param width Width of the plane\n * @param height Height of the plane\n * @param subdivisionsW Number of horizontal subdivisions\n * @param subdivisionsH Number of vertical subdivisions\n * @param tilingFactor Number of times to tile the texture across the plane\n */\n constructor(\n gl: WebGL2RenderingContext,\n width: number,\n height: number,\n subdivisionsW: number,\n subdivisionsH: number,\n tilingFactor: number,\n ) {\n super()\n\n const verts = twgl.primitives.createPlaneVertices(width, height, subdivisionsW, subdivisionsH)\n\n // Mutate the texture coords to tile the texture\n for (let i = 0; i < verts.texcoord.length; i++) {\n verts.texcoord[i] = verts.texcoord[i] * tilingFactor\n }\n\n this.bufferInfo = twgl.createBufferInfoFromArrays(gl, verts)\n this.triangles += this.bufferInfo.numElements / 3\n }\n}\n\n/**\n * A simple cylinder primitive with a given radius, height and subdivisions\n */\nexport class PrimitiveCylinder extends Primitive {\n public readonly caps: boolean\n /**\n * Create a new cylinder primitive\n * @param gl WebGL2RenderingContext\n * @param radius Radius of the cylinder\n * @param height Height of the cylinder\n * @param subdivisionsR Subdivisions around the cylinder\n * @param subdivisionsV Subdivisions vertically\n * @param caps Should the cylinder have caps\n */\n constructor(\n gl: WebGL2RenderingContext,\n radius: number,\n height: number,\n subdivisionsR: number,\n subdivisionsV: number,\n caps: boolean,\n ) {\n super()\n\n this.caps = caps\n this.bufferInfo = twgl.primitives.createCylinderBufferInfo(\n gl,\n radius,\n height,\n subdivisionsR,\n subdivisionsV,\n caps,\n caps,\n )\n\n this.triangles += this.bufferInfo.numElements / 3\n }\n}\n","// ===== particles.ts =========================================================\n// Particle system using GPU for particle simulation and VAO instancing\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport log from 'loglevel'\n\nimport updateFS from '../../shaders/particles/update.frag'\nimport updateVS from '../../shaders/particles/update.vert'\nimport renderFS from '../../shaders/particles/render.frag'\nimport renderVS from '../../shaders/particles/render.vert'\n\nimport { Renderable } from './types.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { Stats } from '../core/stats.ts'\nimport { RGBA, XYZ } from '../engine/tuples.ts'\nimport { TextureCache } from '../core/cache.ts'\nimport { mat4, vec3 } from 'gl-matrix'\n\nconst emptyMat = mat4.create()\n\n/**\n * Particle system, uses transform feedback on the GPU to update particles\n * and VAO instancing to render them\n */\nexport class ParticleSystem implements Renderable {\n private progInfoUpdate: twgl.ProgramInfo\n private progInfoRender: twgl.ProgramInfo\n private inputBuffInfo: twgl.BufferInfo\n private outputBuffInfo: twgl.BufferInfo\n private outputVAO: twgl.VertexArrayInfo\n\n /** When enabled, particles will be spawned and emitted */\n public enabled: boolean\n /** Texture to use for particles */\n public texture: WebGLTexture\n /** Emission rate, number of particles per frame */\n public emitRate: number\n /** Min lifetime of particles in seconds */\n public minLifetime: number\n /** Max lifetime of particles in seconds */\n public maxLifetime: number\n /** Gravity vector. Default: [0, -9.81, 0] */\n public gravity: XYZ\n /** Min power (speed) of particles, this is multiplied by the direction vector */\n public minPower: number\n /** Max power (speed) of particles, this is multiplied by the direction vector */\n public maxPower: number\n /** Particles will randomly emit in a direction between this vector and direction2 */\n public direction1: XYZ\n /** Particles will randomly emit in a direction between this vector and direction1 */\n public direction2: XYZ\n /** Particles are spawned in a bounding box, defined by this vector as one corner */\n public emitterBoxMin: XYZ\n /** Particles are spawned in a bounding box, defined by this vector as one corner */\n public emitterBoxMax: XYZ\n /** Speed up or slow down time */\n public timeScale: number\n /** Change colour and alpha as particle reaches it's lifetime. Default: [0,0,0,1] */\n public ageColour: RGBA\n /** Min random size of particles */\n public minSize: number\n /** Max random size of particles */\n public maxSize: number\n /** Min initial random rotation of particles in radians */\n public minInitialRotation: number\n /** Max initial random rotation of particles in radians */\n public maxInitialRotation: number\n /** Min random rotation speed of particles in radians per second */\n public minRotationSpeed: number\n /** Max random rotation speed of particles in radians per second */\n public maxRotationSpeed: number\n /** Duration of particle system in frames, -1 = forever. Default: -1 */\n public duration: number\n /** Acceleration or deceleration multiplier, default 1.0. Applied every frame, so keep values *very* close to 1.0 */\n public acceleration: number\n /** Blend source mode, default: 'SRC_ALPHA', leave alone unless you know what you are doing */\n public blendSource: number\n /** Blend destination mode, default: 'ONE', leave alone unless you know what you are doing */\n public blendDest: number\n /** Colour multiplier pre-applied to particle texture before ageing */\n public preColour: RGBA\n /** Age power curve */\n public agePower: number\n /** Particles transformed fixed to local coordinate space, generally leave as false */\n public localSpace: boolean\n\n /**\n * Create a new particle system\n * @param gl WebGL2 rendering context\n * @param maxParticles Maximum number of particles in the system\n * @param baseSize Size of the particle quad\n */\n constructor(gl: WebGL2RenderingContext, maxParticles: number, baseSize: number) {\n this.emitRate = 300\n this.minLifetime = 2.0\n this.maxLifetime = 6.0\n this.minPower = 25\n this.maxPower = 35\n this.gravity = [0, -9.81, 0]\n this.direction1 = [-0.5, 1, -0.5]\n this.direction2 = [0.5, 1, 0.5]\n this.timeScale = 3.0\n this.ageColour = [0.0, 0.0, 0.0, 1.0]\n this.minSize = 1.0\n this.maxSize = 1.0\n this.minInitialRotation = 0.0\n this.maxInitialRotation = 0.0\n this.minRotationSpeed = 0.0\n this.maxRotationSpeed = 0.0\n this.duration = -1\n this.enabled = true\n this.emitterBoxMin = [0, 0, 0]\n this.emitterBoxMax = [0, 0, 0]\n this.acceleration = 1.0\n this.blendSource = gl.SRC_ALPHA\n this.blendDest = gl.ONE\n this.preColour = [1.0, 1.0, 1.0, 1.0]\n this.agePower = 1.0\n this.localSpace = false\n\n // Create shaders and programs\n this.progInfoUpdate = twgl.createProgramInfo(gl, [updateVS, updateFS], {\n transformFeedbackVaryings: ['tf_position', 'tf_velocity', 'tf_age', 'tf_props'],\n })\n this.progInfoRender = twgl.createProgramInfo(gl, [renderVS, renderFS])\n\n // Create initial buffers, note these are for ALL particles regardless of emission rate\n // These are all updated in the shader\n const positions = new Float32Array(maxParticles * 4)\n const velocities = new Float32Array(maxParticles * 3)\n const ages = new Float32Array(maxParticles * 2)\n const props = new Float32Array(maxParticles * 4)\n const seeds = new Float32Array(maxParticles)\n for (let i = 0; i < maxParticles; i++) {\n positions[i * 3] = 0\n positions[i * 3 + 1] = 0\n positions[i * 3 + 2] = 0\n positions[i * 3 + 3] = 0 // Rotation\n\n velocities[i * 3] = 0\n velocities[i * 3 + 1] = 0\n velocities[i * 3 + 2] = 0\n\n ages[i * 2] = 0 // Age\n // Lifetime, initial random value to stop \"bursting\"\n ages[i * 2 + 1] = Math.random() * 3\n\n props[i * 4] = 1.0 // Size\n props[i * 4 + 1] = 0 // Rotation speed\n props[i * 4 + 2] = 0 // Unused\n props[i * 4 + 3] = 0 // Unused\n\n seeds[i] = Math.random()\n }\n\n // Create input buffer used by transform feedback & update shader\n // Note the divisor of 0, this means the data is static and will not change\n this.inputBuffInfo = twgl.createBufferInfoFromArrays(gl, {\n position: { numComponents: 4, data: positions, divisor: 0 },\n velocity: { numComponents: 3, data: velocities, divisor: 0 },\n age: { numComponents: 2, data: ages, divisor: 0 },\n props: { numComponents: 4, data: props, divisor: 0 },\n seed: { numComponents: 1, data: seeds, divisor: 0 },\n })\n\n // Create output buffer used by transform feedback & update shader\n // Note the divisor of 1, this means the data is dynamic and will change\n const quadVerts = twgl.primitives.createXYQuadVertices(baseSize)\n // Mutate/merge the quadVerts object to add our custom attributes\n Object.assign(quadVerts, {\n tf_position: { numComponents: 4, data: positions, divisor: 1 },\n tf_velocity: { numComponents: 3, data: velocities, divisor: 1 },\n tf_age: { numComponents: 2, data: ages, divisor: 1 },\n tf_props: { numComponents: 4, data: props, divisor: 1 },\n })\n // Now create the buffer and VAO\n this.outputBuffInfo = twgl.createBufferInfoFromArrays(gl, quadVerts)\n\n this.outputVAO = twgl.createVertexArrayInfo(gl, this.progInfoRender, this.outputBuffInfo)\n\n // Create texture for particle\n this.texture = TextureCache.defaultWhite\n\n log.info('✨ Created particle system with', maxParticles, 'particles')\n }\n\n /**\n * Render the particle system and implement the renderable interface\n * @param gl WebGL2 rendering context\n * @param uniforms Uniforms to pass to the shaders\n */\n render(gl: WebGL2RenderingContext, uniforms: UniformSet) {\n if (this.duration == 0) {\n this.enabled = false\n }\n if (this.duration > 0) {\n this.duration--\n }\n\n gl.blendFunc(this.blendSource, this.blendDest)\n this.updateParticles(gl, uniforms.u_world as mat4)\n this.renderParticles(gl, uniforms)\n\n // Swap the buffers between input & output, kinda weird and ugly but it works!\n for (const attribName in this.inputBuffInfo.attribs) {\n const tempBuff = this.inputBuffInfo.attribs[attribName].buffer\n\n if (this.outputBuffInfo && this.outputBuffInfo.attribs && this.outputBuffInfo.attribs[`tf_${attribName}`]) {\n this.inputBuffInfo.attribs[attribName].buffer = this.outputBuffInfo.attribs[`tf_${attribName}`].buffer\n this.outputBuffInfo.attribs[`tf_${attribName}`].buffer = tempBuff\n }\n }\n }\n\n /**\n * Update the particles positions and velocities\n */\n private updateParticles(gl: WebGL2RenderingContext, worldTrans: mat4) {\n const tf = twgl.createTransformFeedback(gl, this.progInfoUpdate, this.outputBuffInfo)\n\n const pos = [0, 0, 0] as vec3\n if (!this.localSpace) {\n vec3.transformMat4(pos, pos, worldTrans)\n }\n\n gl.enable(gl.RASTERIZER_DISCARD)\n gl.useProgram(this.progInfoUpdate.program)\n\n twgl.setBuffersAndAttributes(gl, this.progInfoUpdate, this.inputBuffInfo)\n gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf)\n\n gl.beginTransformFeedback(gl.POINTS)\n\n twgl.setUniforms(this.progInfoUpdate, {\n u_time: Stats.totalTime,\n u_deltaTime: Stats.deltaTime * this.timeScale,\n u_randTex: TextureCache.defaultRand,\n\n // NOTE: ULTRA IMPORTANT! Without this the rand function in the shader will not work\n u_maxInstances: this.inputBuffInfo.numElements,\n\n u_enabled: this.enabled,\n u_lifetimeMinMax: [this.minLifetime, this.maxLifetime],\n u_gravity: this.gravity,\n u_powerMinMax: [this.minPower, this.maxPower],\n u_direction1: this.direction1,\n u_direction2: this.direction2,\n u_timeScale: this.timeScale,\n u_sizeMinMax: [this.minSize, this.maxSize],\n u_initialRotationMinMax: [this.minInitialRotation, this.maxInitialRotation],\n u_rotationSpeedMinMax: [this.minRotationSpeed, this.maxRotationSpeed],\n u_emitterBoxMin: this.emitterBoxMin,\n u_emitterBoxMax: this.emitterBoxMax,\n u_accel: this.acceleration,\n u_posOffset: pos,\n })\n\n twgl.drawBufferInfo(gl, this.inputBuffInfo, gl.POINTS, this.emitRate)\n\n gl.endTransformFeedback()\n gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null)\n gl.disable(gl.RASTERIZER_DISCARD)\n }\n\n /**\n * Render the particles to the world\n */\n private renderParticles(gl: WebGL2RenderingContext, uniforms: UniformSet) {\n gl.useProgram(this.progInfoRender.program)\n\n const particleUniforms = {\n ...uniforms,\n u_world: this.localSpace ? uniforms.u_world : emptyMat,\n u_texture: this.texture,\n u_ageColour: this.ageColour,\n u_preColour: this.preColour,\n u_agePower: this.agePower,\n }\n\n twgl.setUniforms(this.progInfoRender, particleUniforms)\n\n const objList = [\n {\n programInfo: this.progInfoRender,\n vertexArrayInfo: this.outputVAO,\n uniforms: particleUniforms,\n instanceCount: this.emitRate,\n },\n ]\n\n twgl.setBuffersAndAttributes(gl, this.progInfoRender, this.outputVAO)\n twgl.drawObjectList(gl, objList)\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Particle update fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// Does nothing, just here to make the WebGL compiler happy!\nvoid main() {}\n","#version 300 es\n\n// ============================================================================\n// Particle update vertex shader, for on GPU particle simulation\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position;\nin vec3 velocity;\nin vec2 age;\nin vec4 props;\nin float seed;\n\nuniform float u_deltaTime;\nuniform sampler2D u_randTex;\nuniform float u_maxInstances;\nuniform vec2 u_lifetimeMinMax;\nuniform vec2 u_powerMinMax;\nuniform vec3 u_gravity;\nuniform vec3 u_direction1;\nuniform vec3 u_direction2;\nuniform float u_timeScale;\nuniform vec2 u_sizeMinMax;\nuniform vec2 u_initialRotationMinMax;\nuniform vec2 u_rotationSpeedMinMax;\nuniform bool u_enabled;\nuniform vec3 u_emitterBoxMin;\nuniform vec3 u_emitterBoxMax;\nuniform float u_accel;\nuniform vec3 u_posOffset;\n\nout vec4 tf_position;\nout vec3 tf_velocity;\nout vec2 tf_age;\nout vec4 tf_props;\n\nvec4 rand(float offset) {\n float uv = float(gl_VertexID) / u_maxInstances + offset;\n return texture(u_randTex, vec2(uv)).rgba;\n}\n\nfloat randBetween(float min, float max, float offset) {\n vec4 r = rand(offset);\n return min + (max - min) * r.w;\n}\n\n// NOTES: TF varyings & packing\n// * position[0,1,2] = current position\n// * position[3] = rotation\n// * age[0] = current age\n// * age[1] = lifetime\n// * props[0] = size\n// * props[1] = rotation speed\n\nvoid main() {\n float t = u_deltaTime;\n float new_age = age[0] + t;\n\n float rot = position[3] + props[1] * t;\n\n tf_velocity = velocity * u_accel + u_gravity * t;\n tf_position = vec4(position.xyz + tf_velocity * t, rot);\n tf_age[0] = new_age;\n tf_age[1] = age[1];\n tf_props = props;\n\n // Dead particles are respawned\n if (new_age > age[1] && u_enabled) {\n vec4 r = rand(seed);\n\n tf_age[0] = 0.0;\n tf_position[0] = randBetween(u_emitterBoxMin.x, u_emitterBoxMax.x, r.x) + u_posOffset.x;\n tf_position[1] = randBetween(u_emitterBoxMin.y, u_emitterBoxMax.y, r.y) + u_posOffset.y;\n tf_position[2] = randBetween(u_emitterBoxMin.z, u_emitterBoxMax.z, r.z) + u_posOffset.z;\n tf_position[3] = randBetween(u_initialRotationMinMax.x, u_initialRotationMinMax.y, seed);\n\n float power = randBetween(u_powerMinMax.x, u_powerMinMax.y, 0.0);\n\n tf_velocity = vec3(\n randBetween(u_direction1.x, u_direction2.x, r.x + position.x) * power,\n randBetween(u_direction1.y, u_direction2.y, r.y + position.y) * power,\n randBetween(u_direction1.z, u_direction2.z, r.z + position.z) * power\n );\n\n tf_age[1] = randBetween(u_lifetimeMinMax.x, u_lifetimeMinMax.y, seed + position.x);\n tf_props[0] = randBetween(u_sizeMinMax.x, u_sizeMinMax.y, seed + position.y);\n tf_props[1] = randBetween(u_rotationSpeedMinMax.x, u_rotationSpeedMinMax.y, seed);\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Particle render fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec2 v_texcoord;\nin float v_ageNorm;\n\nuniform sampler2D u_texture;\nuniform vec4 u_ageColour;\nuniform vec4 u_preColour;\n\nout vec4 outColor;\n\nvoid main() {\n vec4 tex = texture(u_texture, v_texcoord);\n tex.r *= u_preColour.r;\n tex.g *= u_preColour.g;\n tex.b *= u_preColour.b;\n tex.a *= u_preColour.a;\n\n tex.a *= 1.0 - v_ageNorm * u_ageColour.a;\n tex.r *= 1.0 - v_ageNorm * u_ageColour.r;\n tex.g *= 1.0 - v_ageNorm * u_ageColour.g;\n tex.b *= 1.0 - v_ageNorm * u_ageColour.b;\n\n outColor = tex;\n}\n","#version 300 es\n\n// ============================================================================\n// Particle render vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nin vec4 position; // Vertex positions of the particle quad\nin vec2 texcoord;\nin vec4 tf_position; // Position of the particle\nin vec2 tf_age;\nin vec4 tf_props;\n\nuniform mat4 u_view;\nuniform mat4 u_proj;\nuniform mat4 u_world;\nuniform float u_agePower;\n\nout vec2 v_texcoord;\nout vec3 v_position;\nout float v_ageNorm;\n\nvoid main() {\n vec3 vert_pos = position.xyz;\n v_ageNorm = clamp(tf_age[0] / tf_age[1], 0.0, 1.0);\n v_ageNorm = pow(v_ageNorm, u_agePower);\n\n // Rotate by tf_position[3] (rotation)\n float s = sin(tf_position[3]);\n float c = cos(tf_position[3]);\n mat2 rot = mat2(c, -s, s, c);\n vert_pos.xy = rot * position.xy;\n\n // Scale by tf_props[0] (size)\n vert_pos = vert_pos.xyz * tf_props[0];\n\n // Move to the world at the particle position\n vec4 world_pos = u_world * vec4(tf_position.xyz, 1.0);\n vec4 view_pos = u_view * world_pos;\n\n // Billboarding magic\n gl_Position = u_proj * (view_pos + vec4(vert_pos.xy, 0.0, 0.0));\n\n v_position = world_pos.xyz;\n v_texcoord = texcoord;\n}\n","// ===== model.ts =============================================================\n// Main model class, holds a list of parts, each with a material\n// Models are parsed from OBJ files\n// Ben Coleman, 2023\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport log from 'loglevel'\n\nimport { Material } from '../engine/material.ts'\nimport { parseMTL } from '../parsers/mtl-parser.ts'\nimport { parseOBJ } from '../parsers/obj-parser.ts'\nimport { fetchFile } from '../core/files.ts'\nimport { getGl, UniformSet } from '../core/gl.ts'\nimport { Renderable } from './types.ts'\nimport { Stats } from '../core/stats.ts'\nimport { ProgramCache } from '../core/cache.ts'\n\n/**\n * Holds a 3D model, as a list of parts, each with a material\n * Plus map of named materials\n */\nexport class Model implements Renderable {\n private programInfo: twgl.ProgramInfo\n private readonly parts = [] as ModelPart[]\n private readonly materials = {} as Record\n private triangles: number\n private _boundingBox: number[]\n\n /** Name of the model, usually the filename without the extension */\n public readonly name: string\n\n /**\n * Constructor is private, use static `parse()` method instead\n */\n private constructor(name: string) {\n this.name = name\n this.triangles = 0\n this.programInfo = ProgramCache.instance.default\n this._boundingBox = [\n Number.MAX_VALUE,\n Number.MAX_VALUE,\n Number.MAX_VALUE,\n Number.MIN_VALUE,\n Number.MIN_VALUE,\n Number.MIN_VALUE,\n ]\n }\n\n /**\n * Render is used draw this model, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ): void {\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n // Render each part of the model\n for (const part of this.parts) {\n const bufferInfo = part.bufferInfo\n\n if (materialOverride === undefined) {\n // Get the named material for this part\n let material = this.materials[part.materialName]\n\n // Fall back to default material if not found\n if (!material) {\n material = this.materials.__default\n }\n\n material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, bufferInfo)\n Stats.drawCallsPerFrame++\n }\n }\n\n /** Simple getter for the number of triangles in the model */\n get triangleCount(): number {\n return this.triangles\n }\n\n /**\n * Parse an OBJ file & MTL material libraries, returns a new Model\n * @param {string} path - The path to the OBJ file\n * @param {string} objFilename - The name of the OBJ file\n * @param {boolean} filterTextures - Apply texture filtering to textures, default: true\n * @param {boolean} flipTextureY - Flip the Y axis of textures as they are loaded, default: false\n * @param {boolean} flipUV - Flip the UV coords of the model in the vertex/mesh data, default: true\n */\n static async parse(path = '.', objFilename: string, filterTextures = true, flipTextureY = false, flipUV = false) {\n const startTime = performance.now()\n\n // Create a new model with the name of the file\n const name = objFilename.split('.')[0]\n const model = new Model(name)\n\n // Load the OBJ file from URL\n let objFile: string\n try {\n objFile = await fetchFile(`${path}/${objFilename}`)\n } catch (err) {\n throw new Error(`💥 Unable to load file '${path}/${objFilename}'`)\n }\n\n // Try to parse the OBJ file\n const objData = parseOBJ(objFile, flipUV)\n\n if (!objData.geometries || objData.geometries.length === 0) {\n throw new Error(`💥 Error parsing '${objFilename}', might not be a OBJ file`)\n }\n\n // We assume that the OBJ file has a SINGLE material library\n // This is a good assumption for nearly all files I've seen\n if (objData.matLibNames && objData.matLibNames.length > 0) {\n try {\n const mtlFile = await fetchFile(`${path}/${objData.matLibNames[0]}`)\n const materialsRawList = parseMTL(mtlFile)\n\n for (const [matName, matRaw] of materialsRawList) {\n model.materials[matName] = Material.fromMtl(matRaw, path, filterTextures, flipTextureY)\n }\n } catch (err) {\n log.warn(`💥 Unable to load material library ${objData.matLibNames[0]}`)\n }\n }\n\n // Fall back default material\n model.materials.__default = new Material()\n model.materials.__default.diffuse = [0.1, 0.6, 0.9]\n\n // This really should already been memoized by the context at this point\n const gl = getGl()\n\n if (!gl) {\n throw new Error('💥 Unable to get WebGL context')\n }\n\n for (const g of objData.geometries) {\n // Calculate bounding box\n for (let i = 0; i < g.data.position.length; i += 3) {\n const x = g.data.position[i]\n const y = g.data.position[i + 1]\n const z = g.data.position[i + 2]\n if (x < model._boundingBox[0]) model._boundingBox[0] = x\n if (y < model._boundingBox[1]) model._boundingBox[1] = y\n if (z < model._boundingBox[2]) model._boundingBox[2] = z\n if (x > model._boundingBox[3]) model._boundingBox[3] = x\n if (y > model._boundingBox[4]) model._boundingBox[4] = y\n if (z > model._boundingBox[5]) model._boundingBox[5] = z\n }\n\n log.info(`♟️ Model '${objFilename}' part '${g.material}'`)\n\n // TODO: One day add tangent generation\n const bufferInfo = twgl.createBufferInfoFromArrays(gl, g.data)\n model.parts.push(new ModelPart(bufferInfo, g.material))\n }\n\n log.debug(\n `♟️ Model '${objFilename}' loaded with ${model.parts.length} parts, ${\n Object.keys(model.materials).length\n } materials in ${((performance.now() - startTime) / 1000).toFixed(2)}s`,\n )\n\n model.triangles = objData.triangles\n return model\n }\n\n /**\n * Get list of all material names in this model used by all parts\n * @returns {string[]} - List of material names\n */\n get materialNames(): string[] {\n return Object.keys(this.materials)\n }\n\n /**\n * Get number of parts in this model\n */\n get partsCount(): number {\n return this.parts.length\n }\n\n /**\n * Get list of parts in this model, names are the material names\n * @returns {string[]} - List of part material names\n */\n get partList(): string[] {\n return this.parts.map((p) => p.materialName)\n }\n\n /**\n * Can modify & override an existing named material\n * @param {string} name - Name of the material to modify\n * @param {Material} material - New material to use\n */\n setNamedMaterial(name: string, material: Material): void {\n this.materials[name] = material\n }\n\n /**\n * Get a named material\n * @param {string} name - Name of the material to get\n */\n getNamedMaterial(name: string): Material {\n return this.materials[name]\n }\n\n public get boundingBox(): number[] {\n return this._boundingBox\n }\n}\n\n/**\n * Holds part of a model, as the WebGL buffers needed to render it\n * Plus the material name associated with this part\n */\nexport class ModelPart {\n public readonly bufferInfo: twgl.BufferInfo\n public readonly materialName: string\n\n /**\n * @param {twgl.BufferInfo} bufferInfo - WebGL buffer info for this model part\n * @param {string} materialName - Name of the material associated with this part\n */\n constructor(bufferInfo: twgl.BufferInfo, materialName: string) {\n this.bufferInfo = bufferInfo\n this.materialName = materialName\n }\n}\n","// ===== mtl-parser.mjs ==========================================================\n// A simple MTL parser\n// Taken from https://webglfundamentals.org/webgl/lessons/webgl-load-obj-w-mtl.html\n// Ben Coleman, 2023\n// ===============================================================================\n\n/**\n * A \"raw\" material fetched from the MTL parser, don't use this directly\n */\nexport type MtlMaterial = {\n illum?: number\n\n ns?: number\n d?: number\n\n ka?: [number, number, number]\n kd?: [number, number, number]\n ks?: [number, number, number]\n ke?: [number, number, number]\n\n texDiffuse?: string\n texSpecular?: string\n texNormal?: string\n}\n\n/**\n * Parse an MTL file returning a map of materials.\n * The returned {@link typescript!MtlMaterial} should be passed to new Material() to create a material\n * @param {string} mtlFile - The MTL file as a string\n * @returns {Map} - A map of materials\n */\nexport function parseMTL(mtlFile: string): Map {\n const materials = new Map()\n let material = {} as MtlMaterial\n\n const keywords = {\n newmtl(_: string[], unparsedArgs: string) {\n material = {} as MtlMaterial\n materials.set(unparsedArgs, material)\n },\n\n Ns(parts: string[]) {\n material.ns = parseFloat(parts[0])\n },\n Ka(parts: string[]) {\n material.ka = <[number, number, number]>parts.map(parseFloat)\n },\n Kd(parts: string[]) {\n material.kd = <[number, number, number]>parts.map(parseFloat)\n },\n Ks(parts: string[]) {\n material.ks = <[number, number, number]>parts.map(parseFloat)\n },\n // This is a non-standard addition, but semi-official\n Ke(parts: string[]) {\n material.ke = <[number, number, number]>parts.map(parseFloat)\n },\n Ni() {\n // Not used\n // Material.ni = parseFloat(parts[0])\n },\n d(parts: string[]) {\n material.d = parseFloat(parts[0])\n },\n illum(parts: string[]) {\n material.illum = parseInt(parts[0])\n },\n map_Kd(_: string[], unparsedArgs: string) {\n material.texDiffuse = unparsedArgs\n },\n map_Ks(_: string[], unparsedArgs: string) {\n material.texSpecular = unparsedArgs\n },\n map_bump(_: string[], unparsedArgs: string) {\n material.texNormal = unparsedArgs\n },\n map_Bump(_: string[], unparsedArgs: string) {\n material.texNormal = unparsedArgs\n },\n } as Record void>\n\n const keywordRE = /(\\w*)(?: )*(.*)/\n const lines = mtlFile.split('\\n')\n\n for (let lineNo = 0; lineNo < lines.length; ++lineNo) {\n const line = lines[lineNo].trim()\n if (line === '' || line.startsWith('#')) {\n continue\n }\n\n const m = keywordRE.exec(line)\n if (!m) {\n continue\n }\n\n const [, keyword, unparsedArgs] = m\n const parts = line.split(/\\s+/).slice(1)\n\n const handler = keywords[keyword]\n if (!handler) {\n // Console.warn('unhandled keyword:', keyword)\n continue\n }\n\n handler(parts, unparsedArgs)\n }\n\n return materials\n}\n","// ===== obj-parser.mjs ==========================================================\n// A simple OBJ parser, works well, but FAR from comprehensive\n// Taken from https://webglfundamentals.org/webgl/lessons/webgl-obj-loader.html\n// Ben Coleman, 2023\n// ===============================================================================\n\nconst keywordRE = /(\\w*)(?: )*(.*)/\n\n/**\n * ParseResult is the result of parsing an OBJ file\n */\nexport type ParseResult = {\n /** List of material libs (MTL files) */\n matLibNames: string[]\n\n /** List of geometries, each with a material name and vertex data */\n geometries: Geometry[]\n\n /** Total number of triangles in the OBJ file */\n triangles: number\n}\n\n/**\n * Each OBJ file is made up of a list of geometries, each with a material name.\n * These can be thought of as parts of the overall model.\n */\nexport type Geometry = {\n /** Name of the material for this geometry part */\n material: string\n\n /** Vertex data for this geometry part, ready for turning into an BufferInfo in twgl.js */\n data: {\n position: number[]\n texcoord?: number[]\n normal: number[]\n tangent?: number[]\n }\n}\n\n/**\n * Parse an OBJ file returning a list of geometries and materials libs\n * @param {string} objFile - The OBJ file as a string\n * @param {boolean} flipUV - Flip the V texcoord axis, for OpenGL\n */\nexport function parseOBJ(objFile: string, flipUV: boolean) {\n const lines = objFile.split('\\n')\n\n const objPositions = [[0, 0, 0]]\n const objTexcoords = [[0, 0]]\n const objNormals = [[0, 0, 0]]\n\n // Same order as `f` indices\n const objVertexData = [objPositions, objTexcoords, objNormals]\n\n let triangles = 0\n\n // Same order as `f` indices\n let webglVertexData = [\n [], // Position\n [], // Texcoord\n [], // Normal\n ] as number[][]\n\n const geometries = Array()\n let geometry = {} as Geometry\n let material = '__default'\n const materialLibs = Array()\n\n const keywords = {\n v(parts: string[]) {\n objPositions.push(parts.map(parseFloat))\n },\n\n vn(parts: string[]) {\n objNormals.push(parts.map(parseFloat))\n },\n\n vt(parts: string[]) {\n // Only 2D texcoords supported, so ignore the 3rd if present\n // Also handle UV flip in the V direction (Y axis) for OpenGL\n if (flipUV) {\n objTexcoords.push([parseFloat(parts[0]), 1.0 - parseFloat(parts[1])])\n } else {\n objTexcoords.push([parseFloat(parts[0]), parseFloat(parts[1])])\n }\n },\n\n f(parts: string[]) {\n triangles++\n setGeometry()\n const numTriangles = parts.length - 2\n for (let tri = 0; tri < numTriangles; ++tri) {\n addVertex(parts[0])\n addVertex(parts[tri + 1])\n addVertex(parts[tri + 2])\n }\n },\n\n usemtl(_: string[], unparsedArgs: string) {\n material = unparsedArgs\n newGeometry()\n },\n\n mtllib(_: string[], unparsedArgs: string) {\n materialLibs.push(unparsedArgs)\n },\n\n // Not used, but suppress warnings\n s() {\n return\n },\n\n o() {\n return\n },\n\n g() {\n return\n },\n\n l() {\n return\n },\n } as Record void>\n\n /**\n * Updates webglVertexData per vertex\n * @param {string} vert - String in the form of \"v/vt/vn\" as per OBJ spec\n */\n function addVertex(vert: string) {\n const ptn = vert.split('/')\n\n ptn.forEach((objIndexStr, i) => {\n if (!objIndexStr) {\n return\n }\n\n const objIndex = parseInt(objIndexStr)\n const index = objIndex + (objIndex >= 0 ? 0 : objVertexData[i].length)\n\n webglVertexData[i].push(...objVertexData[i][index])\n })\n }\n\n /**\n * Start a new geometry object\n */\n function newGeometry() {\n // If there is an existing geometry and it's not empty then start a new one.\n if (geometry.material) {\n geometry = {} as Geometry\n }\n }\n\n /**\n * Set the geometry for the current material/part\n */\n function setGeometry() {\n if (!geometry.material) {\n const position = [] as number[]\n const texcoord = [] as number[]\n const normal = [] as number[]\n\n webglVertexData = [position, texcoord, normal]\n\n /** @type {Geometry} */\n geometry = {\n material,\n data: {\n position,\n texcoord,\n normal,\n },\n }\n\n geometries.push(geometry)\n }\n }\n\n // Parse the OBJ file line by line\n for (let lineNo = 0; lineNo < lines.length; ++lineNo) {\n const line = lines[lineNo].trim()\n if (line === '' || line.startsWith('#')) {\n continue\n }\n\n const m = keywordRE.exec(line)\n if (!m) {\n continue\n }\n\n const [, keyword, unparsedArgs] = m\n const parts = line.split(/\\s+/).slice(1)\n\n const handler = keywords[keyword]\n if (!handler) {\n console.warn('unhandled keyword:', keyword, 'at line', lineNo + 1)\n continue\n }\n\n handler(parts, unparsedArgs)\n }\n\n // FIX: For those OBJ files that don't have texcoord data\n for (const g of geometries) {\n if (g.data.texcoord && g.data.texcoord.length <= 0) {\n delete g.data.texcoord\n }\n }\n\n // Return the list of geometries and material libs, plus triangle count\n return {\n matLibNames: materialLibs,\n geometries,\n triangles,\n } as ParseResult\n}\n","// ===== files.ts =============================================================\n// File loading utilities\n// Ben Coleman, 2023\n// ============================================================================\n\ntype Shader = {\n vertex: string\n fragment: string\n}\n\n/**\n * Fetch a file from the server\n *\n * @param {string} path - URL path to file\n * @returns {Promise} File contents as a string\n */\nexport async function fetchFile(filePath: string) {\n const resp = await fetch(filePath)\n\n if (!resp.ok) {\n throw new Error(`💥 File fetch failed: ${resp.statusText}`)\n }\n\n const text = await resp.text()\n return text\n}\n\n/**\n * Fetch a pair of shaders from the server\n *\n * @param {string} vertPath - URL path to vertex shader\n * @param {string} fragPath - URL path to fragment shader\n * @returns {Promise} Pair of shaders as strings\n */\nexport async function fetchShaders(vertPath: string, fragPath: string) {\n const vsResp = await fetch(vertPath)\n const fsResp = await fetch(fragPath)\n\n if (!vsResp.ok || !fsResp.ok) {\n throw new Error(`💥 Fetch failed - vertex: ${vsResp.statusText}, fragment: ${fsResp.statusText}`)\n }\n\n const vsText = await vsResp.text()\n const fsText = await fsResp.text()\n\n return { vertex: vsText, fragment: fsText } as Shader\n}\n","// ===== hud.ts =========================================================\n// A HTML based HUD for the game, this is a simple div for now\n// Ben Coleman, 2023\n// ======================================================================\n\nimport { Stats } from './stats.ts'\nimport { version } from '../../package.json'\nimport { Camera } from '../engine/camera.ts'\n\nexport class HUD {\n private hud: HTMLDivElement\n private canvas: HTMLCanvasElement\n private debugDiv: HTMLDivElement\n private loadingDiv: HTMLDivElement\n public debug = false\n\n constructor(canvas: HTMLCanvasElement) {\n const parent = canvas.parentElement\n if (!parent) throw new Error('💥 Canvas must have a parent element')\n\n this.canvas = canvas\n\n this.hud = document.createElement('div')\n this.hud.classList.add('gsots3d-hud')\n this.hud.style.pointerEvents = 'none'\n\n this.updateWithCanvas = this.updateWithCanvas.bind(this)\n window.addEventListener('resize', this.updateWithCanvas)\n window.addEventListener('load', this.updateWithCanvas)\n\n this.debugDiv = document.createElement('div')\n this.debugDiv.classList.add('gsots3d-debug')\n this.debugDiv.style.fontSize = 'min(1.5vw, 20px)'\n this.debugDiv.style.fontFamily = 'monospace'\n this.debugDiv.style.color = 'white'\n this.debugDiv.style.padding = '1vw'\n this.addHUDItem(this.debugDiv)\n\n this.loadingDiv = document.createElement('div')\n this.loadingDiv.classList.add('gsots3d-loading')\n this.loadingDiv.innerHTML = `💾 Loading...

GSOTS-3D v${version}
`\n this.loadingDiv.style.font = 'normal 3vw sans-serif'\n this.loadingDiv.style.color = '#ccc'\n this.loadingDiv.style.position = 'absolute'\n this.loadingDiv.style.top = '50%'\n this.loadingDiv.style.left = '50%'\n this.loadingDiv.style.textAlign = 'center'\n this.loadingDiv.style.transform = 'translate(-50%, -50%)'\n this.addHUDItem(this.loadingDiv)\n\n parent.appendChild(this.hud)\n this.updateWithCanvas()\n }\n\n /**\n * Update the HUD position and size to match the canvas\n */\n private updateWithCanvas() {\n const canvasStyles = window.getComputedStyle(this.canvas, null)\n this.hud.style.position = canvasStyles.getPropertyValue('position')\n this.hud.style.top = canvasStyles.getPropertyValue('top')\n this.hud.style.left = canvasStyles.getPropertyValue('left')\n this.hud.style.width = canvasStyles.getPropertyValue('width')\n this.hud.style.height = canvasStyles.getPropertyValue('height')\n this.hud.style.transform = canvasStyles.getPropertyValue('transform')\n }\n\n /**\n * Add a HTML element to the HUD\n * @param item HTML element to add\n */\n addHUDItem(item: HTMLElement) {\n this.hud.appendChild(item)\n }\n\n /**\n * Render the HUD, called once per frame\n */\n render(debug = false, camera: Camera) {\n // Draw the debug HUD\n if (debug) {\n this.debugDiv.innerHTML = `\n GSOTS-3D v${version}

\n Camera: ${camera.toString()}
\n Instances: ${Stats.instances}
\n Draw calls: ${Stats.drawCallsPerFrame}
\n Triangles: ${Stats.triangles}
\n Render: FPS: ${Stats.FPS} / ${Stats.totalTimeRound}s
\n `\n } else {\n this.debugDiv.innerHTML = ''\n }\n }\n\n /**\n * Hide the loading message, this is called by the engine\n */\n hideLoading() {\n this.loadingDiv.style.display = 'none'\n }\n}\n","// ===== post-effects.ts ===============================================================================\n// Full screen effects and post processing\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport * as log from 'loglevel'\nimport * as twgl from 'twgl.js'\nimport { UniformSet } from '../core/gl.ts'\nimport { TextureCache } from '../core/cache.ts'\nimport { Stats } from '../core/stats.ts'\nimport { RGB } from './tuples.ts'\n\n/**\n * PostEffects class, used to render full screen effects via post processing\n * This is a wrapper around a shader program that renders from a framebuffer to the screen\n */\nexport class PostEffects {\n private _frameBuff: twgl.FramebufferInfo\n private buffInfo: twgl.BufferInfo\n private uniforms: UniformSet\n private progInfo: twgl.ProgramInfo\n\n constructor(gl: WebGL2RenderingContext, shaderCode: string) {\n // Create a framebuffer to hold image for this post effects to process\n this._frameBuff = twgl.createFramebufferInfo(gl, undefined, gl.canvas.width, gl.canvas.height)\n\n // Simple 2-triangle quad for a shader to render to the whole screen\n this.buffInfo = twgl.createBufferInfoFromArrays(gl, {\n position: {\n numComponents: 2,\n data: [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1],\n },\n texcoord: {\n numComponents: 2,\n data: [0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],\n },\n })\n\n this.uniforms = {\n image: this._frameBuff.attachments[0],\n width: gl.canvas.width,\n height: gl.canvas.height,\n time: Stats.totalTime,\n delta: Stats.deltaTime,\n randTex: TextureCache.defaultRand,\n }\n\n // Note. We don't follow the naming convention from the other shaders here\n // to allow the user to write their own shaders and keep them simple\n const vertShader = `#version 300 es\n precision highp float;\n in vec4 position;\n in vec2 texcoord;\n out vec2 pos;\n void main() {\n pos = texcoord;\n gl_Position = position;\n }`\n\n const fragShader = `#version 300 es\n precision highp float;\n in vec2 pos;\n uniform sampler2D image;\n uniform float width;\n uniform float height;\n uniform float time;\n uniform float frame;\n uniform float delta;\n uniform sampler2D randTex;\n out vec4 pixel;\n \n vec4 randRGBA(float offset) {\n vec2 uv = vec2(pos.x + offset, pos.y + offset + 0.1);\n return texture(randTex, vec2(uv)).rgba;\n }\n \n float randPhase(vec2 co, float speed)\n {\n float a = 12.9898;\n float b = 78.233;\n float c = 43758.5453;\n float dt = dot(co.xy, vec2(a,b));\n float sn = mod(dt, 3.14159);\n\n return fract((sin(sn) * c) + time * speed);\n }\n\n float randF(vec2 st) {\n return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);\n } \n\n ${shaderCode}\n `\n\n log.debug(`🥽 PostEffects creating shader program\\n${fragShader}`)\n this.progInfo = twgl.createProgramInfo(gl, [vertShader, fragShader])\n }\n\n /**\n * Render the post effects to the screen, called last in the render loop\n * @param gl WebGL2RenderingContext\n */\n renderToScreen(gl: WebGL2RenderingContext) {\n gl.useProgram(this.progInfo.program)\n\n this.uniforms.time = Stats.totalTime\n this.uniforms.delta = Stats.deltaTime\n this.uniforms.frame = Stats.frameCount\n\n twgl.setUniforms(this.progInfo, this.uniforms)\n twgl.setBuffersAndAttributes(gl, this.progInfo, this.buffInfo)\n\n twgl.bindFramebufferInfo(gl, null)\n twgl.drawBufferInfo(gl, this.buffInfo)\n }\n\n /**\n * Get the framebuffer that this post effects is rendering to\n * Used to update the image that the post effects will update\n */\n get frameBuffer() {\n return this._frameBuff\n }\n\n /**\n * Create a simple scanlines effect with noise and flickering\n * Taken from https://www.shadertoy.com/view/3dBSRD\n * @param gl WebGL2RenderingContext\n * @param density Density of scanlines, 0.0 - 1.0\n * @param opacity Opacity of scanlines, 0.0 - 1.0\n * @param noise Amount of noise, 0.0 - 1.0\n * @param flicker Amount of flickering, 0.0 - 1.0\n */\n static scanlines(gl: WebGL2RenderingContext, density: number, opacity: number, noise: number, flicker: number) {\n const shader = `\n float density = ${density.toFixed(3)};\n float opacityScanline = ${opacity.toFixed(3)};\n float opacityNoise = ${noise.toFixed(3)};\n float flickering = ${flicker.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n \n float count = height * density;\n vec2 sl = vec2(sin(pos.y * count), cos(pos.y * count));\n vec3 scanlines = vec3(sl.x, sl.y, sl.x);\n \n col += col * scanlines * opacityScanline;\n col += col * vec3(randF(pos * time)) * opacityNoise;\n col += col * sin(110.0 * time) * flickering;\n \n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a glitch effect with horizontal lines\n * @param gl WebGL2RenderingContext\n * @param amount Amount of glitch, 0.0 - 1.0\n */\n static glitch(gl: WebGL2RenderingContext, amount: number) {\n const shader = `\n float amount = ${amount.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n\n float offset = randF(vec2(time, pos.y)) * amount;\n\n col.r = texture(image, vec2(pos.x + offset, pos.y)).r;\n col.g = texture(image, vec2(pos.x - offset, pos.y)).g;\n col.b = texture(image, vec2(pos.x + offset, pos.y)).b;\n\n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create duotone effect with two colours and contrast\n * @param gl WebGL2RenderingContext\n */\n static duotone(gl: WebGL2RenderingContext, colour1: RGB, colour2: RGB, contrast: number) {\n const shader = ` \n vec3 col1 = vec3(${colour1[0].toFixed(3)}, ${colour1[1].toFixed(3)}, ${colour1[2].toFixed(3)});\n vec3 col2 = vec3(${colour2[0].toFixed(3)}, ${colour2[1].toFixed(3)}, ${colour2[2].toFixed(3)});\n float contrast = ${contrast.toFixed(3)};\n\n void main() {\n vec3 col = texture(image, pos).rgb;\n\n vec3 lumFactor = vec3(0.2126, 0.7152, 0.0722);\n vec3 desat = vec3(dot(col, lumFactor));\n\n // increase contrast\n desat = pow(desat, vec3(contrast));\n desat *= contrast;\n \n pixel = vec4(mix(col1, col2, desat), 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a noise effect\n * @param gl WebGL2RenderingContext\n * @param amount Amount of noise, 0.0 - 1.0\n * @param speed Speed of noise change\n */\n static noise(gl: WebGL2RenderingContext, amount: number, speed: number) {\n const shader = `\n float amount = ${amount.toFixed(3)};\n float speed = ${speed.toFixed(3)};\n \n void main() {\n vec3 col = texture(image, pos).rgb;\n \n col.r += randPhase(pos, speed) * amount;\n col.g += randPhase(pos - 0.1, speed) * amount;\n col.b += randPhase(pos + 0.1, speed) * amount;\n \n //col += rand(8.0 * time).rgb * amount;\n\n pixel = vec4(col, 1.0);\n }`\n\n return new PostEffects(gl, shader)\n }\n\n /**\n * Create a two colour contrast threshold effect\n * @param gl WebGL2RenderingContext\n * @param threshold Threshold value, 0.0 - 1.0\n * @param colourDark Dark colour\n * @param colourBright Bright colour\n */\n static contrast(gl: WebGL2RenderingContext, threshold: number, colourDark: RGB, colourBright: RGB) {\n const shader = `\n float threshold = ${threshold.toFixed(3)};\n vec3 bright = vec3(${colourBright[0].toFixed(3)}, ${colourBright[1].toFixed(3)}, ${colourBright[2].toFixed(3)});\n vec3 dark = vec3(${colourDark[0].toFixed(3)}, ${colourDark[1].toFixed(3)}, ${colourDark[2].toFixed(3)});\n\n void main() {\n vec3 col = texture(image, pos).rgb;\n\n float brightness = (col.r + col.g + col.b) / 3.0;\n brightness = clamp(brightness, 0.0, 1.0);\n\n if (brightness > threshold) {\n pixel = vec4(bright, 1.0);\n } else {\n pixel = vec4(dark, 1.0);\n }\n }`\n\n return new PostEffects(gl, shader)\n }\n}\n","#version 300 es\n\n// ============================================================================\n// Phong fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// ===== Constants ============================================================\n\nconst int MAX_LIGHTS = 16;\nconst int MAX_SHADOWS = 8;\nconst float MAX_SHAD_A = 0.125;\n\n// Got this from http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/#poisson-sampling\nvec3 poissonDisk[8] = vec3[](\n vec3(-0.94201624, -0.39906216, -0.4684316),\n vec3(0.94558609, -0.76890725, -0.34478877),\n vec3(-0.094184101, -0.9293887, -0.3048823),\n vec3(0.34495938, 0.2938776, -0.001735733),\n vec3(-0.91588581, 0.45771432, -0.087759815),\n vec3(-0.81544232, -0.87912464, -0.03352997),\n vec3(-0.38277543, 0.27676845, -0.9485365),\n vec3(-0.58723171, -0.73007023, -0.22162315)\n);\n\n// ===== Structs ==============================================================\n\nstruct LightDir {\n vec3 direction;\n vec3 colour;\n vec3 ambient;\n};\n\nstruct LightPos {\n vec3 position;\n vec3 colour;\n vec3 ambient;\n float constant;\n float linear;\n float quad;\n bool enabled;\n};\n\nstruct Material {\n vec3 ambient;\n vec3 diffuse;\n vec3 specular;\n vec3 emissive;\n float shininess;\n float opacity;\n float reflectivity;\n sampler2D diffuseTex;\n sampler2D specularTex;\n sampler2D normalTex;\n bool hasNormalTex;\n bool unshaded;\n};\n\n// Inputs from vertex shader\nin vec3 v_normal;\nin vec2 v_texCoord;\nin vec4 v_position;\nin vec4 v_shadowCoord;\n\n// Some global uniforms\nuniform vec3 u_camPos;\nuniform float u_gamma;\nuniform bool u_flipTextureX;\nuniform bool u_flipTextureY;\n\n// Main lights and material uniforms\nuniform Material u_mat;\nuniform LightDir u_lightDirGlobal;\nuniform LightPos u_lightsPos[MAX_LIGHTS];\nuniform int u_lightsPosCount;\n// Reflection map isn't part of the material struct for complex reasons\nuniform samplerCube u_reflectionMap;\n// Shadows\nuniform highp sampler2DShadow u_shadowMap;\n// uniform float u_shadowScatter; // REMOVED FOR NOW\nuniform bool u_receiveShadow;\n\n// Global texture coords shared between functions\nvec2 texCoord;\n\n// Output colour of this pixel/fragment\nout vec4 outColour;\n\n// ===== Helper functions =====================================================\n\n// Simple mixer\nvec4 mix4(vec4 a, vec4 b, float mix) {\n return a * (1.0 - mix) + b * mix;\n}\n\n// Function to help with get values from the shadow map\nfloat shadowMapSample(highp sampler2DShadow map, vec3 coord) {\n // As WebGL 2 does not support GL_CLAMP_TO_BORDER or GL_TEXTURE_BORDER_COLOR, we need to do this :(\n if (coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0) {\n return 1.0;\n }\n\n return texture(map, coord);\n}\n\n// Shade a fragment using a directional light source\nvec4 shadeDirLight(LightDir light, Material mat, vec3 N, vec3 V) {\n vec3 L = normalize(-light.direction);\n vec3 H = normalize(L + V);\n\n vec3 diffuseCol = vec3(texture(mat.diffuseTex, texCoord)) * mat.diffuse;\n vec3 specularCol = vec3(texture(mat.specularTex, texCoord)) * mat.specular;\n\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), mat.shininess) : 0.0;\n\n // Shadow map lookup\n vec3 projCoords = v_shadowCoord.xyz / v_shadowCoord.w * 0.5 + 0.5;\n\n // REMOVED FOR NOW - PCF for shadows using 8 samples of a poisson disk\n // float shadow = u_receiveShadow ? 0.0 : 1.0;\n // float scatter = u_shadowScatter / 100.0;\n // for (int i = u_receiveShadow ? 0 : MAX_SHADOWS; i < MAX_SHADOWS; i++) {\n // vec3 offset = poissonDisk[i] * scatter;\n // shadow += shadowMapSample(u_shadowMap, projCoords + offset) * MAX_SHAD_A;\n // }\n\n float shadow = u_receiveShadow ? shadowMapSample(u_shadowMap, projCoords) : 1.0;\n\n vec3 ambient = light.ambient * mat.ambient * diffuseCol;\n vec3 diffuse = light.colour * max(diff, 0.0) * diffuseCol * shadow;\n vec3 specular = light.colour * spec * specularCol * shadow;\n\n // Return a vec4 to support transparency, note specular is not affected by opacity\n return vec4(ambient + diffuse, mat.opacity / float(u_lightsPosCount + 1)) + vec4(specular, spec);\n}\n\n// Shade a fragment using a positional light source\nvec4 shadePosLight(LightPos light, Material mat, vec3 N, vec3 V) {\n vec3 L = normalize(light.position - v_position.xyz);\n vec3 H = normalize(L + V);\n\n vec3 diffuseCol = vec3(texture(mat.diffuseTex, texCoord)) * mat.diffuse;\n vec3 specularCol = vec3(texture(mat.specularTex, texCoord)) * mat.specular;\n\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), mat.shininess) : 0.0;\n\n // Light attenuation, see: https://learnopengl.com/Lighting/Light-casters\n float dist = length(light.position - v_position.xyz);\n float attenuation = 1.0 / (light.constant + light.linear * dist + light.quad * (dist * dist));\n\n vec3 ambient = light.ambient * mat.ambient * diffuseCol * attenuation;\n vec3 diffuse = light.colour * max(diff, 0.0) * diffuseCol * attenuation;\n vec3 specular = light.colour * spec * specularCol * attenuation;\n\n // Return a vec4 to support transparency, note specular is not affected by opacity\n return vec4(ambient + diffuse, mat.opacity / float(u_lightsPosCount + 1)) + vec4(specular, spec);\n}\n\n// ===== Main shader ==========================================================\n\nvoid main() {\n vec3 V = normalize(u_camPos - v_position.xyz);\n\n // Flip texture coords if needed\n texCoord = u_flipTextureY ? vec2(v_texCoord.x, 1.0 - v_texCoord.y) : v_texCoord;\n texCoord = u_flipTextureX ? vec2(1.0 - texCoord.x, texCoord.y) : texCoord;\n\n vec3 N = normalize(v_normal);\n\n // Normal mapping, this is expensive so only do it if we have a normal map\n if (u_mat.hasNormalTex) {\n vec3 normMap = texture(u_mat.normalTex, texCoord).xyz * 2.0 - 1.0;\n\n vec3 Q1 = dFdx(v_position.xyz);\n vec3 Q2 = dFdy(v_position.xyz);\n vec2 st1 = dFdx(texCoord);\n vec2 st2 = dFdy(texCoord);\n\n vec3 T = -normalize(Q1 * st2.t - Q2 * st1.t);\n vec3 B = normalize(cross(N, T));\n mat3 TBN = mat3(T, B, N);\n\n N = normalize(TBN * normMap);\n }\n\n vec4 outColorPart;\n if (u_mat.unshaded) {\n // Skip lighting/shading and just use the texture if unshaded\n vec3 diffuseTexCol = vec3(texture(u_mat.diffuseTex, texCoord)) * u_mat.diffuse;\n outColorPart = vec4(diffuseTexCol, 1.0);\n } else {\n // Handle the main directional light, only one of these\n outColorPart = shadeDirLight(u_lightDirGlobal, u_mat, N, V);\n\n // Add positional lights\n for (int i = 0; i < u_lightsPosCount; i++) {\n outColorPart += shadePosLight(u_lightsPos[i], u_mat, N, V);\n }\n }\n\n // Add emissive component\n float emissiveAlpha = u_mat.emissive.r + u_mat.emissive.g + u_mat.emissive.b > 0.0 ? 1.0 : 0.0;\n outColorPart += vec4(u_mat.emissive, emissiveAlpha);\n\n // Get reflection vector and sample reflection texture\n vec3 R = reflect(-V, N);\n vec4 reflectCol = vec4(texture(u_reflectionMap, R).rgb, 1.0);\n\n // Add reflection component, not sure if this is correct, looks ok\n outColorPart = mix4(outColorPart, reflectCol, u_mat.reflectivity);\n\n // Gamma correction, as GL_FRAMEBUFFER_SRGB is not supported on WebGL\n outColorPart.rgb = pow(outColorPart.rgb, vec3(1.0 / u_gamma));\n\n outColour = outColorPart;\n}\n","#version 300 es\n\n// ============================================================================\n// Phong vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\n// Input attributes from buffers\nin vec4 position;\nin vec3 normal;\nin vec2 texcoord;\n\nuniform mat4 u_worldViewProjection;\nuniform mat4 u_worldInverseTranspose;\nuniform mat4 u_world;\nuniform mat4 u_shadowMatrix;\n\n// Output varying's to pass to fragment shader\nout vec2 v_texCoord;\nout vec3 v_normal;\nout vec4 v_position;\nout vec4 v_shadowCoord;\n\nvoid main() {\n v_texCoord = texcoord;\n v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;\n v_position = u_world * position;\n v_shadowCoord = u_shadowMatrix * v_position;\n\n gl_Position = u_worldViewProjection * position;\n}\n","#version 300 es\n\n// ============================================================================\n// Billboard fragment shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nstruct Material {\n vec3 ambient;\n vec3 diffuse;\n vec3 specular;\n vec3 emissive;\n float shininess;\n float opacity;\n float reflectivity;\n sampler2D diffuseTex;\n sampler2D specularTex;\n sampler2D normalTex;\n bool hasNormalTex;\n};\n\n// From vertex shader\nin vec2 v_texCoord;\nin vec3 v_lighting;\n\n// Main lights and material uniforms\nuniform Material u_mat;\nuniform float u_gamma;\n\n// Output colour of this pixel/fragment\nout vec4 outColour;\n\nvoid main() {\n vec4 texel = texture(u_mat.diffuseTex, v_texCoord);\n\n // Magic to make transparent sprites work, without blending\n // Somehow this also works with the shadow map render pass, which is a bonus\n if (texel.a < 0.75) {\n discard;\n }\n\n vec3 colour = texel.rgb * u_mat.diffuse * v_lighting;\n\n // Gamma correction, as GL_FRAMEBUFFER_SRGB is not supported on WebGL\n colour = pow(colour, vec3(1.0 / u_gamma));\n\n outColour = vec4(colour, u_mat.opacity);\n}\n","#version 300 es\n\n// ============================================================================\n// Billboard vertex shader\n// Ben Coleman, 2023\n// ============================================================================\n\nprecision highp float;\n\nconst int MAX_LIGHTS = 16;\n\nstruct LightDir {\n vec3 direction;\n vec3 colour;\n vec3 ambient;\n};\n\nstruct LightPos {\n vec3 position;\n vec3 colour;\n vec3 ambient;\n float constant;\n float linear;\n float quad;\n bool enabled;\n};\n\n// Input attributes from buffers\nin vec4 position;\nin vec2 texcoord;\n\nuniform mat4 u_worldViewProjection;\nuniform mat4 u_world;\nuniform int u_lightsPosCount;\nuniform vec3 u_camPos;\nuniform LightDir u_lightDirGlobal;\nuniform LightPos u_lightsPos[MAX_LIGHTS];\n\n// Output varying's to pass to fragment shader\nout vec2 v_texCoord;\nout vec3 v_lighting;\n\n/*\n * Legacy lighting calc\n * Returns vec2(diffuse, specular)\n */\nvec2 lightCalc(vec3 N, vec3 L, vec3 H, float shininess) {\n float diff = dot(N, L);\n float spec = diff > 0.0 ? pow(max(dot(N, H), 0.0), shininess) : 0.0;\n return vec2(diff, spec);\n}\n\nvoid main() {\n v_texCoord = texcoord;\n gl_Position = u_worldViewProjection * position;\n vec3 worldPos = (u_world * position).xyz;\n\n // Normal for a billboard always points at camera\n vec3 worldNormal = normalize(u_camPos - worldPos);\n\n vec3 V = normalize(u_camPos - worldPos);\n vec3 N = normalize(worldNormal);\n float fudge = 1.5;\n\n // Add point lights to lighting output\n for (int i = 0; i < u_lightsPosCount; i++) {\n LightPos light = u_lightsPos[i];\n vec3 L = normalize(light.position - worldPos.xyz);\n\n float diffuse = max(dot(N, L), 0.0);\n\n // Distance attenuation\n float distance = length(light.position - worldPos.xyz);\n float attenuation = 1.0 / (light.constant + light.linear * distance + light.quad * (distance * distance));\n\n // Note small hack here to fudge the light intensity\n v_lighting += light.colour * fudge * attenuation * diffuse;\n }\n\n // Add in global directional light\n // Approximate by using a fixed direction for the normal pointing up\n vec3 globalLightL = normalize(-u_lightDirGlobal.direction);\n float globalDiffuse = dot(vec3(0.0, 1.0, 0.0), globalLightL);\n\n v_lighting += u_lightDirGlobal.colour * globalDiffuse;\n v_lighting += u_lightDirGlobal.ambient;\n}\n","// ===== physics.ts ===============================================================================\n// Helper functions for adding physics to instances using CANNON.js\n// Ben Coleman, 2023\n// =============================================================================================\n\nimport * as CANNON from 'cannon-es'\nimport { Instance } from '../renderable/instance.ts'\nimport { PrimitiveCube, PrimitiveSphere } from '../renderable/primitive.ts'\nimport { quat } from 'gl-matrix'\nimport { Model } from '../renderable/model.ts'\nimport { XYZ } from './tuples.ts'\n\n/**\n * Create a new CANNON.Body for a sphere, will link the body to the instance\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n */\nfunction createSphereBody(inst: Instance, mass: number, material?: CANNON.Material, offset = [0, 0, 0] as XYZ) {\n if (inst.renderable === undefined) {\n throw new Error('Cannot create body for instance with no renderable')\n }\n\n let radius = 1\n if (inst.renderable instanceof PrimitiveSphere) {\n radius = (inst.renderable as PrimitiveSphere).radius\n }\n\n if (inst.renderable instanceof PrimitiveCube) {\n radius = (inst.renderable as PrimitiveCube).size / 2\n }\n\n if (inst.renderable instanceof Model) {\n // Base the radius on the bounding box of the model\n const boundBox = (inst.renderable as Model).boundingBox\n\n const x = (boundBox[3] - boundBox[0]) * inst.scale[0]\n const y = (boundBox[4] - boundBox[1]) * inst.scale[1]\n const z = (boundBox[5] - boundBox[2]) * inst.scale[2]\n\n radius = Math.max(x, y, z) / 2\n }\n\n const body = new CANNON.Body({\n mass,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n material,\n })\n\n const offsetVec = new CANNON.Vec3(offset[0], offset[1], offset[2])\n body.addShape(new CANNON.Sphere(radius), offsetVec)\n\n inst.physicsBody = body\n return body\n}\n\n/**\n * Create a new cube/box CANNON.Body enclosing the provided instance. It will attempt fit the box to the\n * instance as best a possible, otherwise will fall back to a 1x1x1 box\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n * @param offset Optional offset to apply to the body, useful when models are not centered on origin\n */\nfunction createBoxBody(inst: Instance, mass: number, material?: CANNON.Material, offset = [0, 0, 0] as XYZ) {\n if (inst.renderable === undefined) {\n throw new Error('Cannot create body for instance with no renderable')\n }\n\n let sizeVec = new CANNON.Vec3(0.5, 0.5, 0.5)\n\n if (inst.renderable instanceof PrimitiveSphere) {\n const size = (inst.renderable as PrimitiveSphere).radius * 2\n sizeVec = new CANNON.Vec3(size / 2, size / 2, size / 2)\n }\n\n if (inst.renderable instanceof PrimitiveCube) {\n const size = (inst.renderable as PrimitiveCube).size\n sizeVec = new CANNON.Vec3((size / 2) * inst.scale[0], (size / 2) * inst.scale[1], (size / 2) * inst.scale[2])\n }\n\n if (inst.renderable instanceof Model) {\n // Base the size on the bounding box of the model\n const boundBox = (inst.renderable as Model).boundingBox\n\n sizeVec = new CANNON.Vec3(\n ((boundBox[3] - boundBox[0]) * inst.scale[0]) / 2,\n ((boundBox[4] - boundBox[1]) * inst.scale[1]) / 2,\n ((boundBox[5] - boundBox[2]) * inst.scale[2]) / 2,\n )\n }\n\n const quat = inst.getQuaternion()\n const body = new CANNON.Body({\n mass,\n material,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n quaternion: new CANNON.Quaternion(quat[0], quat[1], quat[2], quat[3]),\n })\n\n const offsetVec = new CANNON.Vec3(offset[0], offset[1], offset[2])\n body.addShape(new CANNON.Box(sizeVec), offsetVec)\n\n inst.physicsBody = body\n return body\n}\n\n/**\n * Create a new CANNON.Body for a plane, will link the body to the instance\n * @param inst Instance to create body for\n * @param mass Mass of the body\n * @param material Optional CANNON.Material to use\n */\nfunction createPlaneBody(inst: Instance, mass: number, material?: CANNON.Material) {\n const instQuat = inst.getQuaternion()\n const q = quat.fromValues(instQuat[0], instQuat[1], instQuat[2], instQuat[3])\n\n // Rotate 90 degrees around the X axis, as CANNON.Plane is along the Z axis\n quat.rotateX(q, q, -Math.PI / 2)\n\n const quaternion = new CANNON.Quaternion(q[0], q[1], q[2], q[3])\n\n const body = new CANNON.Body({\n mass,\n position: new CANNON.Vec3(inst.position[0], inst.position[1], inst.position[2]),\n shape: new CANNON.Plane(),\n material,\n quaternion,\n })\n\n inst.physicsBody = body\n return body\n}\n\nexport const Physics = {\n createSphereBody,\n createBoxBody,\n createPlaneBody,\n}\n","// ===== builder.ts =========================================================\n// Instance builder for creating custom renderable instances\n// Ben Coleman, 2024\n// ============================================================================\n\nimport * as twgl from 'twgl.js'\nimport { vec3 } from 'gl-matrix'\n\nimport { Renderable } from './types.ts'\nimport { ProgramCache } from '../core/cache.ts'\nimport { Stats } from '../core/stats.ts'\nimport { UniformSet } from '../core/gl.ts'\nimport { Material } from '../engine/material.ts'\nimport { XYZ } from '../engine/tuples.ts'\nimport { ModelPart } from './model.ts'\n\n// TODO: No support for smooth shading, with shared vertices and normals\n\n/**\n * A builder for creating multi-part custom renderable instances from triangle meshes\n *\n * Example usage:\n * ```typescript\n * const builder = new RenderableBuilder()\n * const part = builder.newPart('foo' Material.RED)\n * builder.addTriangle([1, -1, 1], [1, 1, 1], [-1, 1, 1])\n * const renderable = builder.build(gl)\n */\nexport class RenderableBuilder {\n public readonly parts: Map\n private materials: Map\n\n constructor() {\n this.parts = new Map()\n this.materials = new Map()\n }\n\n /**\n * Create and add a 'part', each part should have a unique name, and material to apply to it\n * Vertex mesh data is then added to the part, with addQuad and addTriangle\n * @param name Name of this part, just a string can be anything\n * @param material Material to attach and apply to all surfaces in this part\n */\n newPart(name: string, material: Material): BuilderPart {\n if (this.parts.has(name)) {\n throw new Error('Builder part name exists!')\n }\n\n const builderPart = new BuilderPart()\n\n this.parts.set(name, builderPart)\n this.materials.set(name, material)\n\n return builderPart\n }\n\n /**\n * Called after all parts are ready, to generate a CustomRenderable\n * @param gl A WebGL2RenderingContext\n */\n build(gl: WebGL2RenderingContext): CustomRenderable {\n const buffers = new Map()\n\n for (const [name, builderPart] of this.parts) {\n const partBuffers = builderPart.build(gl)\n if (!partBuffers) continue\n buffers.set(name, partBuffers)\n }\n\n return new CustomRenderable(buffers, this.materials)\n }\n}\n\n/**\n * Class to manage parts or sections\n */\nexport class BuilderPart {\n private vertexData: number[] = []\n private vertexCount: number = 0\n private indexData: number[] = []\n private indexCount: number = 0\n private normalData: number[] = []\n private texcoordData: number[] = []\n\n private triangleCount: number = 0\n private _customArrayData: twgl.Arrays | undefined\n\n private addVertex(x: number, y: number, z: number): number {\n this.vertexData.push(x, y, z)\n return this.vertexCount++\n }\n\n private addIndex(): number {\n this.indexData.push(this.indexCount)\n return this.indexCount++\n }\n\n private addNormal(n: XYZ) {\n this.normalData.push(n[0], n[1], n[2])\n }\n\n /**\n * Add a triangle to the renderable part\n * Each triangle must be defined by 3 vertices and will get a normal calculated\n * Each triangle will get a unique normal, so no smooth shading\n * @param v1 Vertex one of the triangle\n * @param v2 Vertex two of the triangle\n * @param v3 Vertex three of the triangle\n */\n addTriangle(v1: XYZ, v2: XYZ, v3: XYZ, tc1 = [0, 0], tc2 = [0, 0], tc3 = [0, 0]) {\n this.triangleCount++\n this.addVertex(v1[0], v1[1], v1[2])\n this.addIndex()\n this.addVertex(v2[0], v2[1], v2[2])\n this.addIndex()\n this.addVertex(v3[0], v3[1], v3[2])\n this.addIndex()\n\n // Normal calculation\n const u = vec3.subtract(vec3.create(), v2, v1)\n const v = vec3.subtract(vec3.create(), v3, v1)\n const n = vec3.cross(vec3.create(), u, v)\n vec3.normalize(n, n)\n\n this.addNormal([n[0], n[1], n[2]])\n this.addNormal([n[0], n[1], n[2]])\n this.addNormal([n[0], n[1], n[2]])\n\n this.texcoordData.push(...tc1, ...tc2, ...tc3)\n }\n\n /*\n * Add a two triangle quad to the renderable part\n * Each quad must be defined by 4 vertices and will get a normal calculated\n * Each quad will get a unique normal, so no smooth shading\n * @param v1 Vertex one of the quad\n * @param v2 Vertex two of the quad\n * @param v3 Vertex three of the quad\n * @param v4 Vertex four of the quad\n */\n addQuad(v1: XYZ, v2: XYZ, v3: XYZ, v4: XYZ, tc1 = [0, 0], tc2 = [0, 0], tc3 = [0, 0], tc4 = [0, 0]) {\n // Anti-clockwise winding order\n this.addTriangle(v1, v2, v3, tc1, tc2, tc3)\n this.addTriangle(v1, v3, v4, tc1, tc3, tc4)\n }\n\n /**\n * This is a very advanced feature, and allows you to provide your own twgl.Arrays\n * This is useful for creating custom renderables from existing data\n * @param array The twgl.Arrays to use for the renderable\n */\n set customArrayData(array: twgl.Arrays) {\n this._customArrayData = array\n }\n\n /**\n * Build the renderable from the data added\n * @param gl A WebGL2 rendering context\n * @returns BufferInfo used by twgl\n */\n build(gl: WebGL2RenderingContext): twgl.BufferInfo | null {\n let bufferInfo: twgl.BufferInfo\n if (this._customArrayData) {\n bufferInfo = twgl.createBufferInfoFromArrays(gl, this._customArrayData)\n } else {\n if (this.vertexData.length === 0) {\n return null\n }\n\n if (this.indexData.length === 0) {\n return null\n }\n\n // This is where the magic happens\n bufferInfo = twgl.createBufferInfoFromArrays(gl, {\n position: this.vertexData,\n indices: this.indexData,\n normal: this.normalData,\n texcoord: this.texcoordData,\n })\n }\n\n return bufferInfo\n }\n}\n\n/**\n * A custom renderable instance, created from a RenderableBuilder\n */\nexport class CustomRenderable implements Renderable {\n private programInfo: twgl.ProgramInfo = ProgramCache.instance.default\n private _triangleCount: number = 0\n private modelParts: ModelPart[]\n\n // List of materials mapped by name\n public readonly materials: Map\n\n constructor(bufferInfos: Map, materials: Map) {\n this.modelParts = new Array()\n this.materials = materials\n\n for (const [name, bi] of bufferInfos) {\n const p = new ModelPart(bi, name)\n this.modelParts.push(p)\n }\n }\n\n /**\n * Render is used draw this custom renderable, this is called from the Instance that wraps\n * this renderable.\n */\n render(\n gl: WebGL2RenderingContext,\n uniforms: UniformSet,\n materialOverride?: Material,\n programOverride?: twgl.ProgramInfo,\n ) {\n const programInfo = programOverride || this.programInfo\n gl.useProgram(programInfo.program)\n\n // Render all parts\n for (const part of this.modelParts) {\n const bufferInfo = part.bufferInfo\n\n if (materialOverride === undefined) {\n const material = this.materials.get(part.materialName)\n if (!material) continue\n material.apply(programInfo)\n } else {\n materialOverride.apply(programInfo)\n }\n\n twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)\n twgl.setUniforms(programInfo, uniforms)\n\n twgl.drawBufferInfo(gl, bufferInfo)\n Stats.drawCallsPerFrame++\n }\n }\n\n get triangleCount(): number {\n return this._triangleCount\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAMA,KAAC,SAAU,MAAM,YAAY;AACzB;AACA,UAAI,OAAO,WAAW,cAAc,OAAO,KAAK;AAC5C,eAAO,UAAU;AAAA,MACrB,WAAW,OAAO,WAAW,YAAY,OAAO,SAAS;AACrD,eAAO,UAAU,WAAW;AAAA,MAChC,OAAO;AACH,aAAK,MAAM,WAAW;AAAA,MAC1B;AAAA,IACJ,GAAE,SAAM,WAAY;AAChB;AAGA,UAAIA,QAAO,WAAW;AAAA,MAAC;AACvB,UAAI,gBAAgB;AACpB,UAAI,OAAQ,OAAO,WAAW,iBAAmB,OAAO,OAAO,cAAc,iBACzE,kBAAkB,KAAK,OAAO,UAAU,SAAS;AAGrD,UAAI,aAAa;AAAA,QACb;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACJ;AAEA,UAAI,iBAAiB,CAAC;AACtB,UAAI,gBAAgB;AAGpB,eAAS,WAAW,KAAK,YAAY;AACjC,YAAI,SAAS,IAAI,UAAU;AAC3B,YAAI,OAA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A;AAAA;AAAA,EAMA,OACE,IACA,UACA,kBACA,iBACA;AACA,UAAM,cAAc,mBAAmB,KAAK;AAC5C,OAAG,WAAW,YAAY,OAAO;AAGjC,eAAW,QAAQ,KAAK,YAAY;AAClC,YAAM,aAAa,KAAK;AAExB,UAAI,qBAAqB,QAAW;AAClC,cAAM,WAAW,KAAK,UAAU,IAAI,KAAK,YAAY;AACrD,YAAI,CAAC;AAAU;AACf,iBAAS,MAAM,WAAW;AAAA,MAC5B,OAAO;AACL,yBAAiB,MAAM,WAAW;AAAA,MACpC;AAEA,MAAK,wBAAwB,IAAI,aAAa,UAAU;AACxD,MAAK,YAAY,aAAa,QAAQ;AAEtC,MAAK,eAAe,IAAI,UAAU;AAClC,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,IAAI,gBAAwB;AAC1B,WAAO,KAAK;AAAA,EACd;AACF;","names":["noop","location","log","import_loglevel","a","b","a","b","v0","v1","v2","a","length","length","length","len","tmp","v0","v1","v2","lerp","a","b","angle","c","base","glEnumToString","isArrayBuffer","getShared2DContext","internalFormat","isArrayBuffer","isArrayBuffer","a","b","clearEventHandlers","onError","onLoad","cb","img","location","b","typeInfo","normalize","log","error","gl","program","token","node","program","location","program","errors","gl","programs","add","create","identity","create","a","identity","b","b2","len","c","add","scale","a2","add","clone","copy","create","dot","equals","exactEquals","fromValues","identity","invert","len","length","lerp","mul","multiply","normalize","random","rotateX","rotateY","rotateZ","scale","set","sqrLen","squaredLength","str","add","clone","copy","create","equals","exactEquals","fromValues","inverse","length","mul","multiply","rotateX","rotateY","rotateZ","scale","set","str","sub","subtract","create","clone","a","length","fromValues","copy","set","add","b","subtract","multiply","scale","inverse","len","c","rotateX","rotateY","rotateZ","str","exactEquals","equals","a2","b2","sub","mul","create","clone","a","fromValues","copy","set","add","b","scale","a","b","length","a","squaredLength","normalize","a","len","dot","b","lerp","a","b","exactEquals","a","b","equals","a2","b2","forEach","create","a","create","identity","a","b","dot","multiply","rotateX","rotateY","rotateZ","scale","random","invert","a2","str","clone","fromValues","copy","set","add","mul","lerp","length","len","squaredLength","sqrLen","normalize","exactEquals","equals","c","b","tmp","a","c","angle","a","min","max","va","vb","vc","cb","ab","b","dist","c","localPlaneEq","planeEqWS","add","wc","torque","distance","len","a","b","c","dot","squaredDistance","a","b","b","min","max","min","max","c","dot","dot2","dist","r","v1","v2","j","relpos","worldPillarOffset","min","max","tmp","va","vb","vc","performance","normalize","len","scale","distance","a","b","add","import_loglevel","log","import_loglevel","CameraType","camView","log","glsl_default","glsl_default","import_loglevel","glsl_default","glsl_default","a","b","glsl_default","log","import_loglevel","log","angle","BillboardType","scale","Material","b","Material","import_loglevel","update_default","render_default","update_default","render_default","log","import_loglevel","keywordRE","Material","log","debug","log","glsl_default","glsl_default","glsl_default","glsl_default","log","glsl_default","a","b","v1","v2"]} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 15ad737..ab04168 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gsots3d", - "version": "0.0.5-alpha.8", + "version": "0.0.5-alpha.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gsots3d", - "version": "0.0.5-alpha.8", + "version": "0.0.5-alpha.10", "license": "MIT", "dependencies": { "cannon-es": "^0.20.0", diff --git a/package.json b/package.json index c8abf82..6fd9d3b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gsots3d", - "version": "0.0.5-alpha.9", + "version": "0.0.5-alpha.10", "description": "Getting S**t On The Screen in 3D. A library for doing 3D graphics in the browser.", "author": "Ben Coleman", "license": "MIT",