{"version":3,"sources":["jsdelivr-header.js","/npm/regl-worldview@0.18.1/src/utils/getOrthographicBounds.js","/npm/regl-worldview@0.18.1/src/camera/cameraProject.js","/npm/regl-worldview@0.18.1/src/utils/commandUtils.js","/npm/regl-worldview@0.18.1/src/camera/cameraStateSelectors.js","/npm/regl-worldview@0.18.1/src/camera/CameraStore.js","/npm/regl-worldview@0.18.1/src/camera/camera.js","/npm/regl-worldview@0.18.1/src/camera/CameraListener.js","/npm/regl-worldview@0.18.1/src/utils/common.js","/npm/regl-worldview@0.18.1/src/utils/Raycast.js","/npm/regl-worldview@0.18.1/src/WorldviewReactContext.js","/npm/regl-worldview@0.18.1/src/commands/Command.js","/npm/regl-worldview@0.18.1/src/utils/aggregate.js","/npm/regl-worldview@0.18.1/src/utils/Dimensions.js","/npm/regl-worldview@0.18.1/src/utils/HitmapObjectIdManager.js","/npm/regl-worldview@0.18.1/src/utils/signal.js","/npm/regl-worldview@0.18.1/src/utils/queuePromise.js","/npm/regl-worldview@0.18.1/src/WorldviewContext.js","/npm/regl-worldview@0.18.1/src/Worldview.js","/npm/regl-worldview@0.18.1/src/utils/Bounds.js","/npm/regl-worldview@0.18.1/src/utils/eulerFromQuaternion.js","/npm/regl-worldview@0.18.1/src/utils/fromGeometry.js","/npm/regl-worldview@0.18.1/src/utils/draco.js","/npm/regl-worldview@0.18.1/src/utils/parseGLB.js","/npm/regl-worldview@0.18.1/src/utils/getChildrenForHitmapDefaults.js","/npm/regl-worldview@0.18.1/src/utils/withRenderStateOverrides.js","/npm/regl-worldview@0.18.1/src/commands/Cylinders.js","/npm/regl-worldview@0.18.1/src/commands/Cones.js","/npm/regl-worldview@0.18.1/src/commands/Arrows.js","/npm/regl-worldview@0.18.1/src/commands/Lines.js","/npm/regl-worldview@0.18.1/src/commands/Axes.js","/npm/regl-worldview@0.18.1/src/commands/Cubes.js","/npm/regl-worldview@0.18.1/src/commands/Spheres.js","/npm/regl-worldview@0.18.1/src/commands/DrawPolygon/index.js","/npm/regl-worldview@0.18.1/src/commands/DrawPolygon/PolygonBuilder.js","/npm/regl-worldview@0.18.1/src/commands/Triangles.js","/npm/regl-worldview@0.18.1/src/commands/FilledPolygons.js","/npm/regl-worldview@0.18.1/src/commands/Text.js","/npm/regl-worldview@0.18.1/src/commands/GLText.js","/npm/regl-worldview@0.18.1/src/commands/GLTFScene.js","/npm/regl-worldview@0.18.1/src/commands/Grid.js","/npm/regl-worldview@0.18.1/src/commands/Overlay.js","/npm/regl-worldview@0.18.1/src/commands/Points.js","/npm/regl-worldview@0.18.1/src/utils/SDFGenerator.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,qjCCEA,MAAM,YAQJ,YAAY,EAAc,GAAa,gBAAA,KAAA,eAAA,gBAAA,KAAA,gBAAA,gBAAA,KAAA,cAAA,gBAAA,KAAA,iBAAA,gBAAA,KAAA,gBAAA,gBAAA,KAAA,iBACrC,KAAK,KAAO,EACZ,KAAK,IAAM,EACX,KAAK,OAAS,EACd,KAAK,QAAU,EACf,KAAK,MAAyB,EAAjB,KAAK,IAAI,GACtB,KAAK,OAAyB,EAAhB,KAAK,IAAI,EACxB,EAGY,SAAS,sBAAsB,EAAmB,EAAe,GAC9E,MAAM,EAAS,EAAQ,EAEjB,EAAmB,KAAK,IAAI,GAGlC,OAAO,IAAI,aAFI,EAAmB,EAAK,EAC3B,EAAmB,EAEhC,CClBD,MAAM,WAAa,EACb,UAAY,EACZ,KAAO,CAAC,EAAG,EAAG,EAAG,GAER,SAAS,cAAc,EAAU,EAAW,EAAgB,GACzE,MAAM,EAAK,EAAS,GAClB,EAAK,EAAS,GACd,EAAS,EAAS,GAClB,EAAU,EAAS,GAMrB,KAAK,IAAI,KAAM,EAAI,GAAI,EAAI,GAAI,EAAI,GAAI,GAGvC,KAAK,cAAc,KAAM,KAAM,GAG/B,MAAM,EAAI,KAAK,GAef,OAdU,IAAN,IAEF,KAAK,GAAK,KAAK,GAAK,EACpB,KAAK,GAAK,KAAK,GAAK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AY,GAE5B,EAAE,MAAM,QAAU,OAClB,EAAE,QACF,EAAE,QACH,gB","file":"/npm/regl-worldview@0.18.1/dist/index.esm.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/regl-worldview@0.18.1/dist/index.esm.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nclass BoundingBox {\n  left: number;\n  right: number;\n  top: number;\n  bottom: number;\n  width: number;\n  height: number;\n\n  constructor(left: number, top: number) {\n    this.left = left;\n    this.top = top;\n    this.right = -left;\n    this.bottom = -top;\n    this.width = Math.abs(left) * 2;\n    this.height = Math.abs(top) * 2;\n  }\n}\n\nexport default function getOrthographicBounds(zDistance: number, width: number, height: number): BoundingBox {\n  const aspect = width / height;\n  // never go below ground level\n  const distanceToGround = Math.abs(zDistance);\n  const left = (-distanceToGround / 2) * aspect;\n  const top = distanceToGround / 2;\n  return new BoundingBox(left, top);\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\n// Copied from Jam3/camera-project\n// in order to replace gl-vec4 dependency with gl-matrix\n\nimport { vec4 } from \"gl-matrix\";\n\nimport type { Vec3, Vec4, Mat4 } from \"../types\";\n\nconst NEAR_RANGE = 0;\nconst FAR_RANGE = 1;\nconst tmp4 = [0, 0, 0, 0];\n\nexport default function cameraProject(out: any, vec: Vec3, viewport: Vec4, combinedProjView: Mat4): Vec4 {\n  const vX = viewport[0],\n    vY = viewport[1],\n    vWidth = viewport[2],\n    vHeight = viewport[3],\n    n = NEAR_RANGE,\n    f = FAR_RANGE;\n\n  // convert: clip space -> NDC -> window coords\n  // implicit 1.0 for w component\n  vec4.set(tmp4, vec[0], vec[1], vec[2], 1.0);\n\n  // transform into clip space\n  vec4.transformMat4(tmp4, tmp4, combinedProjView);\n\n  // now transform into NDC\n  const w = tmp4[3];\n  if (w !== 0) {\n    // how to handle infinity here?\n    tmp4[0] = tmp4[0] / w;\n    tmp4[1] = tmp4[1] / w;\n    tmp4[2] = tmp4[2] / w;\n  }\n\n  // and finally into window coordinates\n  // the foruth component is (1/clip.w)\n  // which is the same as gl_FragCoord.w\n  out[0] = vX + (vWidth / 2) * tmp4[0] + (0 + vWidth / 2);\n  out[1] = vY + (vHeight / 2) * tmp4[1] + (0 + vHeight / 2);\n  out[2] = ((f - n) / 2) * tmp4[2] + (f + n) / 2;\n  out[3] = w === 0 ? 0 : 1 / w;\n  return out;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport type { Color, Point, Orientation, ReglCommand, Vec4, Vec3 } from \"../types\";\n\nconst rotateGLSL = `\n  uniform vec3 _position;\n  uniform vec4 _rotation;\n\n  // rotate a 3d point v by a rotation quaternion q\n  vec3 rotate(vec3 v, vec4 q) {\n    vec3 temp = cross(q.xyz, v) + q.w * v;\n    return v + (2.0 * cross(q.xyz, temp));\n  }\n\n  vec3 applyPose(vec3 point) {\n    // rotate the point and then add the position of the pose\n    return rotate(point, _rotation) + _position;\n  }\n`;\n\nconst DEFAULT_TEXT_COLOR = { r: 1, g: 1, b: 1, a: 1 };\n\nexport const pointToVec3 = ({ x, y, z }: Point): Vec3 => {\n  return [x, y, z];\n};\nexport const orientationToVec4 = ({ x, y, z, w }: Orientation): Vec4 => {\n  return [x, y, z, w];\n};\n\nexport const vec3ToPoint = ([x, y, z]: Vec3): Point => ({ x, y, z });\n\nexport const vec4ToOrientation = ([x, y, z, w]: Vec4): Orientation => ({ x, y, z, w });\n\nexport const pointToVec3Array = (points: Point[]) => {\n  const result = new Float32Array(points.length * 3);\n  let i = 0;\n  for (const { x, y, z } of points) {\n    result[i++] = x;\n    result[i++] = y;\n    result[i++] = z;\n  }\n  return result;\n};\n\nexport const toRGBA = (val: Color) => {\n  return [val.r, val.g, val.b, val.a];\n};\n\nexport const vec4ToRGBA = (color: Vec4): Color => ({ r: color[0], g: color[1], b: color[2], a: color[3] });\n\nexport const toColor = (val: Color | Vec4): Color => (Array.isArray(val) ? vec4ToRGBA(val) : val);\n\nexport function getCSSColor(color: Color = DEFAULT_TEXT_COLOR) {\n  const { r, g, b, a } = color;\n  return `rgba(${(r * 255).toFixed()}, ${(g * 255).toFixed()}, ${(b * 255).toFixed()}, ${a.toFixed(3)})`;\n}\n\nconst toRGBAArray = (colors: $ReadOnlyArray<Color>): Float32Array => {\n  const result = new Float32Array(colors.length * 4);\n  let i = 0;\n  for (const { r, g, b, a } of colors) {\n    result[i++] = r;\n    result[i++] = g;\n    result[i++] = b;\n    result[i++] = a;\n  }\n  return result;\n};\n\nconst constantRGBAArray = (count: number, { r, g, b, a }: Color): Float32Array => {\n  const result = new Float32Array(count * 4);\n  for (let i = 0; i < count; i++) {\n    result[4 * i + 0] = r;\n    result[4 * i + 1] = g;\n    result[4 * i + 2] = b;\n    result[4 * i + 3] = a;\n  }\n  return result;\n};\n\n// default blend func params to be mixed into regl commands\nexport const defaultReglBlend = {\n  enable: true,\n  // this is the same gl.BlendFunc used by three.js by default\n  func: {\n    src: \"src alpha\",\n    dst: \"one minus src alpha\",\n    srcAlpha: 1,\n    dstAlpha: \"one minus src alpha\",\n  },\n  equation: {\n    rgb: \"add\",\n    alpha: \"add\",\n  },\n};\n\nexport const defaultReglDepth = {\n  enable: true,\n  mask: true,\n};\n\nexport const defaultDepth = {\n  enable: (context: any, props: any) => (props.depth && props.depth.enable) || defaultReglDepth.enable,\n  mask: (context: any, props: any) => (props.depth && props.depth.mask) || defaultReglDepth.mask,\n};\n\nexport const defaultBlend = {\n  ...defaultReglBlend,\n  enable: (context: any, props: any) => (props.blend && props.blend.enable) || defaultReglBlend.enable,\n  func: (context: any, props: any) => (props.blend && props.blend.func) || defaultReglBlend.func,\n};\n\n// TODO: deprecating, remove before 1.x release\nexport const blend = defaultBlend;\n\n// takes a regl command definition object and injects\n// position and rotation from the object pose and also\n// inserts some glsl helpers to apply the pose to points in a fragment shader\nexport function withPose(command: ReglCommand): ReglCommand {\n  const { vert, uniforms } = command;\n  const newVert = vert.replace(\"#WITH_POSE\", rotateGLSL);\n  const newUniforms = {\n    ...uniforms,\n    _position: (context, props) => {\n      const { position } = props.pose;\n      return Array.isArray(position) ? position : pointToVec3(position);\n    },\n    _rotation: (context, props) => {\n      const { orientation: r } = props.pose;\n      return Array.isArray(r) ? r : [r.x, r.y, r.z, r.w];\n    },\n  };\n  return {\n    ...command,\n    vert: newVert,\n    uniforms: newUniforms,\n  };\n}\n\nexport function getVertexColors({\n  colors,\n  color,\n  points,\n}: {\n  colors?: $ReadOnlyArray<Color> | $ReadOnlyArray<Vec4>,\n  color: Color,\n  points: $ReadOnlyArray<Point>,\n}): Float32Array | $ReadOnlyArray<Vec4> {\n  if ((!colors || !colors.length) && color) {\n    return constantRGBAArray(points.length, color);\n  }\n  if (colors) {\n    // $FlowFixMe this will go away once we consolidate getVertexColors and colorBuffer\n    return shouldConvert(colors) ? toRGBAArray(colors) : colors;\n  }\n  return [];\n}\n\nfunction hasNestedArrays(arr: any[]) {\n  return arr.length && Array.isArray(arr[0]);\n}\n\n// Returns a function which accepts a single color, an array of colors, and the number of instances,\n// and returns a color attribute buffer for use in regl.\n// If there are multiple colors in the colors array, one color will be assigned to each instance.\n// In the case of a single color, the same color will be used for all instances.\nexport function colorBuffer(regl: any) {\n  const buffer = regl.buffer({\n    usage: \"dynamic\",\n    data: [],\n  });\n\n  return function(color: any, colors: any, length: number) {\n    let data, divisor;\n    if (!colors || !colors.length) {\n      data = shouldConvert(color) ? toRGBA(color) : color;\n      divisor = length;\n    } else {\n      data = shouldConvert(colors) ? toRGBAArray(colors) : colors;\n      divisor = 1;\n    }\n    return {\n      buffer: buffer({\n        usage: \"dynamic\",\n        data,\n      }),\n      divisor,\n    };\n  };\n}\n\n// used to determine if the input/array of inputs is an object like {r: 0, g: 0, b: 0} or [0,0,0]\nexport function shouldConvert(props: any) {\n  if (!props || hasNestedArrays(props) || !isNaN(props[0])) {\n    return false;\n  }\n  return true;\n}\n\nexport function intToRGB(i: number = 0): Vec4 {\n  const r = ((i >> 16) & 255) / 255;\n  const g = ((i >> 8) & 255) / 255;\n  const b = (i & 255) / 255;\n  return [r, g, b, 1];\n}\n\nexport function getIdFromColor(rgb: Vec4): number {\n  const r = rgb[0] * 255;\n  const g = rgb[1] * 255;\n  const b = rgb[2] * 255;\n  return b | (g << 8) | (r << 16);\n}\n\nexport function getIdFromPixel(rgb: Uint8Array): number {\n  const r = rgb[0];\n  const g = rgb[1];\n  const b = rgb[2];\n  return b | (g << 8) | (r << 16);\n}\n\n// gl-matrix clone of three.js Vector3.setFromSpherical\n// phi: polar angle (between poles, 0 - pi)\n// theta: azimuthal angle (around equator, 0 - 2pi)\nexport function fromSpherical(out: number[], r: number, theta: number, phi: number): Vec3 {\n  const rSinPhi = r * Math.sin(phi);\n  out[0] = rSinPhi * Math.sin(theta);\n  out[1] = r * Math.cos(phi);\n  out[2] = rSinPhi * Math.cos(theta);\n  return (out: any);\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { vec3, quat, mat4 } from \"gl-matrix\";\nimport { createSelector } from \"reselect\";\n\nimport type { CameraState, Vec4, Vec3, Mat4 } from \"../types\";\nimport { fromSpherical } from \"../utils/commandUtils\";\n\nconst UNIT_X_VECTOR = Object.freeze([1, 0, 0]);\n\n// reusable arrays for intermediate calculations\nconst TEMP_VEC3 = [0, 0, 0];\nconst TEMP_MAT = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\nconst TEMP_QUAT = [0, 0, 0, 0];\n\nconst stateSelector = (state: CameraState) => state;\n\nconst perspectiveSelector = createSelector(\n  stateSelector,\n  ({ perspective }) => perspective\n);\nconst distanceSelector = createSelector(\n  stateSelector,\n  ({ distance }) => distance\n);\nconst phiSelector = createSelector(\n  stateSelector,\n  ({ phi }) => phi\n);\nconst thetaOffsetSelector = createSelector(\n  stateSelector,\n  ({ thetaOffset }) => thetaOffset\n);\nconst targetOrientationSelector = createSelector(\n  stateSelector,\n  ({ targetOrientation }) => targetOrientation\n);\n\n// the heading direction of the target\nconst targetHeadingSelector: (CameraState) => number = createSelector(\n  targetOrientationSelector,\n  (targetOrientation) => {\n    const out = vec3.transformQuat(TEMP_VEC3, UNIT_X_VECTOR, targetOrientation);\n    const heading = -Math.atan2(out[1], out[0]);\n    return heading;\n  }\n);\n\n// orientation of the camera\nconst orientationSelector: (CameraState) => Vec4 = createSelector(\n  perspectiveSelector,\n  phiSelector,\n  thetaOffsetSelector,\n  (perspective, phi, thetaOffset) => {\n    const result = quat.identity([0, 0, 0, 0]);\n    quat.rotateZ(result, result, -thetaOffset);\n\n    // phi is ignored in 2D mode\n    if (perspective) {\n      quat.rotateX(result, result, phi);\n    }\n    return result;\n  }\n);\n\n// position of the camera\nconst positionSelector: (CameraState) => Vec3 = createSelector(\n  thetaOffsetSelector,\n  phiSelector,\n  distanceSelector,\n  (thetaOffset, phi, distance) => {\n    const position = fromSpherical([], distance, thetaOffset, phi);\n\n    // poles are on the y-axis in spherical coordinates; rearrange so they are on the z axis\n    const [x, y, z] = position;\n    position[0] = -x;\n    position[1] = -z;\n    position[2] = y;\n\n    return position;\n  }\n);\n\n/*\nGet the view matrix, which transforms points from world coordinates to camera coordinates.\n\nAn equivalent and easier way to think about this transformation is that it takes the camera from\nits actual position/orientation in the world, and moves it to have position=0,0,0 and orientation=0,0,0,1.\n\nWe build up this transformation in 5 steps as demonstrated below:\n   T = target\n   < = direction of target\n   * = target with offset (position that the camera is looking at)\n   C = camera (always points toward *)\n\nStarting point: actual positions in world coordinates\n\n  |      *\n  |  <T   C\n  |\n  +--------\n\nStep 1: translate target to the origin\n\n  |\n  |  *\n <T---C----\n\nStep 2: rotate around the origin so the target points forward\n(Here we use the target's heading only, ignoring other components of its rotation)\n\n  |\n  ^\n  T--------\n  |\n  | *\n  C\n\nStep 3: translate the target-with-offset point to be at the origin\n\n ^\n T|\n  |\n  *--------\n C|\n  |\n\n\nStep 4: translate the camera to be at the origin\n(Steps 3 and 4 are both translations, but they're kept separate because it's easier\nto conceptualize: 3 uses the targetOffset and 4 uses the distance+thetaOffset+phi.)\n\n ^\n T\n |\n |*\n C--------\n |\n\nStep 5: rotate the camera to point forward\n\n \\\n  T  |\n     *\n     C--------\n     |\n\n*/\nconst viewSelector: (CameraState) => Mat4 = createSelector(\n  stateSelector,\n  orientationSelector,\n  positionSelector,\n  targetHeadingSelector,\n  ({ target, targetOffset, perspective }, orientation, position, targetHeading) => {\n    const m = mat4.identity([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n\n    // apply the steps described above in reverse because we use right-multiplication\n\n    // 5. rotate camera to point forward\n    mat4.multiply(m, m, mat4.fromQuat(TEMP_MAT, quat.invert(TEMP_QUAT, orientation)));\n\n    // 4. move camera to the origin\n    if (perspective) {\n      mat4.translate(m, m, vec3.negate(TEMP_VEC3, position));\n    }\n\n    // 3. move center to the origin\n    mat4.translate(m, m, vec3.negate(TEMP_VEC3, targetOffset));\n\n    // 2. rotate target to point forward\n    mat4.rotateZ(m, m, targetHeading);\n\n    // 1. move target to the origin\n    vec3.negate(TEMP_VEC3, target);\n    if (!perspective) {\n      // if using orthographic camera ensure the distance from \"ground\"\n      // stays large so no reasonably tall item goes past the camera\n      TEMP_VEC3[2] = -2500;\n    }\n    mat4.translate(m, m, TEMP_VEC3);\n\n    return m;\n  }\n);\n\nconst billboardRotation: (CameraState) => Mat4 = createSelector(\n  orientationSelector,\n  targetHeadingSelector,\n  (orientation, targetHeading) => {\n    const m = mat4.identity(mat4.create());\n    mat4.rotateZ(m, m, -targetHeading);\n    mat4.multiply(m, m, mat4.fromQuat(TEMP_MAT, orientation));\n    return m;\n  }\n);\n\nexport default {\n  orientation: orientationSelector,\n  position: positionSelector,\n  targetHeading: targetHeadingSelector,\n  view: viewSelector,\n  billboardRotation,\n};\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { vec3, quat } from \"gl-matrix\";\n\nimport type { Vec2, Vec3, Vec4 } from \"../types\";\nimport selectors from \"./cameraStateSelectors\";\n\nexport type CameraState = {|\n  distance: number,\n  perspective: boolean,\n  phi: number,\n  target: Vec3,\n  targetOffset: Vec3,\n  targetOrientation: Vec4,\n  thetaOffset: number,\n  fovy: number,\n  near: number,\n  far: number,\n|};\n\n//  we use up on the +z axis\nconst UNIT_Z_VECTOR = Object.freeze([0, 0, 1]);\n// reusable array for intermediate calculations\nconst TEMP_QUAT = [0, 0, 0, 0];\n\nexport const DEFAULT_CAMERA_STATE: CameraState = {\n  distance: 75,\n  perspective: true,\n  phi: Math.PI / 4,\n  target: [0, 0, 0],\n  targetOffset: [0, 0, 0],\n  targetOrientation: [0, 0, 0, 1],\n  thetaOffset: 0,\n  fovy: Math.PI / 4,\n  near: 0.01,\n  far: 5000,\n};\n\nfunction distanceAfterZoom(startingDistance: number, zoomPercent: number): number {\n  // keep distance above 0 so that percentage-based zoom always works\n  return Math.max(0.001, startingDistance * (1 - zoomPercent / 100));\n}\n\nexport default class CameraStore {\n  state: CameraState;\n\n  _onChange: (CameraState) => void;\n\n  constructor(\n    handler: (CameraState) => void = () => {},\n    initialCameraState: $Shape<CameraState> = DEFAULT_CAMERA_STATE\n  ) {\n    this._onChange = handler;\n    this.setCameraState(initialCameraState);\n  }\n\n  setCameraState = (state: $Shape<CameraState>) => {\n    // Fill in missing properties from DEFAULT_CAMERA_STATE.\n    // Mutate the `state` parameter instead of copying -- this\n    // matches the previous behavior of this method, which didn't\n    // fill in missing properties but also didn't copy `state`.\n    for (const [key, value] of Object.entries(DEFAULT_CAMERA_STATE)) {\n      if (state[key] == null) {\n        state[key] = value;\n      }\n    }\n    // `state` must be a valid CameraState now, because we filled in\n    // missing properties from DEFAULT_CAMERA_STATE.\n    this.state = (state: any);\n  };\n\n  cameraRotate = ([x, y]: Vec2) => {\n    // This can happen in 2D mode, when both e.movementX and e.movementY are evaluated as negative and mouseX move is 0\n    if (x === 0 && y === 0) {\n      return;\n    }\n    const { thetaOffset, phi } = this.state;\n    this.setCameraState({\n      ...this.state,\n      thetaOffset: thetaOffset - x,\n      phi: Math.max(0, Math.min(phi + y, Math.PI)),\n    });\n    this._onChange(this.state);\n  };\n\n  // move the camera along x, y axis; do not move up/down\n  cameraMove = ([x, y]: Vec2) => {\n    // moveX and moveY both be 0 sometimes\n    if (x === 0 && y === 0) {\n      return;\n    }\n\n    const { targetOffset, thetaOffset } = this.state;\n\n    // rotate around z axis so the offset is in the target's reference frame\n    const result = [x, y, 0];\n    const offset = vec3.transformQuat(result, result, quat.setAxisAngle(TEMP_QUAT, UNIT_Z_VECTOR, -thetaOffset));\n\n    this.setCameraState({\n      ...this.state,\n      targetOffset: vec3.add(offset, targetOffset, offset),\n    });\n    this._onChange(this.state);\n  };\n\n  cameraZoom = (zoomPercent: number) => {\n    const { distance } = this.state;\n    const newDistance: number = distanceAfterZoom(distance, zoomPercent);\n    if (distance === newDistance) {\n      return;\n    }\n\n    this.setCameraState({\n      ...this.state,\n      distance: newDistance,\n    });\n    this._onChange(this.state);\n  };\n}\n\nexport { selectors };\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { mat4 } from \"gl-matrix\";\n\nimport type { Vec3, Mat4, CameraCommand, Viewport } from \"../types\";\nimport getOrthographicBounds from \"../utils/getOrthographicBounds\";\nimport project from \"./cameraProject\";\nimport { selectors, DEFAULT_CAMERA_STATE, type CameraState } from \"./CameraStore\";\n\nconst TEMP_MAT = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n// This is the regl command which encapsulates the camera projection and view matrices.\n// It adds the matrices to the regl context so they can be used by other commands.\nexport default (regl: any) => {\n  if (!regl) {\n    throw new Error(\"Invalid regl instance\");\n  }\n\n  return class Camera implements CameraCommand {\n    viewportWidth: number = 0;\n    viewportHeight: number = 0;\n    cameraState: CameraState = DEFAULT_CAMERA_STATE;\n\n    getProjection(): Mat4 {\n      const { near, far, distance, fovy } = this.cameraState;\n      if (!this.cameraState.perspective) {\n        const bounds = getOrthographicBounds(distance, this.viewportWidth, this.viewportHeight);\n        const { left, right, bottom, top } = bounds;\n        return mat4.ortho([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], left, right, bottom, top, near, far);\n      }\n      const aspect = this.viewportWidth / this.viewportHeight;\n      return mat4.perspective([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], fovy, aspect, near, far);\n    }\n\n    getView(): Mat4 {\n      return selectors.view(this.cameraState);\n    }\n\n    // convert a point in 3D space to a point on the screen\n    toScreenCoord(viewport: Viewport, point: Vec3) {\n      const projection = this.getProjection();\n      const view = selectors.view(this.cameraState);\n      const combinedProjView = mat4.multiply(TEMP_MAT, projection, view);\n      const [x, y, z, w] = project([], point, viewport, combinedProjView);\n      if (z < 0 || z > 1 || w < 0) {\n        // resulting point is outside the window depth range\n        return undefined;\n      }\n      const diffY = viewport[3] + viewport[1];\n      const diffX = viewport[0];\n      // move the x value over based on the left of the viewport\n      // and move the y value over based on the bottom of the viewport\n      return [x - diffX, diffY - y, z];\n    }\n\n    draw = regl({\n      // adds context variables to the regl context so they are accessible from commands\n      context: {\n        // use functions, not lambdas here to make sure we can access\n        // the regl supplied this scope: http://regl.party/api#this\n        projection(context, props) {\n          const { viewportWidth, viewportHeight } = context;\n          // save these variables on the camera instance\n          // because we need them for raycasting\n          this.viewportWidth = viewportWidth;\n          this.viewportHeight = viewportHeight;\n          this.cameraState = props;\n          return this.getProjection();\n        },\n\n        view(context, props) {\n          return this.getView();\n        },\n\n        // inverse of the view rotation, used for making objects always face the camera\n        billboardRotation(context, props) {\n          return selectors.billboardRotation(this.cameraState);\n        },\n\n        isPerspective(context, props) {\n          return this.cameraState.perspective;\n        },\n\n        fovy(context, props) {\n          return this.cameraState.fovy;\n        },\n      },\n\n      // adds view and projection as uniforms to every command\n      // and makes them available in the shaders\n      uniforms: {\n        view: regl.context(\"view\"),\n        billboardRotation: regl.context(\"billboardRotation\"),\n        projection: regl.context(\"projection\"),\n      },\n    });\n  };\n};\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport normalizeWheel from \"normalize-wheel\";\nimport * as React from \"react\";\n\nimport type { CameraKeyMap, CameraAction, Vec2 } from \"../types\";\nimport getOrthographicBounds from \"../utils/getOrthographicBounds\";\nimport CameraStore from \"./CameraStore\";\n\nconst PAN_SPEED = 4;\nconst MOUSE_ZOOM_SPEED = 0.3;\nconst KEYBOARD_MOVE_SPEED = 0.3;\nconst KEYBOARD_ZOOM_SPEED = 150;\nconst KEYBOARD_SPIN_SPEED = 1.5;\n\nconst DEFAULT_KEYMAP: CameraKeyMap = {\n  KeyA: \"moveLeft\",\n  KeyD: \"moveRight\",\n  KeyE: \"rotateRight\",\n  KeyF: \"tiltUp\",\n  KeyQ: \"rotateLeft\",\n  KeyR: \"tiltDown\",\n  KeyS: \"moveDown\",\n  KeyW: \"moveUp\",\n  KeyX: \"zoomOut\",\n  KeyZ: \"zoomIn\",\n};\n\ntype KeyMotion = { x?: number, y?: number, zoom?: number, yaw?: number, tilt?: number };\n\ntype Props = {|\n  cameraStore: CameraStore,\n  keyMap?: CameraKeyMap,\n  shiftKeys: boolean,\n  children?: React.ChildrenArray<React.Element<any> | null>,\n|};\n\n// attaches mouse and keyboard listeners to allow for moving the camera on user input\nexport default class CameraListener extends React.Component<Props> {\n  _keyTimer: ?AnimationFrameID;\n  _keys: Set<string> = new Set();\n  _buttons: Set<number> = new Set();\n  _listeners = [];\n  _shiftKey = false;\n  _metaKey = false;\n  _ctrlKey = false;\n\n  _el: ?HTMLDivElement;\n  _rect: ClientRect | DOMRect;\n  _initialMouse: Vec2;\n\n  componentDidMount() {\n    const { _el } = this;\n    if (!_el) {\n      return;\n    }\n\n    this._rect = _el.getBoundingClientRect();\n    const listen = (target: any, name: string, fn) => {\n      target.addEventListener(name, fn);\n      this._listeners.push({ target, name, fn });\n    };\n    listen(document, \"blur\", this._onBlur);\n    listen(window, \"mouseup\", this._onWindowMouseUp);\n    _el.addEventListener(\"wheel\", this._onWheel, { passive: false });\n  }\n\n  componentWillUnmount() {\n    this._listeners.forEach((listener) => {\n      listener.target.removeEventListener(listener.name, listener.fn);\n    });\n    this._endDragging();\n    const { _el } = this;\n    if (!_el) {\n      return;\n    }\n    _el.removeEventListener(\"wheel\", this._onWheel, { passive: false });\n  }\n\n  focus() {\n    if (this._el) {\n      this._el.focus();\n    }\n  }\n\n  _getMouseOnScreen = (mouse: MouseEvent) => {\n    const { clientX, clientY } = mouse;\n    const { top, left, width, height } = this._rect;\n    const x = (clientX - left) / width;\n    const y = (clientY - top) / height;\n    return [x, y];\n  };\n\n  _onMouseDown = (e: MouseEvent) => {\n    const { _el } = this;\n    if (!_el) {\n      return;\n    }\n\n    e.preventDefault();\n    this._buttons.add(e.button);\n    _el.focus();\n    this._rect = _el.getBoundingClientRect();\n    this._initialMouse = this._getMouseOnScreen(e);\n    this.startDragging(e);\n  };\n\n  _isLeftMouseDown() {\n    return this._buttons.has(0);\n  }\n\n  _isRightMouseDown() {\n    return this._buttons.has(2);\n  }\n\n  _getMagnitude(base: number = 1) {\n    return this._shiftKey ? base / 10 : base;\n  }\n\n  _getMoveMagnitude() {\n    // avoid interference with drawing tools\n    if (this._ctrlKey) {\n      return { x: 0, y: 0 };\n    }\n\n    const {\n      cameraStore: {\n        state: { distance, perspective },\n      },\n    } = this.props;\n    if (perspective) {\n      // in perspective mode its more like flying, so move by the magnitude\n      // we use the camera distance as a heuristic\n      return { x: distance, y: distance };\n    }\n    // in orthographic mode we know the exact viewable area\n    // which is a square so we can move exactly percentage within it\n    const { width, height } = this._rect;\n    const bounds = getOrthographicBounds(distance, width, height);\n    return { x: bounds.width, y: bounds.height };\n  }\n\n  _onWindowMouseMove = (e: MouseEvent) => {\n    if (!this._buttons.size) {\n      return;\n    }\n    this._shiftKey = e.shiftKey;\n    const {\n      cameraStore: {\n        cameraMove,\n        cameraRotate,\n        state: { perspective },\n      },\n    } = this.props;\n\n    // compute the amount the mouse has moved\n    let moveX, moveY;\n    const mouse = this._getMouseOnScreen(e);\n    // when pointer lock is enabled, we get movementX and movementY (with direction reversed)\n    // instead of the screenX/screenY changing... except, when using synergy, they come through\n    // like regular mousemove events.\n    if ((document: any).pointerLockElement && (e.movementX || e.movementY)) {\n      moveX = -e.movementX / this._rect.width;\n      moveY = -e.movementY / this._rect.height;\n    } else {\n      moveX = this._initialMouse[0] - mouse[0];\n      moveY = this._initialMouse[1] - mouse[1];\n    }\n    this._initialMouse = mouse;\n\n    if (this._isRightMouseDown()) {\n      const magnitude = this._getMagnitude(PAN_SPEED);\n      // in orthographic mode, flip the direction of rotation so \"left\" means \"counterclockwise\"\n      const x = (perspective ? moveX : -moveX) * magnitude;\n      // do not rotate vertically in orthograhpic mode\n      const y = perspective ? moveY * magnitude : 0;\n      cameraRotate([x, y]);\n    }\n\n    if (this._isLeftMouseDown()) {\n      const { x, y } = this._getMoveMagnitude();\n      cameraMove([this._getMagnitude(moveX * x), this._getMagnitude(-moveY * y)]);\n    }\n  };\n\n  _onMouseUp = (e: MouseEvent) => {\n    this._buttons.delete(e.button);\n    this._endDragging();\n  };\n\n  _onWindowMouseUp = (e: MouseEvent) => {\n    const { _el } = this;\n    if (!_el) {\n      return;\n    }\n\n    // do nothing if this container had a mouseup, because we catch it in the onMouseUp handler\n    if (_el.contains((e.target: any)) || e.target === _el) {\n      return;\n    }\n    // If mouseup triggers on the window outside this container, clear any active interactions.\n    // This will allow a mouseup outside the browser window to be handled; otherwise the mouse\n    // \"sticks\" in a down position until another click on this element is received.\n    this._buttons.clear();\n    this._endDragging();\n  };\n\n  startDragging(e: MouseEvent) {\n    if (e.button !== 0 && this._el && typeof this._el.requestPointerLock === \"function\") {\n      this._el.requestPointerLock();\n    }\n    window.addEventListener(\"mousemove\", this._onWindowMouseMove);\n  }\n\n  _endDragging() {\n    window.removeEventListener(\"mousemove\", this._onWindowMouseMove);\n    if (typeof (document: any).exitPointerLock === \"function\") {\n      (document: any).exitPointerLock();\n    }\n  }\n\n  _getKeyMotion = (code: string): ?KeyMotion => {\n    const moveSpeed = this._getMagnitude(KEYBOARD_MOVE_SPEED);\n    const zoomSpeed = this._getMagnitude(KEYBOARD_ZOOM_SPEED);\n    const spinSpeed = this._getMagnitude(KEYBOARD_SPIN_SPEED);\n    const { keyMap, shiftKeys } = this.props;\n    const action: CameraAction | false = (keyMap && keyMap[code]) || DEFAULT_KEYMAP[code] || false;\n\n    if (this._shiftKey && !shiftKeys) {\n      return null;\n    }\n\n    switch (action) {\n      case \"moveRight\":\n        return { x: moveSpeed };\n      case \"moveLeft\":\n        return { x: -moveSpeed };\n      case \"moveUp\":\n        return { y: moveSpeed };\n      case \"moveDown\":\n        return { y: -moveSpeed };\n      case \"zoomIn\":\n        return { zoom: zoomSpeed };\n      case \"zoomOut\":\n        return { zoom: -zoomSpeed };\n      case \"rotateLeft\":\n        return { yaw: -spinSpeed };\n      case \"rotateRight\":\n        return { yaw: spinSpeed };\n      case \"tiltUp\":\n        return { tilt: -spinSpeed };\n      case \"tiltDown\":\n        return { tilt: spinSpeed };\n      case false:\n        return null;\n      default:\n        (action: empty);\n        console.warn(\"Unrecognized key action:\", action);\n        return null;\n    }\n  };\n\n  _moveKeyboard(dt: number) {\n    const motion = { x: 0, y: 0, zoom: 0, yaw: 0, tilt: 0 };\n    this._keys.forEach((code) => {\n      const { x = 0, y = 0, zoom = 0, yaw = 0, tilt = 0 } = this._getKeyMotion(code) || {};\n      motion.x += x;\n      motion.y += y;\n      motion.zoom += zoom;\n      motion.yaw += yaw;\n      motion.tilt += tilt;\n    });\n\n    const {\n      cameraStore: {\n        cameraMove,\n        cameraRotate,\n        cameraZoom,\n        state: { perspective },\n      },\n    } = this.props;\n\n    if (motion.x || motion.y) {\n      const { x, y } = this._getMoveMagnitude();\n      cameraMove([motion.x * x * dt, motion.y * y * dt]);\n    }\n    if (motion.yaw || (perspective && motion.tilt)) {\n      cameraRotate([motion.yaw * dt, perspective ? motion.tilt * dt : 0]);\n    }\n    if (motion.zoom) {\n      cameraZoom(motion.zoom * dt);\n    }\n  }\n\n  _startKeyTimer(lastStamp: ?number) {\n    if (this._keyTimer) {\n      return;\n    }\n    this._keyTimer = requestAnimationFrame((stamp) => {\n      this._moveKeyboard((lastStamp ? stamp - lastStamp : 0) / 1000);\n      this._keyTimer = undefined;\n\n      // Only start the timer if keys are still pressed.\n      // We do this rather than stopping the timer in onKeyUp, because keys held\n      // sometimes actually trigger repeated keyup/keydown, rather than just repeated keydown.\n      // By checking currently-down keys in the requestAnimationFrame callback, we give the browser enough time to\n      // handle both the keyup and keydown before checking whether we should restart the timer.\n      if (this._keys.size) {\n        this._startKeyTimer(stamp);\n      }\n    });\n  }\n\n  _stopKeyTimer() {\n    if (this._keyTimer) {\n      cancelAnimationFrame(this._keyTimer);\n    }\n    this._keyTimer = undefined;\n  }\n\n  _onKeyDown = (e: SyntheticKeyboardEvent<HTMLDivElement>) => {\n    const { keyMap } = this.props;\n    this._shiftKey = e.shiftKey;\n    this._metaKey = e.metaKey;\n    this._ctrlKey = e.ctrlKey;\n    const code = ((e.nativeEvent: any): KeyboardEvent).code;\n\n    // ignore repeated keydown events\n    if (e.repeat || this._keys.has(code)) {\n      e.stopPropagation();\n      e.preventDefault();\n      return;\n    }\n\n    if (e.altKey || e.ctrlKey || e.metaKey) {\n      // we don't currently handle these modifiers\n      return;\n    }\n\n    // allow null, false, or empty keymappings which explicitly cancel Worldview from processing that key\n    if (keyMap && code in keyMap && !keyMap[code]) {\n      return false;\n    }\n\n    // if we respond to this key, start the update timer\n    if (this._getKeyMotion(code)) {\n      this._keys.add(code);\n      this._startKeyTimer();\n      e.stopPropagation();\n      e.preventDefault();\n    }\n  };\n\n  _onKeyUp = (e: SyntheticKeyboardEvent<HTMLDivElement>) => {\n    this._shiftKey = e.shiftKey;\n    this._metaKey = e.metaKey;\n    this._ctrlKey = e.ctrlKey;\n\n    this._keys.delete(((e.nativeEvent: any): KeyboardEvent).code);\n  };\n\n  _onWheel = (e: WheelEvent) => {\n    // stop the wheel event here, as wheel propagation through the entire dom\n    // can cause the browser to slow down & thrash\n    e.preventDefault();\n    e.stopPropagation();\n    this._shiftKey = e.shiftKey;\n\n    // with osx trackpad scrolling, slow to medium pixelY is around +/- 1 to 10\n    // external mouse wheels generally come in higher values around +/- 30 to 50\n    const { pixelX, pixelY } = normalizeWheel(e);\n\n    // shift+scroll on an external mouse may scroll in the X direction instead of Y\n    const wheelAmount = pixelY || pixelX;\n\n    // we use positive value to indicate zooming in\n    // and negative value to zoom out, so reverse the direction of the wheel\n    const dir = Math.sign(wheelAmount) * -1;\n    const amount = Math.abs(wheelAmount);\n    // restrict zoom percentage per tick to between 1 & 50 percent\n    const percentage = Math.max(1, Math.min(amount, 50));\n\n    // support shift+wheel magnitude adjustment\n    const zoomPercentage = this._getMagnitude(percentage * dir * MOUSE_ZOOM_SPEED);\n    this.props.cameraStore.cameraZoom(zoomPercentage);\n  };\n\n  // make sure all movements stop if the document loses focus by resetting modifier keys\n  // to their 'off' position\n  // (e.g. ctrl+tab leaving the page should not leave the ctrl key in the 'on' position)\n  _onBlur = (e: MouseEvent) => {\n    this._keys = new Set();\n    this._ctrlKey = false;\n    this._shiftKey = false;\n    this._metaKey = false;\n    this._stopKeyTimer();\n  };\n\n  _onContextMenu = (e: MouseEvent) => {\n    e.preventDefault();\n    e.stopPropagation();\n  };\n\n  render() {\n    const { children } = this.props;\n    return (\n      <div\n        tabIndex={0}\n        style={{ outline: \"none\" }}\n        draggable\n        ref={(el) => (this._el = el)}\n        onMouseDown={this._onMouseDown}\n        onMouseUp={this._onMouseUp}\n        onBlur={this._onBlur}\n        onContextMenu={this._onContextMenu}\n        onKeyDown={this._onKeyDown}\n        onKeyUp={this._onKeyUp}>\n        {children}\n      </div>\n    );\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nexport function getNodeEnv() {\n  return process && process.env && process.env.NODE_ENV;\n}\n\n/* eslint-disable no-undef */\nexport const inWebWorker = () =>\n  global.postMessage && typeof WorkerGlobalScope !== \"undefined\" && self instanceof WorkerGlobalScope;\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { vec3, mat4 } from \"gl-matrix\";\n\nimport type { CameraCommand, Vec3 } from \"../types\";\n\ntype ClickInfo = { clientX: number, clientY: number, width: number, height: number };\n\nconst tempVec = [0, 0, 0];\nconst tempMat = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n\nexport class Ray {\n  origin: Vec3;\n  dir: Vec3;\n  point: Vec3;\n\n  constructor(origin: Vec3, dir: Vec3, point: Vec3) {\n    this.origin = origin;\n    this.dir = dir;\n    this.point = point;\n  }\n\n  distanceToPoint(point: Vec3) {\n    return vec3.distance(this.origin, point);\n  }\n\n  // https://commons.apache.org/proper/commons-math/javadocs/api-3.6/src-html/org/apache/commons/math3/geometry/euclidean/threed/Plane.html#line.394\n  planeIntersection(planeCoordinate: Vec3, planeNormal: Vec3): ?Vec3 {\n    const d = vec3.dot(planeNormal, planeCoordinate);\n    const cosine = vec3.dot(planeNormal, this.dir);\n\n    if (cosine === 0) {\n      return null;\n    }\n\n    const x = (d - vec3.dot(planeNormal, this.origin)) / cosine;\n    const contact = vec3.add([0, 0, 0], this.origin, vec3.scale(tempVec, this.dir, x));\n    return contact;\n  }\n}\n\n// adapted from https://github.com/regl-project/regl/blob/master/example/raycast.js\nexport function getRayFromClick(camera: CameraCommand, { clientX, clientY, width, height }: ClickInfo) {\n  const projectionMatrix = camera.getProjection();\n  const viewMatrix = camera.getView();\n\n  const vp = mat4.multiply(tempMat, projectionMatrix, viewMatrix);\n  const invVp = mat4.invert(tempMat, vp);\n\n  const mouseX = (2.0 * clientX) / width - 1.0;\n  const mouseY = (-2.0 * clientY) / height + 1.0;\n  // get a single point on the camera ray.\n  const rayPoint = vec3.transformMat4([0, 0, 0], [mouseX, mouseY, 0.0], invVp);\n\n  // get the position of the camera.\n  const rayOrigin = vec3.transformMat4([0, 0, 0], [0, 0, 0], mat4.invert(tempMat, viewMatrix));\n  const rayDir = vec3.normalize([0, 0, 0], vec3.subtract(tempVec, rayPoint, rayOrigin));\n\n  return new Ray(rayOrigin, rayDir, rayPoint);\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React from \"react\";\n\nimport { type WorldviewContextType } from \"./WorldviewContext\";\n\n// $FlowFixMe\nexport default React.createContext((undefined: WorldviewContextType | void));\n","// @flow\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type {\n  ComponentMouseHandler,\n  GetChildrenForHitmap,\n  MouseEventEnum,\n  RawCommand,\n  Color,\n  Point,\n  MouseEventObject,\n} from \"../types\";\nimport { getNodeEnv } from \"../utils/common\";\nimport { Ray } from \"../utils/Raycast\";\nimport { type WorldviewContextType } from \"../WorldviewContext\";\nimport WorldviewReactContext from \"../WorldviewReactContext\";\n\nexport const SUPPORTED_MOUSE_EVENTS = [\"onClick\", \"onMouseUp\", \"onMouseMove\", \"onMouseDown\", \"onDoubleClick\"];\n\nexport type MarkerDefault = {\n  id?: number,\n  points?: Point[],\n  color?: Color,\n};\n\nexport type CommonCommandProps = {\n  [MouseEventEnum]: ComponentMouseHandler,\n  layerIndex?: number,\n  getChildrenForHitmap?: GetChildrenForHitmap,\n};\n\ntype Props<T> = {\n  ...CommonCommandProps,\n  children?: T[] | T,\n  // Deprecated, but here for backwards compatibility\n  drawProps?: T[],\n  reglCommand: RawCommand<T>,\n};\n\nexport type CommandProps<T> = Props<T>;\n\n// Component to dispatch children (for drawing) and hitmap props and a reglCommand to the render loop to render with regl.\nexport default class Command<T> extends React.Component<Props<T>> {\n  context: ?WorldviewContextType;\n  static displayName = \"Command\";\n\n  constructor(props: Props<T>) {\n    super(props);\n    // In development put a check in to make sure the reglCommand prop is not mutated.\n    // Similar to how react checks for unsupported or deprecated calls in a development build.\n    if (getNodeEnv() !== \"production\") {\n      // $FlowFixMe\n      this.shouldComponentUpdate = (nextProps: Props) => {\n        if (nextProps.reglCommand !== this.props.reglCommand) {\n          console.error(\"Changing the regl command prop on a <Command /> is not supported.\");\n        }\n        return true;\n      };\n    }\n  }\n\n  componentDidMount() {\n    const context = this.context;\n    if (!context) {\n      return;\n    }\n    context.onMount(this, this.props.reglCommand);\n    this._updateContext();\n  }\n\n  componentDidUpdate() {\n    this._updateContext();\n  }\n\n  componentWillUnmount() {\n    const context = this.context;\n    if (!context) {\n      return;\n    }\n    context.onUnmount(this);\n  }\n\n  _updateContext() {\n    const context = this.context;\n    if (!context) {\n      return;\n    }\n\n    const { reglCommand, layerIndex, getChildrenForHitmap } = this.props;\n    const children = this.props.children || this.props.drawProps;\n    if (children == null) {\n      return;\n    }\n    context.registerDrawCall({\n      instance: this,\n      reglCommand,\n      children,\n      layerIndex,\n      getChildrenForHitmap,\n    });\n  }\n\n  handleMouseEvent(\n    objects: MouseEventObject[],\n    ray: Ray,\n    e: SyntheticMouseEvent<HTMLCanvasElement>,\n    mouseEventName: MouseEventEnum\n  ) {\n    const mouseHandler = this.props[mouseEventName];\n    if (!mouseHandler || !objects.length) {\n      return;\n    }\n    mouseHandler(e, { ray, objects });\n  }\n\n  render() {\n    return (\n      <WorldviewReactContext.Consumer>\n        {(ctx: ?WorldviewContextType) => {\n          if (ctx) {\n            this.context = ctx;\n          }\n          return null;\n        }}\n      </WorldviewReactContext.Consumer>\n    );\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\n// Takes an array of [value, key] and aggregates across the keys. Results in a Map of [key, values[]], in order of the\n// keys as seen in the array.\nexport default function aggregate<T, K>(array: Array<[T, K]>): Map<K, T[]> {\n  const aggregationMap = new Map<K, T[]>();\n  array.forEach(([item, key]) => {\n    const existingItems = aggregationMap.get(key) || [];\n    existingItems.push(item);\n    if (!aggregationMap.has(key)) {\n      aggregationMap.set(key, existingItems);\n    }\n  });\n  return aggregationMap;\n}\n","// @flow\n//\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React, { useEffect, useState, useCallback, type Node } from \"react\";\n\nimport { inWebWorker } from \"./common\";\n\ntype DimensionsParams = {| height: number, width: number, left: number, top: number |};\ntype Props = {|\n  children: (DimensionsParams) => Node,\n|};\n\n// Jest does not include ResizeObserver.\nclass ResizeObserverMock {\n  _callback: (ResizeObserverEntry[]) => void;\n  constructor(callback) {\n    this._callback = callback;\n  }\n\n  observe() {\n    const entry: any = { contentRect: { width: 150, height: 150 } };\n    this._callback([entry]);\n  }\n  unobserve() {}\n}\nconst ResizeObserverImpl =\n  process.env.NODE_ENV === \"test\" || inWebWorker() ? (ResizeObserverMock: any) : ResizeObserver;\n\n// Calculates the dimensions of the parent element, and passes those dimensions to the child function.\n// Uses resizeObserver, which is very performant.\n// Works by rendering an empty div, getting the parent element, and then once we know the dimensions of the parent\n// element, rendering the children. After the initial render it just observes the parent element.\n// We expect the parent element to never change.\nexport default function Dimensions({ children }: Props) {\n  const [parentElement, setParentElement] = useState(undefined);\n  const [dimensions, setDimensions] = useState<?DimensionsParams>();\n  // This resizeObserver should never change.\n  const [resizeObserver] = useState<ResizeObserver>(\n    () =>\n      new ResizeObserverImpl((entries) => {\n        if (!entries || !entries.length) {\n          return;\n        }\n\n        // We only observe a single element, so just use the first entry.\n        // We have to round because these could be sub-pixel values.\n        const newWidth = Math.round(entries[0].contentRect.width);\n        const newHeight = Math.round(entries[0].contentRect.height);\n        const newLeft = Math.round(entries[0].contentRect.left);\n        const newTop = Math.round(entries[0].contentRect.top);\n        setDimensions({ width: newWidth, height: newHeight, top: newTop, left: newLeft });\n      })\n  );\n\n  // This should only fire once, because `dimensions` should only be undefined at the beginning.\n  const setParentElementRef = useCallback((element) => {\n    if (element) {\n      setParentElement(element.parentElement);\n    }\n  }, []);\n\n  useEffect(() => {\n    if (!parentElement) {\n      return;\n    }\n    resizeObserver.observe(parentElement);\n    // Make sure to unobserve when we unmount the component.\n    return () => resizeObserver.unobserve(parentElement);\n  }, [parentElement, resizeObserver]);\n\n  // This only happens during the first render - we use it to grab the parentElement of this div.\n  if (dimensions == null) {\n    return <div ref={setParentElementRef} />;\n  }\n  return children(dimensions);\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport last from \"lodash/last\";\n\nimport Command from \"../commands/Command\";\nimport type { ObjectHitmapId, Vec4, MouseEventObject } from \"../types\";\nimport { intToRGB } from \"./commandUtils\";\n\nfunction fillArray(start: number, length: number): number[] {\n  return new Array(length).fill(0).map((_, index) => start + index);\n}\n\ntype CommandType = Command<any>;\n\n/*\n * This object manages the mapping between objects that are rendered into the scene and their IDs.\n * It supplies an API for generating IDs for a rendered object and then accessing those objects based on their ID.\n */\nexport default class HitmapObjectIdManager {\n  _objectsByObjectHitmapIdMap: { [ObjectHitmapId]: Object } = {};\n  _commandsByObjectMap: Map<Object, CommandType> = new Map();\n  _nextObjectHitmapId = 1;\n  _instanceIndexByObjectHitmapIdMap: { [ObjectHitmapId]: number } = {};\n\n  assignNextColors = (command: CommandType, object: Object, count: number): Vec4[] => {\n    if (count < 1) {\n      throw new Error(\"Must get at least 1 id\");\n    }\n\n    const ids: ObjectHitmapId[] = fillArray(this._nextObjectHitmapId, count);\n    this._nextObjectHitmapId = last(ids) + 1;\n\n    // Instanced rendering - add to the instanced ID map.\n    if (count > 1) {\n      ids.forEach((id, index) => {\n        this._instanceIndexByObjectHitmapIdMap[id] = index;\n      });\n    }\n\n    // Store the mapping of ID to original marker object\n    for (const id of ids) {\n      this._objectsByObjectHitmapIdMap[id] = object;\n    }\n    this._commandsByObjectMap.set(object, command);\n\n    // Return colors from the IDs.\n    const colors = ids.map((id) => intToRGB(id));\n    return colors;\n  };\n\n  getObjectByObjectHitmapId = (objectHitmapId: ObjectHitmapId): MouseEventObject => {\n    return {\n      object: this._objectsByObjectHitmapIdMap[objectHitmapId],\n      instanceIndex: this._instanceIndexByObjectHitmapIdMap[objectHitmapId],\n    };\n  };\n\n  getCommandForObject = (object: Object): ?CommandType => {\n    return this._commandsByObjectMap.get(object);\n  };\n}\n","// @flow\n//\n//  Copyright (c) 2019-present, Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nexport type Signal<T> = Promise<T> & {\n  resolve: (T) => void,\n  reject: (Error) => void,\n};\n\nexport function signal<T>(): Signal<T> {\n  let resolve;\n  let reject;\n  const promise: any = new Promise((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  promise.resolve = resolve;\n  promise.reject = reject;\n  return promise;\n}\n","// @flow\n//\n//  Copyright (c) 2019-present, Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { signal, type Signal } from \"./signal\";\n\ntype QueuedFn = ((...args: any[]) => Promise<any>) & { currentPromise: ?Promise<any> };\n\n// Wait for the previous promise to resolve before starting the next call to the function.\nexport default function queuePromise(fn: (...args: any[]) => Promise<any>): QueuedFn {\n  // Whether we are currently waiting for a promise returned by `fn` to resolve.\n  let calling = false;\n  // The list of calls made to the function was made while a call was in progress.\n  const nextCalls: {| args: any[], promise: Signal<any> |}[] = [];\n\n  function queuedFn(...args) {\n    if (calling) {\n      const returnPromise = signal();\n      nextCalls.push({ args, promise: returnPromise });\n      return returnPromise;\n    }\n    return start(...args);\n  }\n\n  function start(...args) {\n    calling = true;\n\n    const promise = fn(...args).finally(() => {\n      calling = false;\n      queuedFn.currentPromise = undefined;\n      if (nextCalls.length) {\n        const { promise: nextPromise, args: nextArgs } = nextCalls.shift();\n        start(...nextArgs)\n          .then((result) => nextPromise.resolve(result))\n          .catch((error) => nextPromise.reject(error));\n      }\n    });\n    queuedFn.currentPromise = promise;\n\n    return promise;\n  }\n\n  return queuedFn;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\nimport createREGL from \"regl\";\nimport shallowequal from \"shallowequal\";\n\nimport { camera, CameraStore } from \"./camera/index\";\nimport Command from \"./commands/Command\";\nimport type {\n  Dimensions,\n  RawCommand,\n  CompiledReglCommand,\n  CameraCommand,\n  Vec4,\n  CameraState,\n  MouseEventObject,\n  GetChildrenForHitmap,\n  AssignNextColorsFn,\n} from \"./types\";\nimport { getIdFromPixel, intToRGB } from \"./utils/commandUtils\";\nimport { getNodeEnv } from \"./utils/common\";\nimport HitmapObjectIdManager from \"./utils/HitmapObjectIdManager\";\nimport queuePromise from \"./utils/queuePromise\";\nimport { getRayFromClick } from \"./utils/Raycast\";\n\ntype Props = any;\n\ntype ConstructorArgs = {\n  dimension: Dimensions,\n  canvasBackgroundColor: Vec4,\n  cameraState: CameraState,\n  defaultCameraState?: CameraState,\n  onCameraStateChange: ?(CameraState) => void,\n  contextAttributes?: ?{ [string]: any },\n};\n\ntype InitializedData = {\n  _fbo: any,\n  regl: any,\n  camera: CameraCommand,\n};\n\nexport type DrawInput = {\n  instance: Command<any>,\n  reglCommand: RawCommand<any>,\n  children: Props,\n  layerIndex: ?number,\n  getChildrenForHitmap: ?GetChildrenForHitmap,\n};\n\nexport type PaintFn = () => void;\n\nexport type WorldviewContextType = {\n  onMount(instance: Command<any>, command: RawCommand<any>): void,\n  registerDrawCall(drawInput: DrawInput): void,\n  registerPaintCallback(PaintFn): void,\n  unregisterPaintCallback(PaintFn): void,\n  onUnmount(instance: Command<any>): void,\n  onDirty(): void,\n  +dimension: Dimensions,\n  +initializedData: ?InitializedData,\n};\n\n// Compile instructions with an initialized regl context into a regl command.\n// If the instructions are a function, pass the context to the instructions and compile the result\n// of the function; otherwise, compile the instructions directly\nfunction compile<T>(regl: any, cmd: RawCommand<T>): CompiledReglCommand<T> {\n  const src = cmd(regl);\n  return typeof src === \"function\" ? src : regl(src);\n}\n\n// This is made available to every Command component as `this.context`.\n// It contains all the regl interaction code and is responsible for collecting and executing\n// draw calls, hitmap calls, and raycasting.\n\nexport class WorldviewContext {\n  _commands: Set<RawCommand<any>> = new Set();\n  _compiled: Map<Function, CompiledReglCommand<any>> = new Map();\n  _drawCalls: Map<React.Component<any>, DrawInput> = new Map();\n  _frame: ?AnimationFrameID;\n  _needsPaint = false;\n  _paintCalls: Map<PaintFn, PaintFn> = new Map();\n  _hitmapObjectIdManager: HitmapObjectIdManager = new HitmapObjectIdManager();\n  _cachedReadHitmapCall: ?{\n    arguments: any[],\n    result: Array<[MouseEventObject, Command<any>]>,\n  } = undefined;\n  // store every compiled command object compiled for debugging purposes\n  reglCommandObjects: { stats: { count: number } }[] = [];\n  counters: { paint?: number, render?: number } = {};\n  dimension: Dimensions;\n  onDirty: () => void;\n  cameraStore: CameraStore;\n  canvasBackgroundColor: Vec4 = [0, 0, 0, 1];\n  // group all initialized data together so it can be checked for existence to verify initialization is complete\n  initializedData: ?InitializedData;\n  contextAttributes: ?{ [string]: any };\n\n  constructor({\n    dimension,\n    canvasBackgroundColor,\n    cameraState,\n    onCameraStateChange,\n    contextAttributes,\n  }: ConstructorArgs) {\n    // used for children to call paint() directly\n    this.dimension = dimension;\n    this.canvasBackgroundColor = canvasBackgroundColor;\n    this.contextAttributes = contextAttributes;\n    this.cameraStore = new CameraStore((cameraState: CameraState) => {\n      if (onCameraStateChange) {\n        onCameraStateChange(cameraState);\n      } else {\n        // this must be called for Worldview with defaultCameraState prop\n        this.paint();\n      }\n    }, cameraState);\n  }\n\n  initialize(canvas: HTMLCanvasElement) {\n    if (this.initializedData) {\n      throw new Error(\"can not initialize regl twice\");\n    }\n\n    const regl = this._instrumentCommands(\n      createREGL({\n        canvas,\n        attributes: this.contextAttributes || {},\n        extensions: [\n          \"angle_instanced_arrays\",\n          \"oes_texture_float\",\n          \"oes_element_index_uint\",\n          \"oes_standard_derivatives\",\n        ],\n        profile: getNodeEnv() !== \"production\",\n      })\n    );\n\n    if (!regl) {\n      throw new Error(\"Cannot initialize regl\");\n    }\n\n    // compile any components which mounted before regl is initialized\n    this._commands.forEach((uncompiledCommand) => {\n      const compiledCommand = compile(regl, uncompiledCommand);\n      this._compiled.set(uncompiledCommand, compiledCommand);\n    });\n\n    const Camera = compile(regl, camera);\n    const compiledCameraCommand = new Camera();\n    // framebuffer object from regl context\n    const fbo = regl.framebuffer({\n      width: Math.round(this.dimension.width),\n      height: Math.round(this.dimension.height),\n    });\n\n    this.initializedData = {\n      _fbo: fbo,\n      camera: compiledCameraCommand,\n      regl,\n    };\n  }\n\n  destroy() {\n    if (this.initializedData) {\n      this.initializedData.regl.destroy();\n    }\n    if (this._frame) {\n      cancelAnimationFrame(this._frame);\n    }\n  }\n\n  // compile a command when it is first mounted, and try to register in _commands and _compiled maps\n  onMount(instance: React.Component<any>, command: RawCommand<any>) {\n    const { initializedData } = this;\n    // do nothing if regl hasn't been initialized yet\n    if (!initializedData || this._commands.has(command)) {\n      return;\n    }\n    this._commands.add(command);\n\n    // for components that mount after regl is initialized\n    this._compiled.set(command, compile(initializedData.regl, command));\n  }\n\n  // unregister children hitmap and draw calls\n  onUnmount(instance: React.Component<any>) {\n    this._drawCalls.delete(instance);\n  }\n\n  unregisterPaintCallback(paintFn: PaintFn) {\n    this._paintCalls.delete(paintFn);\n  }\n\n  registerDrawCall(drawInput: DrawInput) {\n    this._drawCalls.set(drawInput.instance, drawInput);\n  }\n\n  registerPaintCallback(paintFn: PaintFn) {\n    this._paintCalls.set(paintFn, paintFn);\n  }\n\n  setDimension(dimension: Dimensions) {\n    this.dimension = dimension;\n  }\n\n  raycast = (canvasX: number, canvasY: number) => {\n    if (!this.initializedData) {\n      return undefined;\n    }\n\n    const { width, height } = this.dimension;\n    return getRayFromClick(this.initializedData.camera, {\n      clientX: canvasX,\n      clientY: canvasY,\n      width,\n      height,\n    });\n  };\n\n  paint() {\n    try {\n      this._paint();\n    } catch (error) {\n      // Regl automatically tries to reconnect when losing the canvas 3d context.\n      // We should log this error, but it's not important to throw it.\n      if (error.message === \"(regl) context lost\") {\n        console.warn(error);\n      } else {\n        throw error;\n      }\n    }\n  }\n\n  _paint() {\n    this._needsPaint = false;\n    const start = Date.now();\n    this.reglCommandObjects.forEach((cmd) => (cmd.stats.count = 0));\n    if (!this.initializedData) {\n      return;\n    }\n    this._cachedReadHitmapCall = null; // clear the cache every time we paint\n    const { regl, camera } = this.initializedData;\n    this._clearCanvas(regl);\n    camera.draw(this.cameraStore.state, () => {\n      const x = Date.now();\n      this._drawInput();\n      this.counters.paint = Date.now() - x;\n    });\n\n    this._paintCalls.forEach((paintCall) => {\n      paintCall();\n    });\n    this.counters.render = Date.now() - start;\n    // More React state updates may have happened while we were painting, since paint happens\n    // outside the normal React render flow. If this is the case, we need to paint again.\n    if (this._needsPaint) {\n      this._frame = requestAnimationFrame(() => this.paint());\n    } else {\n      this._frame = undefined;\n    }\n  }\n\n  onDirty = () => {\n    if (undefined === this._frame) {\n      this._frame = requestAnimationFrame(() => this.paint());\n    } else {\n      this._needsPaint = true;\n    }\n  };\n\n  readHitmap = queuePromise(\n    (\n      canvasX: number,\n      canvasY: number,\n      enableStackedObjectEvents: boolean,\n      maxStackedObjectCount: number\n    ): Promise<Array<[MouseEventObject, Command<any>]>> => {\n      if (!this.initializedData) {\n        return Promise.reject(new Error(\"regl data not initialized yet\"));\n      }\n      const args = [canvasX, canvasY, enableStackedObjectEvents, maxStackedObjectCount];\n\n      const cachedReadHitmapCall = this._cachedReadHitmapCall;\n      if (cachedReadHitmapCall) {\n        if (shallowequal(cachedReadHitmapCall.arguments, args)) {\n          // Make sure that we aren't returning the exact object identity of the mouseEventObject - we don't know what\n          // callers have done with it.\n          const result = cachedReadHitmapCall.result.map(([mouseEventObject, command]) => [\n            { ...mouseEventObject },\n            command,\n          ]);\n          return Promise.resolve(result);\n        }\n        this._cachedReadHitmapCall = undefined;\n      }\n\n      const { regl, camera, _fbo } = this.initializedData;\n      const { width, height } = this.dimension;\n\n      const x = canvasX;\n      // 0,0 corresponds to the bottom left in the webgl context, but the top left in window coordinates\n      const y = height - canvasY;\n\n      // regl will only resize the framebuffer if the size changed\n      // it uses floored whole pixel values\n      _fbo.resize(Math.floor(width), Math.floor(height));\n\n      return new Promise((resolve) => {\n        // tell regl to use a framebuffer for this render\n        regl({ framebuffer: _fbo })(() => {\n          // clear the framebuffer\n          regl.clear({ color: intToRGB(0), depth: 1 });\n          let currentObjectId = 0;\n          const excludedObjects = [];\n          const mouseEventsWithCommands = [];\n          let counter = 0;\n\n          camera.draw(this.cameraStore.state, () => {\n            // Every iteration in this loop clears the framebuffer, draws the hitmap objects that have NOT already been\n            // seen to the framebuffer, and then reads the pixel under the cursor to find the object on top.\n            // If `enableStackedObjectEvents` is false, we only do this iteration once - we only resolve with 0 or 1\n            // objects.\n            do {\n              if (counter >= maxStackedObjectCount) {\n                // Provide a max number of layers so this while loop doesn't crash the page.\n                console.error(\n                  `Hit ${maxStackedObjectCount} iterations. There is either a bug or that number of rendered hitmap layers under the mouse cursor.`\n                );\n                break;\n              }\n              counter++;\n              regl.clear({ color: intToRGB(0), depth: 1 });\n              this._drawInput(true, excludedObjects);\n\n              // it's possible to get x/y values outside the framebuffer size\n              // if the mouse quickly leaves the draw area during a read operation\n              // reading outside the bounds of the framebuffer causes errors\n              // and puts regl into a bad internal state.\n              // https://github.com/regl-project/regl/blob/28fbf71c871498c608d9ec741d47e34d44af0eb5/lib/read.js#L57\n              if (x < Math.floor(width) && y < Math.floor(height) && x >= 0 && y >= 0) {\n                const pixel = new Uint8Array(4);\n\n                // read pixel value from the frame buffer\n                regl.read({\n                  x,\n                  y,\n                  width: 1,\n                  height: 1,\n                  data: pixel,\n                });\n\n                currentObjectId = getIdFromPixel(pixel);\n                const mouseEventObject = this._hitmapObjectIdManager.getObjectByObjectHitmapId(currentObjectId);\n\n                // Check an error case: if we see an ID/color that we don't know about, it means that some command is\n                // drawing a color into the hitmap that it shouldn't be.\n                if (currentObjectId > 0 && !mouseEventObject) {\n                  console.error(\n                    `Clicked on an unknown object with id ${currentObjectId}. This likely means that a command is painting an incorrect color into the hitmap.`\n                  );\n                }\n                // Check an error case: if we've already seen this object, then the getHitmapFromChildren function\n                // is not respecting the excludedObjects correctly and we should notify the user of a bug.\n                if (\n                  excludedObjects.some(\n                    ({ object, instanceIndex }) =>\n                      object === mouseEventObject.object && instanceIndex === mouseEventObject.instanceIndex\n                  )\n                ) {\n                  console.error(\n                    `Saw object twice when reading from hitmap. There is likely an error in getHitmapFromChildren`,\n                    mouseEventObject\n                  );\n                  break;\n                }\n\n                if (currentObjectId > 0 && mouseEventObject.object) {\n                  const command = this._hitmapObjectIdManager.getCommandForObject(mouseEventObject.object);\n                  excludedObjects.push(mouseEventObject);\n                  if (command) {\n                    mouseEventsWithCommands.push([mouseEventObject, command]);\n                  }\n                }\n              }\n              // If we haven't enabled stacked object events, break out of the loop immediately.\n              // eslint-disable-next-line no-unmodified-loop-condition\n            } while (currentObjectId !== 0 && enableStackedObjectEvents);\n\n            this._cachedReadHitmapCall = {\n              arguments: args,\n              result: mouseEventsWithCommands,\n            };\n            resolve(mouseEventsWithCommands);\n          });\n        });\n      });\n    }\n  );\n\n  _drawInput = (isHitmap?: boolean, excludedObjects?: MouseEventObject[]) => {\n    if (isHitmap) {\n      this._hitmapObjectIdManager = new HitmapObjectIdManager();\n    }\n\n    const drawCalls = Array.from(this._drawCalls.values()).sort((a, b) => (a.layerIndex || 0) - (b.layerIndex || 0));\n    drawCalls.forEach((drawInput: DrawInput) => {\n      const { reglCommand, children, instance, getChildrenForHitmap } = drawInput;\n      if (!children) {\n        return console.debug(`${isHitmap ? \"hitmap\" : \"\"} draw skipped, props was falsy`, drawInput);\n      }\n      const cmd = this._compiled.get(reglCommand);\n      if (!cmd) {\n        return console.warn(\"could not find draw command for\", instance ? instance.constructor.displayName : \"Unknown\");\n      }\n      // draw hitmap\n      if (isHitmap && getChildrenForHitmap) {\n        const assignNextColorsFn: AssignNextColorsFn = (...rest) => {\n          return this._hitmapObjectIdManager.assignNextColors(instance, ...rest);\n        };\n        const hitmapProps = getChildrenForHitmap(children, assignNextColorsFn, excludedObjects || []);\n        if (hitmapProps) {\n          cmd(hitmapProps, true);\n        }\n      } else if (!isHitmap) {\n        cmd(children, false);\n      }\n    });\n  };\n\n  _clearCanvas = (regl: any) => {\n    // Since we aren't using regl.frame and only rendering when we need to,\n    // we need to tell regl to update its internal state.\n    regl.poll();\n    regl.clear({\n      color: this.canvasBackgroundColor,\n      depth: 1,\n    });\n  };\n\n  _instrumentCommands(regl: any) {\n    if (getNodeEnv() === \"production\") {\n      return regl;\n    }\n    return new Proxy(regl, {\n      apply: (target, thisArg, args) => {\n        const command = target(...args);\n        if (typeof command.stats === \"object\") {\n          this.reglCommandObjects.push(command);\n        }\n        return command;\n      },\n    });\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport mapValues from \"lodash/mapValues\";\nimport pickBy from \"lodash/pickBy\";\nimport * as React from \"react\";\n\nimport { CameraListener, DEFAULT_CAMERA_STATE } from \"./camera/index\";\nimport Command from \"./commands/Command\";\nimport type {\n  MouseHandler,\n  Dimensions,\n  Vec4,\n  CameraState,\n  CameraKeyMap,\n  MouseEventEnum,\n  MouseEventObject,\n} from \"./types\";\nimport aggregate from \"./utils/aggregate\";\nimport { getNodeEnv } from \"./utils/common\";\nimport ContainerDimensions from \"./utils/Dimensions\";\nimport { Ray } from \"./utils/Raycast\";\nimport { WorldviewContext } from \"./WorldviewContext\";\nimport WorldviewReactContext from \"./WorldviewReactContext\";\n\nconst DEFAULT_BACKGROUND_COLOR = [0, 0, 0, 1];\nexport const DEFAULT_MOUSE_CLICK_RADIUS = 3;\nconst DEFAULT_MAX_NUMBER_OF_HITMAP_LAYERS = 100;\n\nexport type BaseProps = {|\n  keyMap?: CameraKeyMap,\n  shiftKeys: boolean,\n  backgroundColor?: Vec4,\n  // (Deprecated) rendering the hitmap on mouse move is expensive, so disable it by default\n  hitmapOnMouseMove?: boolean,\n  // Disable hitmap generation for specific mouse events\n  // For example, if you want to disable hitmap generating on drag, use: [\"onMouseDown\", \"onMouseMove\", \"onMouseUp\"]\n  disableHitmapForEvents?: MouseEventEnum[],\n  // getting events for objects stacked on top of each other is expensive, so disable it by default\n  enableStackedObjectEvents?: boolean,\n  // allow users to specify the max stacked object count\n  maxStackedObjectCount: number,\n  showDebug?: boolean,\n  children?: React.Node,\n  style: { [styleAttribute: string]: number | string },\n\n  cameraState?: $Shape<CameraState>,\n  onCameraStateChange?: (CameraState) => void,\n  defaultCameraState?: $Shape<CameraState>,\n  // interactions\n  onDoubleClick?: MouseHandler,\n  onMouseDown?: MouseHandler,\n  onMouseUp?: MouseHandler,\n  onMouseMove?: MouseHandler,\n  onClick?: MouseHandler,\n\n  // Used to scale the canvas resolution and provide a higher image quality\n  resolutionScale?: number,\n  ...Dimensions,\n\n  // Context attributes passed into canvas.getContext.\n  contextAttributes?: ?{ [string]: any },\n  canvas?: HTMLCanvasElement,\n|};\n\ntype State = {|\n  worldviewContext: WorldviewContext,\n|};\n\nfunction handleWorldviewMouseInteraction(\n  objects: MouseEventObject[],\n  ray: Ray,\n  e: SyntheticMouseEvent<HTMLCanvasElement>,\n  handler: MouseHandler\n) {\n  const args = { ray, objects };\n\n  try {\n    handler(e, args);\n  } catch (err) {\n    console.error(\"Error during mouse handler\", err);\n  }\n}\n\n// responsible for camera and scene state management\n// takes in children that declaritively define what should be rendered\nexport class WorldviewBase extends React.Component<BaseProps, State> {\n  _canvas: { current: HTMLCanvasElement | null } = React.createRef();\n  _cameraListener: { current: CameraListener | null } = React.createRef();\n  _tick: AnimationFrameID | void;\n  _dragStartPos: ?{ x: number, y: number } = null;\n\n  static defaultProps = {\n    maxStackedObjectCount: DEFAULT_MAX_NUMBER_OF_HITMAP_LAYERS,\n    backgroundColor: DEFAULT_BACKGROUND_COLOR,\n    shiftKeys: true,\n    style: {},\n    resolutionScale: 1,\n  };\n\n  constructor(props: BaseProps) {\n    super(props);\n    const {\n      width,\n      height,\n      top,\n      left,\n      backgroundColor,\n      onCameraStateChange,\n      cameraState,\n      defaultCameraState,\n      hitmapOnMouseMove,\n      disableHitmapForEvents,\n      canvas,\n    } = props;\n    if (canvas) {\n      this._canvas.current = canvas;\n    }\n    if (onCameraStateChange) {\n      if (!cameraState) {\n        console.warn(\n          \"You provided `onCameraStateChange` without `cameraState`. Use Worldview as a controlled component with `cameraState` and `onCameraStateChange`, or uncontrolled with `defaultCameraState`.\"\n        );\n      }\n      if (cameraState && defaultCameraState) {\n        console.warn(\"You provided both `cameraState` and `defaultCameraState`. `defaultCameraState` will be ignored.\");\n      }\n    } else {\n      if (cameraState) {\n        console.warn(\n          \"You provided `cameraState` without an `onCameraStateChange` handler. This will prevent moving the camera. If the camera should be movable, use `defaultCameraState`, otherwise set `onCameraStateChange`.\"\n        );\n      }\n    }\n\n    if (hitmapOnMouseMove) {\n      if (disableHitmapForEvents) {\n        throw new Error(\n          \"Property 'hitmapOnMouseMove' is deprectated and will be ignored when used along with 'disableHitmapForEvents'.\"\n        );\n      } else {\n        console.warn(\n          \"Property 'hitmapOnMouseMove' is deprectated. Please use 'disableHitmapForEvents' property instead.\"\n        );\n      }\n    }\n\n    this.state = {\n      worldviewContext: new WorldviewContext({\n        dimension: { width, height, top, left },\n        canvasBackgroundColor: backgroundColor || DEFAULT_BACKGROUND_COLOR,\n        // DEFAULT_CAMERA_STATE is applied if both `cameraState` and `defaultCameraState` are not present\n        cameraState: props.cameraState || props.defaultCameraState || DEFAULT_CAMERA_STATE,\n        onCameraStateChange: props.onCameraStateChange || undefined,\n        contextAttributes: props.contextAttributes || {},\n      }),\n    };\n  }\n\n  static getDerivedStateFromProps({ width, height, top, left }: BaseProps, { worldviewContext }: State) {\n    worldviewContext.setDimension({ width, height, top, left });\n    return null;\n  }\n\n  componentDidMount() {\n    if (!this._canvas.current) {\n      return console.warn(\"missing canvas element\");\n    }\n    const { worldviewContext } = this.state;\n    worldviewContext.initialize(this._canvas.current);\n    // trigger rendering in children that require camera to be present, e.g. Text component\n    this.setState({}); //eslint-disable-line\n    // call paint to set the correct viewportWidth and viewportHeight for camera so non-regl components\n    // such as Text can get the correct screen coordinates for the first render\n    worldviewContext.paint();\n  }\n\n  componentWillUnmount() {\n    if (this._tick) {\n      cancelAnimationFrame(this._tick);\n    }\n    this.state.worldviewContext.destroy();\n  }\n\n  componentDidUpdate() {\n    const { worldviewContext } = this.state;\n    // update internal cameraState\n    if (this.props.cameraState) {\n      worldviewContext.cameraStore.setCameraState(this.props.cameraState);\n    }\n    worldviewContext.onDirty();\n  }\n\n  focus() {\n    if (this._cameraListener.current) {\n      this._cameraListener.current.focus();\n    }\n  }\n\n  handleOffscreenMouseEvent = (e: SyntheticMouseEvent<HTMLCanvasElement>, mouseEventName: MouseEventEnum) => {\n    if (mouseEventName === \"onDoubleClick\") {\n      this._onDoubleClick(e, true);\n    } else if (mouseEventName === \"onMouseDown\") {\n      this._onMouseDown(e, true);\n    } else if (mouseEventName === \"onMouseMove\") {\n      this._onMouseMove(e, true);\n    } else if (mouseEventName === \"onMouseUp\") {\n      this._onMouseUp(e, true);\n    }\n  };\n\n  _onDoubleClick = (e: SyntheticMouseEvent<HTMLCanvasElement>, fromOffscreenTarget: boolean) => {\n    this._onMouseInteraction(e, \"onDoubleClick\", fromOffscreenTarget);\n  };\n\n  _onMouseDown = (e: SyntheticMouseEvent<HTMLCanvasElement>, fromOffscreenTarget: boolean) => {\n    this._dragStartPos = { x: e.clientX, y: e.clientY };\n    this._onMouseInteraction(e, \"onMouseDown\", fromOffscreenTarget);\n  };\n\n  _onMouseMove = (e: SyntheticMouseEvent<HTMLCanvasElement>, fromOffscreenTarget: boolean) => {\n    this._onMouseInteraction(e, \"onMouseMove\", fromOffscreenTarget);\n  };\n\n  _onMouseUp = (e: SyntheticMouseEvent<HTMLCanvasElement>, fromOffscreenTarget: boolean) => {\n    this._onMouseInteraction(e, \"onMouseUp\", fromOffscreenTarget);\n    const { _dragStartPos } = this;\n    if (_dragStartPos) {\n      const deltaX = e.clientX - _dragStartPos.x;\n      const deltaY = e.clientY - _dragStartPos.y;\n      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n      if (distance < DEFAULT_MOUSE_CLICK_RADIUS) {\n        this._onMouseInteraction(e, \"onClick\", fromOffscreenTarget);\n      }\n      this._dragStartPos = null;\n    }\n  };\n\n  _onMouseInteraction = (\n    e: SyntheticMouseEvent<HTMLCanvasElement>,\n    mouseEventName: MouseEventEnum,\n    fromOffscreenTarget: boolean\n  ) => {\n    const { worldviewContext } = this.state;\n    const worldviewHandler = this.props[mouseEventName];\n\n    // When working with offscreen canvases, window is not defined and the target\n    // might not be a valid HTMLElement. If so, we can asume any event coming\n    // from an offscreen canvas already has a relevant target.\n    if (!fromOffscreenTarget && (!(e.target instanceof window.HTMLElement) || e.button !== 0)) {\n      return;\n    }\n\n    // $FlowFixMe: Because of `fromOffscreenTarget`, target might not be an actual HTMLElement instance but still needs to implement `getBoundingClientRect`\n    const { top: clientTop, left: clientLeft } = e.target.getBoundingClientRect();\n    const { clientX, clientY } = e;\n\n    const canvasX = clientX - clientLeft;\n    const canvasY = clientY - clientTop;\n    const ray = worldviewContext.raycast(canvasX, canvasY);\n    if (!ray) {\n      return;\n    }\n\n    // Rendering the hitmap is expensive, so we should disable it for some events.\n    // If 'disableHitmapForEvents' is provided, we ignore any events contained in that property.\n    // Otherwise, we ignore 'onMouseMove' events by default unless 'hitmapOnMouseMove' is 'true'\n    const { hitmapOnMouseMove, disableHitmapForEvents = hitmapOnMouseMove ? [] : [\"onMouseMove\"] } = this.props;\n    if (disableHitmapForEvents.includes(mouseEventName)) {\n      if (worldviewHandler) {\n        return handleWorldviewMouseInteraction([], ray, e, worldviewHandler);\n      }\n      return;\n    }\n\n    // reading hitmap is async so we need to persist the event to use later in the event handler\n    (e: any).persist();\n    worldviewContext\n      .readHitmap(canvasX, canvasY, !!this.props.enableStackedObjectEvents, this.props.maxStackedObjectCount)\n      .then((mouseEventsWithCommands) => {\n        const mouseEventsByCommand: Map<Command<any>, Array<MouseEventObject>> = aggregate(mouseEventsWithCommands);\n        for (const [command, mouseEvents] of mouseEventsByCommand.entries()) {\n          command.handleMouseEvent(mouseEvents, ray, e, mouseEventName);\n          if (e.isPropagationStopped()) {\n            break;\n          }\n        }\n        if (worldviewHandler && !e.isPropagationStopped()) {\n          const mouseEvents = mouseEventsWithCommands.map(([mouseEventObject]) => mouseEventObject);\n          handleWorldviewMouseInteraction(mouseEvents, ray, e, worldviewHandler);\n        }\n      })\n      .catch((e) => {\n        console.error(e);\n      });\n  };\n\n  _renderDebug() {\n    const { worldviewContext } = this.state;\n    const initializedData = worldviewContext.initializedData;\n\n    if (getNodeEnv() === \"production\" || !initializedData) {\n      return null;\n    }\n    const { regl } = initializedData;\n    const mem = window.performance.memory;\n    const style = {\n      bottom: 5,\n      right: 10,\n      width: 200,\n      position: \"absolute\",\n      backgroundColor: \"rgba(0, 0, 0, 0.5)\",\n      color: \"white\",\n      fontFamily: \"monospace\",\n      fontSize: 10,\n    };\n    const { counters, reglCommandObjects } = worldviewContext;\n    const data = mapValues(counters, (val) => `${val} ms`);\n    data[\"draw calls\"] = reglCommandObjects.reduce((total, cmd) => total + cmd.stats.count, 0);\n    if (mem) {\n      data[\"heap used\"] = `${((mem.usedJSHeapSize / mem.jsHeapSizeLimit) * 100).toFixed(3)}%`;\n    }\n\n    Object.assign(data, pickBy(regl.stats, (val) => typeof val === \"number\" && val !== 0));\n    if (regl.stats.bufferCount > 1000) {\n      throw new Error(\"Memory leak: Buffer count > 1000.\");\n    }\n\n    const rows = Object.keys(data).map((key) => {\n      return (\n        <tr key={key} style={{ backgroundColor: \"transparent\", border: \"none\" }}>\n          <td style={{ paddingRight: 10, border: \"none\" }}>{key}</td>\n          <td style={{ width: \"100%\", border: \"none\" }}>{data[key]}</td>\n        </tr>\n      );\n    });\n    return (\n      <table style={style}>\n        <tbody>{rows}</tbody>\n      </table>\n    );\n  }\n\n  render() {\n    const {\n      width,\n      height,\n      showDebug,\n      keyMap,\n      shiftKeys,\n      style,\n      cameraState,\n      onCameraStateChange,\n      resolutionScale,\n      canvas,\n    } = this.props;\n    const { worldviewContext } = this.state;\n    // If we are supplied controlled camera state and no onCameraStateChange callback\n    // then there is a 'fixed' camera from outside of worldview itself.\n    const isFixedCamera = cameraState && !onCameraStateChange;\n    const canvasScale = resolutionScale || 1;\n    const canvasHtml = canvas ? null : (\n      <React.Fragment>\n        <canvas\n          style={{ width, height, maxWidth: \"100%\", maxHeight: \"100%\" }}\n          width={width * canvasScale}\n          height={height * canvasScale}\n          ref={this._canvas}\n          onMouseUp={this._onMouseUp}\n          onMouseDown={this._onMouseDown}\n          onDoubleClick={this._onDoubleClick}\n          onMouseMove={this._onMouseMove}\n        />\n        {showDebug && this._renderDebug()}\n      </React.Fragment>\n    );\n\n    return (\n      <div style={{ position: \"relative\", overflow: \"hidden\", ...style }}>\n        {/* skip rendering CameraListener if Worldview has a fixed camera */}\n        {isFixedCamera ? (\n          canvasHtml\n        ) : (\n          <CameraListener\n            cameraStore={worldviewContext.cameraStore}\n            keyMap={keyMap}\n            shiftKeys={shiftKeys}\n            ref={(el) => (this._cameraListener.current = el)}>\n            {canvasHtml}\n          </CameraListener>\n        )}\n        {worldviewContext.initializedData && (\n          <WorldviewReactContext.Provider value={worldviewContext}>\n            {this.props.children}\n          </WorldviewReactContext.Provider>\n        )}\n      </div>\n    );\n  }\n}\n\nexport type Props = $Diff<React.ElementConfig<typeof WorldviewBase>, Dimensions>;\n\nconst Worldview = React.forwardRef<Props, _>((props: Props, ref) => (\n  <ContainerDimensions>\n    {({ width, height, left, top }) => (\n      <WorldviewBase width={width} height={height} left={left} top={top} ref={ref} {...props} />\n    )}\n  </ContainerDimensions>\n));\n\nWorldview.displayName = \"Worldview\";\n\nexport default Worldview;\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport type { Point } from \"../types\";\n\n// a single min/max value\nclass Bound {\n  min: number;\n  max: number;\n\n  constructor() {\n    this.min = Number.MAX_SAFE_INTEGER;\n    this.max = Number.MIN_SAFE_INTEGER;\n  }\n  // update the bound based on a value\n  update(value: number) {\n    this.min = Math.min(this.min, value);\n    this.max = Math.max(this.max, value);\n  }\n}\n\n// represents x, y, and z min & max bounds for a 3d scene\nexport default class Bounds {\n  x: Bound;\n  y: Bound;\n  z: Bound;\n\n  constructor() {\n    this.x = new Bound();\n    this.y = new Bound();\n    this.z = new Bound();\n  }\n\n  // update the bounds based on a point\n  update(point: Point) {\n    this.x.update(point.x);\n    this.y.update(point.y);\n    this.z.update(point.z);\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { mat3 } from \"gl-matrix\";\n\nimport type { Vec3, Vec4 } from \"../types\";\n\nconst scratch = [0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n// gl-matrix clone of three.js Euler.setFromQuaternion\n// assumes default XYZ order\nexport default function eulerFromQuaternion(out: number[], q: Vec4): Vec3 {\n  const m = mat3.fromQuat(scratch, q);\n  const m11 = m[0], m12 = m[3], m13 = m[6]; // prettier-ignore\n  const             m22 = m[4], m23 = m[7]; // prettier-ignore\n  const             m32 = m[5], m33 = m[8]; // prettier-ignore\n\n  out[1] = Math.asin(m13 < -1 ? -1 : m13 > 1 ? 1 : m13);\n  if (Math.abs(m13) < 0.99999) {\n    out[0] = Math.atan2(-m23, m33);\n    out[2] = Math.atan2(-m12, m11);\n  } else {\n    out[0] = Math.atan2(m32, m22);\n    out[2] = 0;\n  }\n  return (out: any);\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport type { ReglCommand, Vec3 } from \"../types\";\nimport { withPose, pointToVec3, defaultBlend, defaultDepth, shouldConvert, colorBuffer } from \"./commandUtils\";\n\n// Creates a regl command factory which will render any geometry described by point positions\n// and elements (indexes into the array of positions), and apply the object's pose, scale, and color to it.\nexport default (positions: Vec3[], elements: Vec3[]) => (regl: any): ReglCommand => {\n  const vertexArray = Float32Array.from([].concat(...positions));\n\n  if (elements.some((face) => face.some((i) => i < 0 || i >= 1 << 16))) {\n    throw new Error(\"Element index out of bounds for Uint16\");\n  }\n  const elementsArray = Uint16Array.from([].concat(...elements));\n\n  const buff = regl.buffer({\n    // tell the gpu this buffer's contents will change frequently\n    usage: \"dynamic\",\n    data: [],\n  });\n  const colorBuff = colorBuffer(regl);\n\n  return withPose({\n    vert: `\n    precision mediump float;\n    attribute vec3 point;\n    attribute vec3 offset;\n    attribute vec4 color;\n    uniform mat4 projection, view;\n    uniform vec3 scale;\n    varying vec4 vColor;\n\n    #WITH_POSE\n\n    void main () {\n      vec3 p = applyPose(scale * point + offset);\n      vColor = color;\n      gl_Position = projection * view * vec4(p, 1);\n    }\n    `,\n    frag: `\n    precision mediump float;\n    varying vec4 vColor;\n    void main () {\n      gl_FragColor = vColor;\n    }`,\n\n    attributes: {\n      point: vertexArray,\n      color: (context, props) => {\n        return colorBuff(props.color, props.colors, props.points ? props.points.length : 1);\n      },\n\n      offset: (context, props) => {\n        const points = shouldConvert(props.points) ? props.points.map(pointToVec3) : props.points || [0, 0, 0];\n        return {\n          buffer: buff({\n            usage: \"dynamic\",\n            data: points,\n          }),\n          divisor: 1,\n        };\n      },\n    },\n\n    elements: elementsArray,\n\n    depth: defaultDepth,\n    blend: defaultBlend,\n\n    uniforms: {\n      scale: (context, props) => (shouldConvert(props.scale) ? pointToVec3(props.scale) : props.scale),\n    },\n\n    count: elementsArray.length,\n\n    instances: (context, props) => (props.points ? props.points.length : 1),\n  });\n};\n","// @flow\n//\n//  Copyright (c) 2021-present, Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport draco3d from \"draco3d\";\n\nconst decodeGeometry = (draco, decoder, json, binary, dracoCompression) => {\n  const { bufferView: bufferViewIndex } = dracoCompression;\n  const bufferView = json.bufferViews[bufferViewIndex];\n  const buffer = new draco.DecoderBuffer();\n  const data = new Int8Array(binary.buffer, binary.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);\n  buffer.Init(data, bufferView.byteLength);\n  const geometryType = decoder.GetEncodedGeometryType(buffer);\n\n  let dracoGeometry;\n  let status;\n  if (geometryType === draco.TRIANGULAR_MESH) {\n    dracoGeometry = new draco.Mesh();\n    status = decoder.DecodeBufferToMesh(buffer, dracoGeometry);\n  } else if (geometryType === draco.POINT_CLOUD) {\n    dracoGeometry = new draco.PointCloud();\n    status = decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);\n  } else {\n    const errorMsg = \"Error: Unknown geometry type.\";\n    console.error(errorMsg);\n  }\n\n  if (!status || !dracoGeometry || !status.ok() || dracoGeometry?.ptr === 0) {\n    throw new Error(`Decoding failed: ${status ? status.error_msg() : \"unknown error\"}`);\n  }\n\n  draco.destroy(buffer);\n\n  return dracoGeometry;\n};\n\nconst decodeAttributes = (draco, decoder, dracoGeometry, attributes) => {\n  const accessors = [];\n  for (const attributeName in attributes) {\n    const attributeId = attributes[attributeName];\n    const attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeId);\n\n    const numComponents = attribute.num_components();\n    const numPoints = dracoGeometry.num_points();\n    const numValues = numPoints * numComponents;\n    const attributeType = Float32Array;\n    const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;\n    const dataType = draco.DT_FLOAT32;\n\n    // eslint-disable-next-line no-underscore-dangle\n    const ptr = draco._malloc(byteLength);\n\n    decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr);\n    const array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice();\n\n    // eslint-disable-next-line no-underscore-dangle\n    draco._free(ptr);\n\n    accessors.push(array);\n  }\n  return accessors;\n};\n\nconst decodeIndices = (draco, decoder, dracoGeometry) => {\n  const numFaces = dracoGeometry.num_faces();\n  const numIndices = numFaces * 3;\n  const byteLength = numIndices * 4;\n\n  // eslint-disable-next-line no-underscore-dangle\n  const ptr = draco._malloc(byteLength);\n\n  decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);\n  const indices = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice();\n\n  // eslint-disable-next-line no-underscore-dangle\n  draco._free(ptr);\n\n  return indices;\n};\n\nconst decodePrimitive = (draco, decoder, json, binary, primitive) => {\n  const { extensions = {} } = primitive;\n  const dracoCompression = extensions.KHR_draco_mesh_compression;\n  if (!dracoCompression) {\n    return;\n  }\n\n  const dracoGeometry = decodeGeometry(draco, decoder, json, binary, dracoCompression);\n\n  dracoCompression.accessors = [];\n\n  const { attributes } = dracoCompression;\n  dracoCompression.accessors.push(...decodeAttributes(draco, decoder, dracoGeometry, attributes));\n\n  dracoCompression.accessors.push(decodeIndices(draco, decoder, dracoGeometry));\n\n  draco.destroy(dracoGeometry);\n};\n\nasync function createDracoModule(): any {\n  // npm does not work correctly when we try to use `import` to fetch the wasm module,\n  // so we need to use `require` here instead. In any case, `draco3dWasm` does not\n  // hold the actual wasm module, but the path to it, which we use in the `locateFile`\n  // function below.\n  const draco3dWasm = require(\"draco3d/draco_decoder.wasm\");\n  return draco3d.createDecoderModule({\n    locateFile: () => {\n      return draco3dWasm;\n    },\n  });\n}\n\nexport default async function decodeCompressedGLB(json: any, binary: DataView) {\n  const { extensionsRequired = [] } = json;\n  if (!extensionsRequired.includes(\"KHR_draco_mesh_compression\")) {\n    // this model does not uses Draco compression\n    return;\n  }\n\n  const draco = await createDracoModule();\n  const decoder = new draco.Decoder();\n\n  json.meshes.forEach((mesh) => {\n    mesh.primitives.forEach((primitive) => {\n      decodePrimitive(draco, decoder, json, binary, primitive);\n    });\n  });\n\n  draco.destroy(decoder);\n}\n","// @flow\n\n//  Copyright (c) 2019-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport decodeCompressedGLB from \"./draco\";\n\ntype TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Uint32Array | Float32Array;\n\nexport type GLBModel = {\n  json: Object,\n  accessors?: TypedArray[],\n  images?: ImageBitmap[],\n};\n\n// Parse a GLB file: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0\n//\n// Returns an object containing the raw json data as well as parsed images (Image) and\n// accessors (TypedArray).\nexport default async function parseGLB(arrayBuffer: ArrayBuffer): Promise<GLBModel> {\n  const data = new DataView(arrayBuffer);\n  let offset = 0;\n\n  function readUint32() {\n    const value = data.getUint32(offset, true);\n    offset += 4;\n    return value;\n  }\n\n  // magic header\n  const magic = readUint32();\n  if (magic !== 0x46546c67) {\n    throw new Error(`incorrect magic value 0x${magic.toString(16)}`);\n  }\n\n  // Binary glTF version\n  const version = readUint32();\n  if (version !== 2) {\n    throw new Error(`incorrect version ${version}`);\n  }\n\n  // total file length\n  const totalLength = readUint32();\n  if (totalLength !== data.byteLength) {\n    throw new Error(`length ${totalLength} doesn't match response length ${data.byteLength}`);\n  }\n\n  function findNextChunkOfType(type) {\n    do {\n      const chunkLength = readUint32();\n      const chunkType = readUint32();\n      if (chunkType === type) {\n        const chunkData = new DataView(data.buffer, offset, chunkLength);\n        offset += chunkLength;\n        return chunkData;\n      }\n      offset += chunkLength;\n    } while (offset < totalLength);\n  }\n\n  const jsonData = findNextChunkOfType(/* JSON */ 0x4e4f534a);\n  if (!jsonData) {\n    throw new Error(\"no JSON chunk found\");\n  }\n\n  const json = JSON.parse(new TextDecoder().decode(jsonData));\n\n  const binary = findNextChunkOfType(/* BIN */ 0x004e4942);\n  if (!binary) {\n    return { json };\n  }\n\n  if (json.buffers[0].uri !== undefined) {\n    throw new Error(\"expected GLB-stored buffer\");\n  }\n\n  // create a TypedArray for each accessor\n  const accessors = json.accessors.map((accessorInfo) => {\n    if (accessorInfo.bufferView == null) {\n      // This accessor has no associated bufferView, which happens when the mesh\n      // contains compressed data. This is not an error, though. So, we return\n      // null and let the mesh handles data access later.\n      return null;\n    }\n\n    let arrayType;\n    // prettier-ignore\n    switch (accessorInfo.componentType) {\n      case WebGLRenderingContext.BYTE: arrayType = Int8Array; break;\n      case WebGLRenderingContext.UNSIGNED_BYTE: arrayType = Uint8Array; break;\n      case WebGLRenderingContext.SHORT: arrayType = Int16Array; break;\n      case WebGLRenderingContext.UNSIGNED_SHORT: arrayType = Uint16Array; break;\n      case WebGLRenderingContext.UNSIGNED_INT: arrayType = Uint32Array; break;\n      case WebGLRenderingContext.FLOAT: arrayType = Float32Array; break;\n      default:\n        throw new Error(`unrecognized componentType ${accessorInfo.componentType}`);\n    }\n    let numComponents;\n    // prettier-ignore\n    switch (accessorInfo.type) {\n      case \"SCALAR\": numComponents = 1; break;\n      case \"VEC2\": numComponents = 2; break;\n      case \"VEC3\": numComponents = 3; break;\n      case \"VEC4\": numComponents = 4; break;\n      case \"MAT2\": numComponents = 4; break;\n      case \"MAT3\": numComponents = 9; break;\n      case \"MAT4\": numComponents = 16; break;\n      default:\n        throw new Error(`unrecognized type ${accessorInfo.type}`);\n    }\n    const bufferView = json.bufferViews[accessorInfo.bufferView];\n    if (bufferView.buffer !== 0) {\n      throw new Error(\"only GLB-stored buffers are supported\");\n    }\n    if (bufferView.byteLength % arrayType.BYTES_PER_ELEMENT !== 0) {\n      throw new Error(\"bufferView.byteLength mismatch\");\n    }\n    return new arrayType(\n      binary.buffer,\n      binary.byteOffset + (bufferView.byteOffset || 0) + (accessorInfo.byteOffset || 0),\n      accessorInfo.count * numComponents\n    );\n  });\n\n  await decodeCompressedGLB(json, binary);\n\n  // load embedded images\n  const images =\n    json.images &&\n    (await Promise.all(\n      json.images.map((imgInfo) => {\n        const bufferView = json.bufferViews[imgInfo.bufferView];\n        const data = new DataView(binary.buffer, binary.byteOffset + bufferView.byteOffset, bufferView.byteLength);\n        return self.createImageBitmap(new Blob([data], { type: imgInfo.mimeType }));\n      })\n    ));\n\n  return { json, accessors, images };\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport type { AssignNextColorsFn, MouseEventObject } from \"../types\";\n\nfunction nonInstancedGetChildrenForHitmapFromSingleProp<T: any>(\n  prop: T,\n  assignNextColors: AssignNextColorsFn,\n  excludedObjects: MouseEventObject[],\n  useOriginalMarkerProp: boolean = false\n): ?T {\n  // The marker that we send to event callbacks.\n  const eventCallbackMarker = useOriginalMarkerProp ? prop.originalMarker : prop;\n  if (excludedObjects.some(({ object }) => object === eventCallbackMarker)) {\n    return null;\n  }\n  const hitmapProp = { ...prop };\n  const [hitmapColor] = assignNextColors(eventCallbackMarker, 1);\n  hitmapProp.color = hitmapColor;\n  if (hitmapProp.colors && hitmapProp.points && hitmapProp.points.length) {\n    hitmapProp.colors = new Array(hitmapProp.points.length).fill(hitmapColor);\n  }\n  return hitmapProp;\n}\n\nexport const nonInstancedGetChildrenForHitmap = <T: any>(\n  props: T,\n  assignNextColors: AssignNextColorsFn,\n  excludedObjects: MouseEventObject[]\n): ?T => {\n  if (Array.isArray(props)) {\n    return props\n      .map((prop) => nonInstancedGetChildrenForHitmapFromSingleProp(prop, assignNextColors, excludedObjects))\n      .filter(Boolean);\n  }\n  return nonInstancedGetChildrenForHitmapFromSingleProp(props, assignNextColors, excludedObjects);\n};\n\n// Almost identical to nonInstancedGetChildrenForHitmap, but instead the object passed to event callbacks is the object\n// at `prop.originalMarker`, not just `prop`.\nexport const getChildrenForHitmapWithOriginalMarker = <T: any>(\n  props: T,\n  assignNextColors: AssignNextColorsFn,\n  excludedObjects: MouseEventObject[]\n) => {\n  if (Array.isArray(props)) {\n    return props\n      .map((prop) => nonInstancedGetChildrenForHitmapFromSingleProp(prop, assignNextColors, excludedObjects, true))\n      .filter(Boolean);\n  }\n  return nonInstancedGetChildrenForHitmapFromSingleProp(props, assignNextColors, excludedObjects, true);\n};\n\nfunction instancedGetChildrenForHitmapFromSingleProp<T: any>(\n  prop: T,\n  assignNextColors: AssignNextColorsFn,\n  excludedObjects: MouseEventObject[],\n  pointCountPerInstance\n): ?T {\n  const matchedExcludedObjects = excludedObjects.filter(({ object, instanceIndex }) => object === prop);\n  const filteredIndices = matchedExcludedObjects\n    .map(({ object, instanceIndex }) => instanceIndex)\n    .filter((instanceIndex) => typeof instanceIndex === \"number\");\n  const hitmapProp = { ...prop };\n  const instanceCount = (hitmapProp.points && Math.ceil(hitmapProp.points.length / pointCountPerInstance)) || 1;\n  // This returns 1 color per instance.\n  const idColors = assignNextColors(prop, instanceCount);\n  const startColor = idColors[0];\n  // We have to map these instance colors to `pointCountPerInstance` number of points\n  if (hitmapProp.points && hitmapProp.points.length) {\n    const allColors = new Array(hitmapProp.points.length).fill().map(() => startColor);\n    for (let i = 0; i < instanceCount; i++) {\n      for (let j = 0; j < pointCountPerInstance; j++) {\n        const idx = i * pointCountPerInstance + j;\n        if (idx < allColors.length) {\n          allColors[idx] = idColors[i];\n        }\n      }\n    }\n    hitmapProp.colors = allColors;\n    if (filteredIndices.length) {\n      hitmapProp.points = hitmapProp.points.filter(\n        (_, index) => !filteredIndices.includes(Math.floor(index / pointCountPerInstance))\n      );\n      hitmapProp.colors = hitmapProp.colors.filter(\n        (_, index) => !filteredIndices.includes(Math.floor(index / pointCountPerInstance))\n      );\n    } else if (matchedExcludedObjects.length) {\n      // if we don't have instance indices, just filter out the whole object.\n      return null;\n    }\n  } else {\n    hitmapProp.color = startColor;\n    if (matchedExcludedObjects.length) {\n      return null;\n    }\n  }\n  return hitmapProp;\n}\n\nexport const createInstancedGetChildrenForHitmap = (pointCountPerInstance: number) => <T: any>(\n  props: T,\n  assignNextColors: AssignNextColorsFn,\n  excludedObjects: MouseEventObject[]\n): ?T => {\n  if (Array.isArray(props)) {\n    return props\n      .map((prop) =>\n        instancedGetChildrenForHitmapFromSingleProp(prop, assignNextColors, excludedObjects, pointCountPerInstance)\n      )\n      .filter(Boolean);\n  }\n  return instancedGetChildrenForHitmapFromSingleProp(props, assignNextColors, excludedObjects, pointCountPerInstance);\n};\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport memoize from \"lodash/memoize\";\n\nimport type { DepthState, BlendState } from \"../types\";\nimport { defaultReglDepth, defaultReglBlend } from \"./commandUtils\";\n\nconst withRenderStateOverrides = (command: any) => (regl: any) => {\n  // Generate the render command once\n  const reglCommand = command(regl);\n\n  // Use memoization to avoid generating multiple render commands for the same render states\n  // for the same render states\n  const memoizedRender = memoize(\n    (props: { depth: DepthState, blend: BlendState }) => {\n      const { depth, blend } = props;\n      return regl({ ...reglCommand, depth, blend });\n    },\n    (...args) => JSON.stringify(args)\n  );\n\n  const renderElement = (props) => {\n    // Get curstom render states from the given marker. Some commands, like <Arrows />\n    // will use the originalMarker property instead. If no custom render states\n    // are present, use either the ones provided in the command or the default ones. We do\n    // need to provide valid objects in order to make sure the hitmap works correctly.\n    const depth = props.depth || props.originalMarker?.depth || reglCommand.depth || defaultReglDepth;\n    const blend = props.blend || props.originalMarker?.blend || reglCommand.blend || defaultReglBlend;\n    memoizedRender({ depth, blend })(props);\n  };\n\n  return (props: any) => {\n    if (Array.isArray(props)) {\n      props.forEach(renderElement);\n    } else {\n      renderElement(props);\n    }\n  };\n};\n\nexport default withRenderStateOverrides;\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { Cylinder } from \"../types\";\nimport fromGeometry from \"../utils/fromGeometry\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport withRenderStateOverrides from \"../utils/withRenderStateOverrides\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\nexport function createCylinderGeometry(numSegments: number, cone: boolean) {\n  // \"poles\" are the centers of top/bottom faces\n  const northPole = [0, 0, 0.5];\n  const southPole = [0, 0, -0.5];\n\n  const points = [northPole, southPole];\n\n  // Keep side faces separate from top/bottom to improve appearance for semi-transparent colors.\n  // We don't have a good approach to transparency right now but this is a small improvement over mixing the faces.\n  const sideFaces = [];\n  const endCapFaces = [];\n\n  for (let i = 0; i < numSegments; i++) {\n    const theta = (2 * Math.PI * i) / numSegments;\n    const x = 0.5 * Math.cos(theta);\n    const y = 0.5 * Math.sin(theta);\n    points.push([x, y, 0.5], [x, y, -0.5]);\n\n    const bottomLeftPt = points.length - 1;\n    const topRightPt = cone ? 0 : i + 1 === numSegments ? 2 : points.length;\n    const bottomRightPt = i + 1 === numSegments ? 3 : points.length + 1;\n    sideFaces.push([bottomLeftPt, topRightPt, bottomRightPt]);\n    endCapFaces.push([bottomLeftPt, bottomRightPt, 1]);\n    if (!cone) {\n      const topLeftPt = points.length - 2;\n      sideFaces.push([topLeftPt, bottomLeftPt, topRightPt]);\n      endCapFaces.push([topLeftPt, topRightPt, 0]);\n    }\n  }\n  return { points, sideFaces, endCapFaces };\n}\n\nconst { points, sideFaces, endCapFaces } = createCylinderGeometry(30, false);\n\nexport const cylinders = withRenderStateOverrides(fromGeometry(points, sideFaces.concat(endCapFaces)));\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\nexport default function Cylinders(props: { ...CommonCommandProps, children: Cylinder[] }) {\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={cylinders} />;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { Cone } from \"../types\";\nimport fromGeometry from \"../utils/fromGeometry\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport withRenderStateOverrides from \"../utils/withRenderStateOverrides\";\nimport Command, { type CommonCommandProps } from \"./Command\";\nimport { createCylinderGeometry } from \"./Cylinders\";\n\nconst { points, sideFaces, endCapFaces } = createCylinderGeometry(30, true);\n\nexport const cones = withRenderStateOverrides(fromGeometry(points, sideFaces.concat(endCapFaces)));\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\nexport default function Cones(props: { ...CommonCommandProps, children: Cone[] }) {\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={cones} />;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { vec3, quat } from \"gl-matrix\";\nimport omit from \"lodash/omit\";\nimport React, { memo, Fragment } from \"react\";\n\nimport type { Arrow } from \"../types\";\nimport { pointToVec3, vec3ToPoint, orientationToVec4, vec4ToOrientation } from \"../utils/commandUtils\";\nimport { getChildrenForHitmapWithOriginalMarker } from \"../utils/getChildrenForHitmapDefaults\";\nimport type { CommonCommandProps } from \"./Command\";\nimport Cones, { cones } from \"./Cones\";\nimport Cylinders, { cylinders } from \"./Cylinders\";\n\nconst UNIT_X_VECTOR = Object.freeze([0, 0, 1]);\n\ntype Props = {\n  ...CommonCommandProps,\n  children: Arrow[],\n};\n\nconst generateArrowPrimitives = (markers: Arrow[]) => {\n  const cylinders = [];\n  const cones = [];\n\n  for (const marker of markers) {\n    let shaftWidthX;\n    let shaftWidthY;\n    let shaftLength;\n    let headWidthX;\n    let headWidthY;\n    let headLength;\n\n    let basePosition;\n    let orientation;\n    let dir;\n    if (marker.points && marker.points.length === 2) {\n      const [start, end] = marker.points;\n      basePosition = [start.x, start.y, start.z];\n      const tipPosition = [end.x, end.y, end.z];\n      const length = vec3.distance(basePosition, tipPosition);\n\n      dir = vec3.subtract([0, 0, 0], tipPosition, basePosition);\n      vec3.normalize(dir, dir);\n      orientation = quat.rotationTo([0, 0, 0, 0], UNIT_X_VECTOR, dir);\n\n      headWidthX = headWidthY = marker.scale.y;\n      headLength = marker.scale.z || length * 0.3;\n      shaftWidthX = shaftWidthY = marker.scale.x;\n      shaftLength = length - headLength;\n    } else {\n      basePosition = pointToVec3(marker.pose.position);\n      orientation = orientationToVec4(marker.pose.orientation);\n      quat.rotateY(orientation, orientation, Math.PI / 2);\n      dir = vec3.transformQuat([0, 0, 0], UNIT_X_VECTOR, orientation);\n\n      shaftWidthX = marker.scale.y || 1;\n      shaftWidthY = marker.scale.z || 1;\n      headWidthX = 2 * shaftWidthX;\n      headWidthY = 2 * shaftWidthY;\n\n      // these magic numbers taken from\n      // https://github.com/ros-visualization/rviz/blob/57325fa075893de70f234f4676cdd08b411858ff/src/rviz/default_plugin/markers/arrow_marker.cpp#L113\n      headLength = 0.23 * (marker.scale.x || 1);\n      shaftLength = 0.77 * (marker.scale.x || 1);\n    }\n\n    const shaftPosition = vec3.scaleAndAdd([0, 0, 0], basePosition, dir, shaftLength / 2);\n    const headPosition = vec3.scaleAndAdd([0, 0, 0], basePosition, dir, shaftLength + headLength / 2);\n\n    cylinders.push({\n      // Set the original marker so we can use it in mouse events\n      originalMarker: marker,\n      scale: { x: shaftWidthX, y: shaftWidthY, z: shaftLength },\n      color: marker.color,\n      pose: {\n        position: vec3ToPoint(shaftPosition),\n        orientation: vec4ToOrientation(orientation),\n      },\n    });\n    cones.push({\n      // Set the original marker so we can use it in mouse events\n      originalMarker: marker,\n      scale: { x: headWidthX, y: headWidthY, z: headLength },\n      color: marker.color,\n      pose: {\n        position: vec3ToPoint(headPosition),\n        orientation: vec4ToOrientation(orientation),\n      },\n    });\n  }\n\n  return {\n    cones,\n    cylinders,\n  };\n};\n\nexport const makeArrowsCommand = () => (regl: any) => {\n  const cylindersCommand = cylinders(regl);\n  const conesCommand = cones(regl);\n  return (props: any) => {\n    const { cylinders: cylinderPrimitives, cones: conePrimitives } = generateArrowPrimitives(props);\n    cylindersCommand(cylinderPrimitives);\n    conesCommand(conePrimitives);\n  };\n};\n\nfunction Arrows(props: Props) {\n  const passedProps = omit(props, \"children\");\n  const { cylinders, cones } = generateArrowPrimitives(props.children);\n  return (\n    <Fragment>\n      <Cylinders getChildrenForHitmap={getChildrenForHitmapWithOriginalMarker} {...passedProps}>\n        {cylinders}\n      </Cylinders>\n      <Cones getChildrenForHitmap={getChildrenForHitmapWithOriginalMarker} {...passedProps}>\n        {cones}\n      </Cones>\n    </Fragment>\n  );\n}\n\nexport default memo<Props>(Arrows);\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport flatten from \"lodash/flatten\";\nimport memoize from \"lodash/memoize\";\nimport * as React from \"react\";\n\nimport type { Line, Vec4, Color, Pose, DepthState, BlendState } from \"../types\";\nimport {\n  defaultBlend,\n  withPose,\n  toRGBA,\n  shouldConvert,\n  pointToVec3,\n  defaultReglDepth,\n  defaultReglBlend,\n} from \"../utils/commandUtils\";\nimport { nonInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\n/*\nTriangle-based line drawing.\n\n4 points (a strip of 2 triangles) are drawn for each segment of the line using instanced arrays.\nEach of the 4 points has a distinct \"point type\" which informs how the input point is offset to\nyield the vertices of the triangle.\n\nPassing the input point as an attribute with {divisor: 1} tells GL to use each point for 1 instance,\nthen move on to the next point -- something like `points.map((p) => draw2Triangles(p))`.\n\n4 attributes are used so the vertex shader can see 4 input points at once (reading from the same\nbuffer with different offsets). This is because the positions of the TL/BL endpoints depend on the\nangle ABC, and the positions of TR/BR depend on the angle BCD.\n\nRoughly the segment looks like:\n\n     TL   -   -   -  .TR\n      |          ,.-' |\nA - - B - - -,.-' - - C - - D\n      |  ,.-'         |\n     BL-' -   -   -   BR\n\nWhen two adjacent segments form an obtuse angle, we draw a miter join:\n\n                      TR/TL.\n                 , '   _/|   ' .\n             , '     _/  |       ' .\n         , '       _/    C           ' .\n     , '         _/      |               ' .\n   TL          _/        |        ______,----'TR\n    \\        _/       ,BR/BL.----'            /\n     B     _/    , '          ' .            D\n      \\  _/ , '                   ' .       /\n       BL'                            ' . BR\n\nBut when the angle gets too sharp, we switch to a \"fold\" join, where the two segments overlap at\nthe corner:\n\n        ,TR/BL---C--BR/TL\n       ,    |.\\__  ,     .\n      ,     | .  \\,_      .\n     ,      |  . ,  \\_     .\n    ,       |   ,     \\__   .\n   ,        |  , .       \\__ .\n  TL._      | ,   .        _.TR\n      'B._  |,     .   _.C'\n          'BL       BR'\n\n(A regular bevel join without any overlaps is harder to achieve without artifacts in the sharp-angle\nedge cases.)\n\n*/\n\nconst FLOAT_BYTES = Float32Array.BYTES_PER_ELEMENT;\nconst POINT_BYTES = 3 * FLOAT_BYTES;\nconst DEFAULT_MONOCHROME_COLOR = [1, 1, 1, 0.2];\n\n// The four points forming the triangles' vertices.\n// Values do not matter, they just need to be distinct.\nconst POINT_TYPES = { BL: 0, TR: 1, BR: 2, TL: 3 };\nconst VERTICES_PER_INSTANCE = Object.keys(POINT_TYPES).length;\n\nconst vert = `\nprecision mediump float;\n\nattribute float pointType;\n\n// per-instance attributes\nattribute vec4 colorB;\nattribute vec4 colorC;\nattribute vec3 positionA;\nattribute vec3 positionB;\nattribute vec3 positionC;\nattribute vec3 positionD;\n// per-instance pose attributes\nattribute vec3 posePosition;\nattribute vec4 poseRotation;\n\nuniform mat4 projection, view;\nuniform float viewportWidth;\nuniform float viewportHeight;\nuniform float alpha;\nuniform float thickness;\nuniform bool joined;\nuniform bool scaleInvariant;\n\nvarying vec4 vColor;\n\n${Object.keys(POINT_TYPES)\n  .map((k) => `const float POINT_${k} = ${POINT_TYPES[k]}.0;`)\n  .join(\"\\n\")}\n\n#WITH_POSE\n\nvec3 applyPoseInstance(vec3 point, vec4 rotation, vec3 position) {\n  // rotate the point and then add the position of the pose\n  // this function is defined in WITH_POSE\n  return rotate(point, rotation) + position;\n}\n\nvec2 rotateCCW(vec2 v) {\n  return vec2(-v.y, v.x);\n}\n\nvec2 normalizeOrZero(vec2 v) {\n  return length(v) < 0.00001 ? vec2(0, 0) : normalize(v);\n}\n\nvoid setPosition(vec4 proj, vec2 offset) {\n  gl_Position = proj;\n\n  offset *= thickness / 2.;\n\n  if (scaleInvariant) {\n    // The given thickness is a number of pixels on screen. Divide x by width/2 and\n    // y by height/2 so that they correspond to pixel distances when scaled from clip space to NDC.\n    offset.x /= viewportWidth / 2.0;\n    offset.y /= viewportHeight / 2.0;\n    // Compensate for automatic division by w\n    offset *= proj.w;\n  } else {\n    // The line thickness should be scaled the same way the camera scales other distances.\n    // projection[0].xyz is the result of projecting a unit x-vector, so its length represents\n    // how much distances are scaled by the camera projection.\n    offset *= length(projection[0].xyz);\n    offset.y *= viewportWidth / viewportHeight;\n  }\n\n  gl_Position.xy += offset;\n}\n\nvoid main () {\n  bool isStart = positionA == positionB;\n  bool isEnd = positionC == positionD;\n  bool isLeft = (pointType == POINT_TL || pointType == POINT_BL);\n  bool isTop = (pointType == POINT_TL || pointType == POINT_TR);\n  bool isEndpoint = isLeft ? isStart : isEnd;\n\n  float scale = isTop ? 1. : -1.;\n\n  mat4 projView = projection * view;\n  vec4 projA = projView * vec4(applyPose(applyPoseInstance(positionA, poseRotation, posePosition)), 1);\n  vec4 projB = projView * vec4(applyPose(applyPoseInstance(positionB, poseRotation, posePosition)), 1);\n  vec4 projC = projView * vec4(applyPose(applyPoseInstance(positionC, poseRotation, posePosition)), 1);\n  vec4 projD = projView * vec4(applyPose(applyPoseInstance(positionD, poseRotation, posePosition)), 1);\n\n  vec2 aspectVec = vec2(viewportWidth / viewportHeight, 1.0);\n  vec2 screenA = projA.xy / projA.w * aspectVec;\n  vec2 screenB = projB.xy / projB.w * aspectVec;\n  vec2 screenC = projC.xy / projC.w * aspectVec;\n  vec2 screenD = projD.xy / projD.w * aspectVec;\n\n  vec2 dirAB = normalizeOrZero(screenB - screenA);\n  vec2 dirBC = normalizeOrZero(screenC - screenB);\n  vec2 dirCD = normalizeOrZero(screenD - screenC);\n\n  vec2 perpAB = rotateCCW(dirAB); // vector perpendicular to AB\n  vec2 perpBC = rotateCCW(dirBC); // vector perpendicular to BC\n\n  vColor = isLeft ? colorB : colorC;\n  vColor.a *= alpha;\n\n  vec4 proj = isLeft ? projB : projC;\n\n  // simple case: non-joined line list\n  if (!joined || isEndpoint) {\n    setPosition(proj, scale * perpBC);\n    return;\n  }\n\n  // clamp to prevent rounding errors from breaking the sqrt()s below\n  float cosB = clamp(-dot(dirAB, dirBC), -1., 1.);\n  float cosC = clamp(-dot(dirBC, dirCD), -1., 1.);\n\n  bool tooSharpB = cosB > 0.01;\n  bool tooSharpC = cosC > 0.01;\n  bool tooSharp = isLeft ? tooSharpB : tooSharpC;\n\n  bool turningRightB = dot(dirAB, rotateCCW(dirBC)) > 0.;\n  bool turningRightC = dot(dirBC, rotateCCW(dirCD)) > 0.;\n  bool turningRight = isLeft ? turningRightB : turningRightC;\n\n  if (tooSharp) {\n    // \"fold join\"\n    vec2 perp = isLeft ? perpAB : perpBC;\n    vec2 dir = isLeft ? dirAB : dirBC;\n    float scalePerp = isLeft ? -1. : 1.;\n    float scaleDir = (turningRight == isLeft) ? 1. : -1.;\n    float tanHalfB = sqrt((1. - cosB) / (1. + cosB));\n    float tanHalfC = sqrt((1. - cosC) / (1. + cosC));\n    float tanHalf = isLeft ? tanHalfB : tanHalfC;\n    setPosition(proj, scale * (scalePerp * perp + scaleDir * dir * tanHalf));\n  } else {\n    // miter join\n    vec2 bisectorB = rotateCCW(normalize(dirAB + dirBC)); // angle bisector of ABC\n    vec2 bisectorC = rotateCCW(normalize(dirBC + dirCD)); // angle bisector of BCD\n    vec2 bisector = isLeft ? bisectorB : bisectorC;\n    float sinHalfB = sqrt((1. - cosB) / 2.);\n    float sinHalfC = sqrt((1. - cosC) / 2.);\n    float sinHalf = isLeft ? sinHalfB : sinHalfC;\n    setPosition(proj, scale * bisector / sinHalf);\n  }\n}\n`;\n\nconst frag = `\nprecision mediump float;\nvarying vec4 vColor;\nvoid main () {\n  gl_FragColor = vColor;\n}\n`;\n\nfunction pointsEqual(a, b) {\n  const [ax, ay, az] = shouldConvert(a) ? pointToVec3(a) : a;\n  const [bx, by, bz] = shouldConvert(b) ? pointToVec3(b) : b;\n  return ax === bx && ay === by && az === bz;\n}\n\nexport const lines = (regl: any) => {\n  if (!regl) {\n    throw new Error(\"Invalid regl instance\");\n  }\n\n  // The point type attribute, reused for each instance\n  const pointTypeBuffer = regl.buffer({\n    type: \"uint16\",\n    usage: \"static\",\n    data: [POINT_TYPES.TL, POINT_TYPES.BL, POINT_TYPES.TR, POINT_TYPES.BR],\n  });\n  const debugColorBuffer = regl.buffer({\n    type: \"float\",\n    usage: \"static\",\n    data: [\n      [0, 1, 1, 1], // cyan\n      [1, 0, 0, 1], // red\n      [0, 1, 0, 1], // green\n      [1, 0, 1, 1], // magenta\n    ],\n  });\n  // The pose position and rotation buffers contain the identity position/rotation, for use when we don't have instanced\n  // poses.\n  const defaultPosePositionBuffer = regl.buffer({\n    type: \"float\",\n    usage: \"static\",\n    data: flatten(new Array(VERTICES_PER_INSTANCE).fill([0, 0, 0])),\n  });\n  const defaultPoseRotationBuffer = regl.buffer({\n    type: \"float\",\n    usage: \"static\",\n    // Rotation array identity is [x: 0, y: 0, z: 0, w: 1]\n    data: flatten(new Array(VERTICES_PER_INSTANCE).fill([0, 0, 0, 1])),\n  });\n\n  // The buffers used for input position & color data\n  const colorBuffer = regl.buffer({ type: \"float\" });\n\n  // All invocations of the vertex shader share data from the positions buffer, but with different\n  // offsets. However, when offset and stride are combined, 3 or 4 attributes reading from the same\n  // buffer produces incorrect results on certain Lenovo hardware running Ubuntu. As a workaround,\n  // we upload the same data into two buffers and have only two attributes reading from each buffer.\n  const positionBuffer1 = regl.buffer({ type: \"float\" });\n  const positionBuffer2 = regl.buffer({ type: \"float\" });\n\n  const posePositionBuffer = regl.buffer({ type: \"float\" });\n  const poseRotationBuffer = regl.buffer({ type: \"float\" });\n\n  const command = regl(\n    withPose({\n      vert,\n      frag,\n      blend: defaultBlend,\n      uniforms: {\n        thickness: regl.prop(\"scale.x\"),\n        viewportWidth: regl.context(\"viewportWidth\"),\n        viewportHeight: regl.context(\"viewportHeight\"),\n        alpha: regl.prop(\"alpha\"),\n        joined: regl.prop(\"joined\"),\n        scaleInvariant: regl.prop(\"scaleInvariant\"),\n      },\n      attributes: {\n        pointType: pointTypeBuffer,\n        colorB: (context, { joined, monochrome, debug }) => ({\n          buffer: debug ? debugColorBuffer : colorBuffer,\n          offset: 0,\n          stride: (joined || monochrome || debug ? 1 : 2) * 4 * FLOAT_BYTES,\n          divisor: monochrome || debug ? 0 : 1,\n        }),\n        colorC: (context, { joined, monochrome, debug }) => ({\n          buffer: debug ? debugColorBuffer : colorBuffer,\n          offset: monochrome || debug ? 0 : 4 * FLOAT_BYTES,\n          stride: (joined || monochrome || debug ? 1 : 2) * 4 * FLOAT_BYTES,\n          divisor: monochrome || debug ? 0 : 1,\n        }),\n        positionA: (context, { joined }) => ({\n          buffer: positionBuffer1,\n          offset: 0,\n          stride: (joined ? 1 : 2) * POINT_BYTES,\n          divisor: 1,\n        }),\n        positionB: (context, { joined }) => ({\n          buffer: positionBuffer1,\n          offset: POINT_BYTES,\n          stride: (joined ? 1 : 2) * POINT_BYTES,\n          divisor: 1,\n        }),\n        positionC: (context, { joined }) => ({\n          buffer: positionBuffer2,\n          offset: 2 * POINT_BYTES,\n          stride: (joined ? 1 : 2) * POINT_BYTES,\n          divisor: 1,\n        }),\n        positionD: (context, { joined }) => ({\n          buffer: positionBuffer2,\n          offset: 3 * POINT_BYTES,\n          stride: (joined ? 1 : 2) * POINT_BYTES,\n          divisor: 1,\n        }),\n        posePosition: (context, { hasInstancedPoses }) => ({\n          buffer: hasInstancedPoses ? posePositionBuffer : defaultPosePositionBuffer,\n          divisor: hasInstancedPoses ? 1 : 0,\n        }),\n        poseRotation: (context, { hasInstancedPoses }) => ({\n          buffer: hasInstancedPoses ? poseRotationBuffer : defaultPoseRotationBuffer,\n          divisor: hasInstancedPoses ? 1 : 0,\n        }),\n      },\n      count: VERTICES_PER_INSTANCE,\n      instances: regl.prop(\"instances\"),\n      primitive: regl.prop(\"primitive\"),\n    })\n  );\n\n  let colorArray = new Float32Array(VERTICES_PER_INSTANCE * 4);\n  let pointArray = new Float32Array(0);\n  let allocatedPoints = 0;\n  let positionArray = new Float32Array(0);\n  let rotationArray = new Float32Array(0);\n\n  function fillPointArray(points: any[], alreadyClosed: boolean, shouldClose: boolean): Float32Array {\n    const numTotalPoints = points.length + (shouldClose ? 3 : 2);\n    if (allocatedPoints < numTotalPoints) {\n      pointArray = new Float32Array(numTotalPoints * 3);\n      allocatedPoints = numTotalPoints;\n    }\n    points.forEach((point, i) => {\n      const [x, y, z] = shouldConvert(point) ? pointToVec3(point) : point;\n      const off = 3 + i * 3;\n      pointArray[off + 0] = x;\n      pointArray[off + 1] = y;\n      pointArray[off + 2] = z;\n    });\n\n    // The \"prior\" point (A) and \"next\" point (D) need to be set when rendering the first & last\n    // segments, so we copy data from the last point(s) to the beginning of the array, and from the\n    // first point(s) to the end of the array.\n    const n = numTotalPoints * 3;\n    if (alreadyClosed) {\n      // First and last points already match; \"prior\" should be the second-to-last\n      // and \"next\" should be the second.\n      pointArray.copyWithin(0, n - 9, n - 6);\n      pointArray.copyWithin(n - 3, 6, 9);\n    } else if (shouldClose) {\n      // First point is being reused after last point; first *two* points need to be copied at the end\n      pointArray.copyWithin(0, n - 9, n - 6);\n      pointArray.copyWithin(n - 6, 3, 9);\n    } else {\n      // Endpoints are separate; just duplicate first & last points, resulting in square-looking endcaps\n      pointArray.copyWithin(0, 3, 6);\n      pointArray.copyWithin(n - 3, n - 6, n - 3);\n    }\n    return pointArray.subarray(0, n);\n  }\n\n  function fillPoseArrays(\n    instances: number,\n    poses: Pose[]\n  ): { positionData: Float32Array, rotationData: Float32Array } {\n    if (positionArray.length < instances * 3) {\n      positionArray = new Float32Array(instances * 3);\n      rotationArray = new Float32Array(instances * 4);\n    }\n    for (let index = 0; index < poses.length; index++) {\n      const positionOffset = index * 3;\n      const rotationOffset = index * 4;\n      const { position, orientation: r } = poses[index];\n      const convertedPosition = Array.isArray(position) ? position : pointToVec3(position);\n      positionArray[positionOffset + 0] = convertedPosition[0];\n      positionArray[positionOffset + 1] = convertedPosition[1];\n      positionArray[positionOffset + 2] = convertedPosition[2];\n\n      const convertedRotation = Array.isArray(r) ? r : [r.x, r.y, r.z, r.w];\n      rotationArray[rotationOffset + 0] = convertedRotation[0];\n      rotationArray[rotationOffset + 1] = convertedRotation[1];\n      rotationArray[rotationOffset + 2] = convertedRotation[2];\n      rotationArray[rotationOffset + 3] = convertedRotation[3];\n    }\n    return {\n      positionData: positionArray.subarray(0, instances * 3),\n      rotationData: rotationArray.subarray(0, instances * 4),\n    };\n  }\n\n  function convertColors(colors: any): Vec4[] {\n    return shouldConvert(colors) ? colors.map(toRGBA) : colors;\n  }\n\n  function fillColorArray(\n    color: ?Color | ?Vec4,\n    colors: ?((Color | Vec4)[]),\n    monochrome: boolean,\n    shouldClose: boolean\n  ): Float32Array {\n    if (monochrome) {\n      if (colorArray.length < VERTICES_PER_INSTANCE * 4) {\n        colorArray = new Float32Array(VERTICES_PER_INSTANCE * 4);\n      }\n      const monochromeColor = color || DEFAULT_MONOCHROME_COLOR;\n      const [convertedMonochromeColor] = convertColors([monochromeColor]);\n      const [r, g, b, a] = convertedMonochromeColor;\n      for (let index = 0; index < VERTICES_PER_INSTANCE; index++) {\n        const offset = index * 4;\n        colorArray[offset + 0] = r;\n        colorArray[offset + 1] = g;\n        colorArray[offset + 2] = b;\n        colorArray[offset + 3] = a;\n      }\n      return colorArray.subarray(0, VERTICES_PER_INSTANCE * 4);\n    } else if (colors) {\n      const length = shouldClose ? colors.length + 1 : colors.length;\n      if (colorArray.length < length * 4) {\n        colorArray = new Float32Array(length * 4);\n      }\n      const convertedColors = convertColors(colors);\n      for (let index = 0; index < convertedColors.length; index++) {\n        const offset = index * 4;\n        const [r, g, b, a] = convertedColors[index];\n        colorArray[offset + 0] = r;\n        colorArray[offset + 1] = g;\n        colorArray[offset + 2] = b;\n        colorArray[offset + 3] = a;\n      }\n\n      if (shouldClose) {\n        const [r, g, b, a] = convertedColors[0];\n        const lastIndex = length - 1;\n        colorArray[lastIndex * 4 + 0] = r;\n        colorArray[lastIndex * 4 + 1] = g;\n        colorArray[lastIndex * 4 + 2] = b;\n        colorArray[lastIndex * 4 + 3] = a;\n      }\n      return colorArray.subarray(0, length * 4);\n    }\n    throw new Error(\"Impossible: !monochrome implies !!colors.\");\n  }\n\n  // Create a new render function based on rendering settings\n  // Memoization is required in order to prevent creating too many functions\n  // that use the same arguments, potentially leading to memory leaks.\n  const memoizedRender = memoize(\n    (props: { depth?: DepthState, blend?: BlendState }) => {\n      const { depth = defaultReglDepth, blend = defaultReglBlend } = props;\n      return regl({ depth, blend });\n    },\n    (...args) => JSON.stringify(args)\n  );\n\n  // Disable depth for debug rendering (so lines stay visible)\n  const render = (props: { debug?: boolean, depth?: DepthState, blend?: BlendState }, commands: any) => {\n    const { debug } = props;\n    if (debug) {\n      memoizedRender({ depth: { enable: false } })(commands);\n    } else {\n      memoizedRender(props)(commands);\n    }\n  };\n\n  // Render one line list/strip\n  function renderLine(props) {\n    const { debug, primitive = \"lines\", scaleInvariant = false, depth, blend } = props;\n    const numInputPoints = props.points.length;\n\n    if (numInputPoints < 2) {\n      return;\n    }\n\n    const alreadyClosed = numInputPoints > 2 && pointsEqual(props.points[0], props.points[numInputPoints - 1]);\n    // whether the first point needs to be duplicated after the last point\n    const shouldClose = !alreadyClosed && props.closed;\n\n    const pointData = fillPointArray(props.points, alreadyClosed, shouldClose);\n    positionBuffer1({ data: pointData, usage: \"dynamic\" });\n    positionBuffer2({ data: pointData, usage: \"dynamic\" });\n\n    const monochrome = !(props.colors && props.colors.length);\n    const colorData = fillColorArray(props.color, props.colors, monochrome, shouldClose);\n    colorBuffer({ data: colorData, usage: \"dynamic\" });\n\n    const joined = primitive === \"line strip\";\n    const effectiveNumPoints = numInputPoints + (shouldClose ? 1 : 0);\n    const instances = joined ? effectiveNumPoints - 1 : Math.floor(effectiveNumPoints / 2);\n\n    // fill instanced pose buffers\n    const { poses } = props;\n    const hasInstancedPoses = !!poses && poses.length > 0;\n    if (hasInstancedPoses && poses) {\n      if (instances !== poses.length) {\n        console.error(`Expected ${instances} poses but given ${poses.length} poses: will result in webgl error.`);\n        return;\n      }\n      const { positionData, rotationData } = fillPoseArrays(instances, poses);\n      posePositionBuffer({ data: positionData, usage: \"dynamic\" });\n      poseRotationBuffer({ data: rotationData, usage: \"dynamic\" });\n    }\n\n    render({ debug, depth, blend }, () => {\n      // Use Object.assign because it's actually faster than babel's object spread polyfill.\n      command(\n        Object.assign({}, props, {\n          joined,\n          primitive: \"triangle strip\",\n          alpha: debug ? 0.2 : 1,\n          monochrome,\n          instances,\n          scaleInvariant,\n          hasInstancedPoses,\n        })\n      );\n      if (debug) {\n        command(\n          Object.assign({}, props, {\n            joined,\n            primitive: \"line strip\",\n            alpha: 1,\n            monochrome,\n            instances,\n            scaleInvariant,\n            hasInstancedPoses,\n          })\n        );\n      }\n    });\n  }\n\n  return (inProps: any) => {\n    if (Array.isArray(inProps)) {\n      inProps.forEach(renderLine);\n    } else {\n      renderLine(inProps);\n    }\n  };\n};\n\nexport default function Lines(props: { ...CommonCommandProps, children: Line[] }) {\n  return <Command getChildrenForHitmap={nonInstancedGetChildrenForHitmap} {...props} reglCommand={lines} />;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React from \"react\";\n\nimport type { Point, Vec3, Line } from \"../types\";\nimport Lines from \"./Lines\";\n\nconst pointToVec3 = (p: Vec3): Point => ({\n  x: p[0],\n  y: p[1],\n  z: p[2],\n});\n\nconst scale = 100;\nconst x = 1 * scale;\nconst xAxisPoints = [[-x, 0, 0], [x, 0, 0]].map(pointToVec3);\nconst yAxisPoints = [[0, -100, 0], [0, 100, 0]].map(pointToVec3);\nconst zAxisPoints = [[0, 0, -100], [0, 0, 100]].map(pointToVec3);\nconst pose = {\n  orientation: { x: 0, y: 0, z: 0, w: 0 },\n  position: { x: 0, y: 0, z: 0 },\n};\nconst xAxis = {\n  pose,\n  points: xAxisPoints,\n  scale: { x: 0.5, y: 0.5, z: 0.5 },\n  color: { r: 0.95, g: 0.26, b: 0.4, a: 1 },\n};\nconst yAxis = {\n  pose,\n  points: yAxisPoints,\n  scale: { x: 0.5, y: 0.5, z: 0.5 },\n  color: { r: 0.02, g: 0.82, b: 0.49, a: 1 },\n};\nconst zAxis = {\n  pose,\n  points: zAxisPoints,\n  scale: { x: 0.5, y: 0.5, z: 0.5 },\n  color: { r: 0.11, g: 0.51, b: 0.92, a: 1 },\n};\n\ntype Axis = Line;\n\ntype Props = {\n  children: Axis[],\n};\n\n// Renders lines along the x, y, and z axes; useful for debugging.\nexport default class Axes extends React.Component<Props> {\n  static defaultProps: Props = {\n    children: [xAxis, yAxis, zAxis],\n  };\n\n  render() {\n    return <Lines>{this.props.children}</Lines>;\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { Cube } from \"../types\";\nimport fromGeometry from \"../utils/fromGeometry\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport withRenderStateOverrides from \"../utils/withRenderStateOverrides\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\nexport const cubes = withRenderStateOverrides(\n  fromGeometry(\n    [\n      // bottom face corners\n      [-0.5, -0.5, -0.5],\n      [-0.5, 0.5, -0.5],\n      [0.5, -0.5, -0.5],\n      [0.5, 0.5, -0.5],\n      // top face corners\n      [-0.5, -0.5, 0.5],\n      [-0.5, 0.5, 0.5],\n      [0.5, -0.5, 0.5],\n      [0.5, 0.5, 0.5],\n    ],\n    [\n      // bottom\n      [0, 1, 2],\n      [1, 2, 3],\n      // top\n      [4, 5, 6],\n      [5, 6, 7],\n      // left\n      [0, 2, 4],\n      [2, 4, 6],\n      // right\n      [1, 3, 5],\n      [3, 5, 7],\n      //front\n      [2, 3, 6],\n      [3, 6, 7],\n      //back\n      [0, 1, 4],\n      [1, 4, 5],\n    ]\n  )\n);\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\nexport default function Cubes(props: { ...CommonCommandProps, children: Cube[] }) {\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={cubes} />;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { SphereList } from \"../types\";\nimport fromGeometry from \"../utils/fromGeometry\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport withRenderStateOverrides from \"../utils/withRenderStateOverrides\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\nconst NUM_PARALLELS = 15;\nconst NUM_MERIDIANS = 15;\nconst RADIUS = 0.5;\n\nconst northPole = [0, 0, RADIUS];\nconst southPole = [0, 0, -RADIUS];\nconst points = [northPole, southPole];\nconst faces = [];\n\nfor (let i = 0; i < NUM_PARALLELS; i++) {\n  for (let j = 0; j < NUM_MERIDIANS; j++) {\n    const phi = ((i + 1) / (NUM_PARALLELS + 1)) * Math.PI;\n    const z = RADIUS * Math.cos(phi);\n    const width = RADIUS * Math.sin(phi);\n    const theta = (j * 2 * Math.PI) / NUM_MERIDIANS;\n    const x = width * Math.cos(theta);\n    const y = width * Math.sin(theta);\n    points.push([x, y, z]);\n    if (j > 0) {\n      // connect to previous parallel (or north pole)\n      const prevMeridianPt = i === 0 ? 0 : points.length - 1 - NUM_MERIDIANS;\n      faces.push([points.length - 2, points.length - 1, prevMeridianPt]);\n      if (i > 0) {\n        faces.push([points.length - 2, prevMeridianPt - 1, prevMeridianPt]);\n      }\n    }\n  }\n  // connect to previous parallel (or north pole)\n  const prevMeridianPt = i === 0 ? 0 : points.length - 2 * NUM_MERIDIANS;\n  faces.push([points.length - 1, points.length - NUM_MERIDIANS, prevMeridianPt]);\n  if (i > 0) {\n    faces.push([points.length - 1, points.length - NUM_MERIDIANS - 1, prevMeridianPt]);\n  }\n}\n// connect last parallel to south pole\nfor (let j = 0; j < NUM_MERIDIANS; j++) {\n  const pt = points.length - NUM_MERIDIANS + j;\n  const prevPt = j === 0 ? points.length - 1 : pt - 1;\n  faces.push([pt, prevPt, 1]);\n}\n\nexport const spheres = withRenderStateOverrides(fromGeometry(points, faces));\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\nexport default function Spheres(props: { ...CommonCommandProps, children: SphereList[] }) {\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={spheres} />;\n}\n","// @flow\n\n//  Copyright (c) 2019-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React from \"react\";\n\nimport type { Line, Point, Vec3, Scale, GetChildrenForHitmap, SphereList } from \"../../types\";\nimport { vec4ToRGBA, vec3ToPoint } from \"../../utils/commandUtils\";\nimport Lines from \"../Lines\";\nimport Spheres from \"../Spheres\";\n\nexport function multiplyScale(scale: Scale, factor: number): Scale {\n  return { x: scale.x * factor, y: scale.y * factor, z: scale.z * factor };\n}\n\nexport const DEFAULT_COLOR = [1, 1, 1, 1];\nexport const ACTIVE_POLYGON_COLOR = [0.8, 0, 0.8, 1];\nexport const ACTIVE_POINT_COLOR = [1, 0.2, 1, 1];\nexport const LINE_STRIP = \"line strip\";\nconst POINT_SIZE_FACTOR = 1.3;\nexport const DRAW_SCALE = { x: 0.1, y: 0.1, z: 0.1 };\nexport const DRAW_POINT_SCALE = multiplyScale(DRAW_SCALE, POINT_SIZE_FACTOR);\nexport const HITMAP_SCALE = { x: 0.5, y: 0.5, z: 0.5 };\nexport const HITMAP_POINT_SCALE = multiplyScale(HITMAP_SCALE, POINT_SIZE_FACTOR);\nexport const POSE = {\n  position: { x: 0, y: 0, z: 0 },\n  orientation: { x: 0, y: 0, z: 0, w: 0 },\n};\n\nlet count = 1;\n\nexport class PolygonPoint {\n  id: number;\n  point: Vec3;\n  active: boolean = false;\n\n  constructor(points: Vec3) {\n    this.id = count++;\n    this.point = points;\n  }\n}\n\nexport class Polygon {\n  id: number;\n  name: string;\n  points: PolygonPoint[] = [];\n  active: boolean = false;\n\n  constructor(name: string = \"\") {\n    this.name = name;\n    this.id = count++;\n  }\n}\n\nexport type DrawPolygonType = Polygon;\n\ntype Props = {\n  children: DrawPolygonType[],\n};\n\nconst polygonLinesGetChildrenForHitmap: GetChildrenForHitmap = <T: any>(\n  props: T,\n  assignNextColors,\n  excludedObjects\n) => {\n  // This is almost identical to the default nonInstancedGetChildrenForHitmap, with changes marked.\n  return props\n    .map((prop) => {\n      if (excludedObjects.some(({ object }) => object === prop)) {\n        return null;\n      }\n      const hitmapProp = { ...prop };\n      // Change from original: pass the original marker as a callback object instead of this marker.\n      const [hitmapColor] = assignNextColors(prop.originalMarker, 1);\n      // Change from original: increase scale for hitmap\n      hitmapProp.scale = HITMAP_SCALE;\n\n      hitmapProp.color = hitmapColor;\n      if (hitmapProp.colors && hitmapProp.points && hitmapProp.points.length) {\n        hitmapProp.colors = new Array(hitmapProp.points.length).fill(hitmapColor);\n      }\n      return hitmapProp;\n    })\n    .filter(Boolean);\n};\n\n/**\n * Draw the polygon lines\n */\nclass PolygonLines extends React.Component<Props> {\n  render() {\n    const polygons = this.props.children;\n    const lines: Line[] = [];\n    for (const poly of polygons) {\n      const color = poly.active ? ACTIVE_POLYGON_COLOR : DEFAULT_COLOR;\n      const points: (Point | Vec3)[] = poly.points.map(({ point }) => vec3ToPoint(point));\n\n      lines.push({\n        primitive: LINE_STRIP,\n        pose: POSE,\n        points,\n        scale: DRAW_SCALE,\n        color: vec4ToRGBA(color),\n        originalMarker: poly,\n      });\n    }\n\n    return <Lines getChildrenForHitmap={polygonLinesGetChildrenForHitmap}>{lines}</Lines>;\n  }\n}\n\nconst polygonPointsGetChildrenForHitmap: GetChildrenForHitmap = <T: any>(\n  props: T,\n  assignNextColors,\n  excludedObjects\n) => {\n  // This is similar to the default nonInstancedGetChildrenForHitmap, with changes marked.\n  return props\n    .map((prop) => {\n      if (excludedObjects.some(({ object }) => object === prop)) {\n        return null;\n      }\n      const hitmapProp = { ...prop };\n      // Change from original: assign a non-instanced color to each point color, even though this marker uses\n      // instancing.\n      // This is so that we can have a unique callback object for each point.\n      hitmapProp.colors = hitmapProp.colors.map((color, index) => {\n        return assignNextColors(prop.originalMarkers[index], 1);\n      });\n      // Change from original: increase scale for hitmap\n      hitmapProp.scale = HITMAP_POINT_SCALE;\n      return hitmapProp;\n    })\n    .filter(Boolean);\n};\n\n/**\n * Draw the polygon points at the end of each lines\n */\nclass PolygonPoints extends React.Component<Props> {\n  render() {\n    const polygons = this.props.children;\n    const points = [];\n    const colors = [];\n    const originalMarkers = [];\n\n    for (const poly of polygons) {\n      const color = poly.active ? ACTIVE_POLYGON_COLOR : DEFAULT_COLOR;\n      for (const point of poly.points) {\n        const convertedPoint = vec3ToPoint(point.point);\n        points.push(convertedPoint);\n        colors.push(point.active ? ACTIVE_POINT_COLOR : color);\n        originalMarkers.push(point);\n      }\n    }\n\n    const sphereList: SphereList = {\n      points,\n      colors,\n      pose: POSE,\n      scale: DRAW_POINT_SCALE,\n      originalMarkers,\n    };\n\n    return <Spheres getChildrenForHitmap={polygonPointsGetChildrenForHitmap}>{[sphereList]}</Spheres>;\n  }\n}\n\nexport default function DrawPolygons({ children: polygons = [] }: Props) {\n  if (polygons.length === 0) {\n    return null;\n  }\n\n  return (\n    <React.Fragment>\n      <PolygonLines>{polygons}</PolygonLines>\n      <PolygonPoints>{polygons}</PolygonPoints>\n    </React.Fragment>\n  );\n}\n","// @flow\n\n//  Copyright (c) 2019-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport distance from \"distance-to-line-segment\";\n\nimport type { Vec3, MouseHandler } from \"../../types\";\nimport { PolygonPoint, Polygon } from \"./index\";\n\ntype OptionalZPoint = {\n  x: number,\n  y: number,\n  z?: number,\n};\n\ntype PolygonAddCommand = {\n  points: OptionalZPoint[],\n  name?: string,\n};\n\nfunction areEqual(point1: PolygonPoint, point2: PolygonPoint) {\n  const [x1, y1, z1] = point1.point;\n  const [x2, y2, z2] = point2.point;\n  return x1 === x2 && y1 === y2 && z1 === z2;\n}\n\nfunction isClosed(polygon: Polygon): boolean {\n  const { points } = polygon;\n  for (let i = 0; i < points.length - 1; i++) {\n    if (areEqual(points[i], points[i + 1])) {\n      return true;\n    }\n  }\n  const firstPoint = points[0];\n  const lastPoint = points[points.length - 1];\n  return areEqual(firstPoint, lastPoint);\n}\n\n// Has listeners you can pass to Worldview for mouse interactions\n// internally builds a list of polygons and modifies the polygons\n// based on mouse & keyboard interactions. For now we use mututation internally\n// instead of immutability to keep the number of allocations lower and make\n// the implementation a bit more straightforward\n\nexport default class PolygonBuilder {\n  mouseDown: boolean = false;\n  polygons: Polygon[];\n  onChange: () => void = () => {};\n  activePolygon: ?Polygon;\n  activePoint: ?PolygonPoint;\n  mouseDownPoint: Vec3;\n\n  constructor(polygons: Polygon[] = []) {\n    this.polygons = polygons;\n  }\n\n  isActivePolygonClosed(): boolean {\n    return !!this.activePolygon && isClosed(this.activePolygon);\n  }\n\n  // adds a polygon to the builder, transforming it into the internal representation\n  addPolygon(cmd: PolygonAddCommand): void {\n    const { points, name } = cmd;\n    if (points.length < 3) {\n      return;\n    }\n    // clear any selections\n    this.selectObject();\n\n    const polygon = new Polygon(name);\n    polygon.points = points.map((p) => new PolygonPoint([p.x, p.y, p.z || 0]));\n    if (!isClosed(polygon)) {\n      polygon.points.push(polygon.points[0]);\n    }\n    this.polygons.push(polygon);\n  }\n\n  // push a new point - either adds to the active polygon\n  // or creates a new polygon at this point\n  pushPoint(point: Vec3): void {\n    const { activePolygon } = this;\n    if (activePolygon) {\n      // do not push a point on a closed polygon\n      if (!isClosed(activePolygon)) {\n        const newPoint = new PolygonPoint(point);\n        activePolygon.points.push(newPoint);\n        this.selectObject(newPoint);\n        return;\n      }\n    }\n\n    const polygon = new Polygon();\n    polygon.points.push(new PolygonPoint(point));\n    const floatingPoint = new PolygonPoint(point);\n    polygon.points.push(floatingPoint);\n    this.polygons.push(polygon);\n    this.selectObject(floatingPoint);\n    this.onChange();\n  }\n\n  // updates the active point to the new position\n  updateActivePoint(point: Vec3): void {\n    if (this.activePoint) {\n      this.activePoint.point = point;\n      this.onChange();\n    }\n  }\n\n  // closes the active polygon by either deleting it if\n  // is only 2 points (no \"single sided\" polygons...)\n  // or inserts an 'overlap' point by making the first point\n  // and last point a reference to the same point in the list\n  // this structure of overlap is similar to the structure used by geoJSON\n  // though \"left to right\" ordering is not enforced\n  closeActivePolygon(): void {\n    const polygon = this.activePolygon;\n    if (!polygon) {\n      return;\n    }\n\n    // remove single lines\n    if (polygon.points.length === 2) {\n      this.deletePolygon(polygon);\n    } else {\n      polygon.points.push(polygon.points[0]);\n    }\n    this.onChange();\n  }\n\n  // mouse move handler - should be added to Worldview as a prop\n  onMouseMove: MouseHandler = (e, args) => {\n    // prevent the camera from responding to move if we\n    // have an active object being edited\n    if (this.activePolygon) {\n      e.preventDefault();\n      e.stopPropagation();\n    }\n    //const cursor = e.ctrlKey ? 'crosshair' : '';\n    //document.body.style.cursor = cursor;\n\n    if (!this.mouseDown) {\n      return;\n    }\n    if (!args) {\n      return;\n    }\n\n    // early return to only raycast when mouse moves during interaction\n    if (!this.activePoint && !this.activePolygon) {\n      return;\n    }\n\n    const { ray } = args;\n    const point = ray.planeIntersection([0, 0, 0], [0, 0, 1]);\n    // satisfy flow\n    if (!point) {\n      return;\n    }\n\n    // satisfy flow\n    const { activePolygon } = this;\n\n    if (this.activePoint) {\n      this.updateActivePoint(point);\n    } else if (activePolygon && this.mouseDownPoint) {\n      // move polygon\n      const [pointX, pointY] = point;\n      const [mouseX, mouseY] = this.mouseDownPoint;\n      // figure out how far the mouse has moved\n      const dX = pointX - mouseX;\n      const dY = pointY - mouseY;\n\n      // save the new mouse position as for the next computation\n      this.mouseDownPoint = point;\n\n      // only update the 'overlap' point once\n      const uniquePoints = activePolygon.points.reduce((acc, point) => {\n        if (!acc.includes(point)) {\n          acc.push(point);\n        }\n        return acc;\n      }, []);\n\n      // adjust each point's location\n      for (const polygonPoint of uniquePoints) {\n        const { point } = polygonPoint;\n        point[0] = point[0] + dX;\n        point[1] = point[1] + dY;\n      }\n\n      this.onChange();\n    }\n  };\n\n  // deletes a polygon\n  deletePolygon(polygon: Polygon): void {\n    this.polygons = this.polygons.filter((poly) => poly !== polygon);\n    this.activePolygon = null;\n  }\n\n  // deletes a point in the active polygon\n  // if the point is the 'overlap point' create a new one\n  // also deletes the entire polygon if the polygon becomes a 1-sided polygon\n  deletePoint(point: PolygonPoint): void {\n    const { activePolygon } = this;\n    if (!activePolygon) {\n      return;\n    }\n    const newPoints = activePolygon.points.filter((p) => p.id !== point.id);\n    // if the 'overlap' point is deleted, create a new start/end overlap point\n    if (newPoints.length === activePolygon.points.length - 2) {\n      newPoints.push(newPoints[0]);\n    }\n    activePolygon.points = newPoints;\n    this.activePoint = null;\n    if (activePolygon.points.length < 4) {\n      this.deletePolygon(activePolygon);\n    }\n    this.onChange();\n  }\n\n  // key down handler - to be passed to Worldview as a prop\n  onKeyDown = (e: KeyboardEvent): void => {\n    // only respond to key events if we have a selected polygon\n    const { activePolygon } = this;\n    if (!activePolygon) {\n      return;\n    }\n\n    switch (e.key) {\n      case \"Delete\":\n      case \"Backspace\":\n        if (this.activePoint) {\n          this.deletePoint(this.activePoint);\n        } else {\n          this.deletePolygon(activePolygon);\n        }\n        this.onChange();\n        break;\n      default:\n        break;\n    }\n  };\n\n  // select either a point or polygon by id\n  selectObject(object?: Polygon | PolygonPoint) {\n    // clear out any previously active objects\n    this.activePolygon = null;\n    if (this.activePoint) {\n      this.activePoint.active = false;\n    }\n    this.activePoint = null;\n\n    for (const polygon of this.polygons) {\n      let isActive = polygon === object;\n      polygon.active = isActive;\n      if (isActive) {\n        this.activePolygon = polygon;\n      }\n      for (const point of polygon.points) {\n        if (point === object) {\n          // if a point is selected, activate both it\n          // and the polygon it belongs to\n          this.activePoint = point;\n          point.active = true;\n          polygon.active = true;\n          this.activePolygon = polygon;\n          isActive = true;\n        }\n      }\n    }\n\n    this.onChange();\n  }\n\n  // mouse up handler - to be passed to Worldview as a prop\n  onMouseUp: MouseHandler = (e, args) => {\n    if (!e.ctrlKey) {\n      this.mouseDown = false;\n    }\n  };\n\n  // double click handler - to be passed to Worldview as a prop\n  onDoubleClick: MouseHandler = (e, args) => {\n    // satisfy flow\n    if (!args) {\n      return;\n    }\n    if (!args.objects.length) {\n      return;\n    }\n\n    this.selectObject(args.objects[0].object);\n\n    // if a point was double-clicked, delete it\n    if (this.activePoint) {\n      this.deletePoint(this.activePoint);\n      return;\n    }\n\n    // otherwise insert a new point into the nearest line of the active polygon\n    const { activePolygon } = this;\n\n    // if no polygon is active, don't do anything w/ the double-click\n    if (!activePolygon) {\n      return;\n    }\n\n    let shortestDistance = Number.MAX_SAFE_INTEGER;\n    let shortestIndex = -1;\n    const { ray } = args;\n    const point = ray.planeIntersection([0, 0, 0], [0, 0, 1]);\n    if (!point) {\n      return;\n    }\n    const [px, py] = point;\n\n    // find the closest line segment of the active polygon\n    const { points } = activePolygon;\n    for (let i = 0; i < points.length - 1; i++) {\n      const point1 = points[i];\n      const point2 = points[i + 1];\n      const [x1, y1] = point1.point;\n      const [x2, y2] = point2.point;\n\n      // distance.squared is faster since we don't care about the\n      // actual distance, just which line produces the shortest distance\n      const dist = distance.squared(x1, y1, x2, y2, px, py);\n      if (dist < shortestDistance) {\n        shortestDistance = dist;\n        shortestIndex = i;\n      }\n    }\n\n    // insert a new point in the nearest line\n    if (shortestIndex > -1) {\n      const newPoint = new PolygonPoint(point);\n      activePolygon.points.splice(shortestIndex + 1, 0, newPoint);\n      this.activePoint = newPoint;\n    }\n    this.onChange();\n  };\n\n  // mouse down handler - to be passed to Worldview as a prop\n  onMouseDown: MouseHandler = (e, args) => {\n    if (!args) {\n      return;\n    }\n    const { ray } = args;\n\n    const point = ray.planeIntersection([0, 0, 0], [0, 0, 1]);\n\n    // satisfy flow but raycasting should always work\n    if (!point) {\n      return;\n    }\n\n    const isFirstClick = !this.mouseDown;\n    this.mouseDown = true;\n    this.mouseDownPoint = point;\n    const isCtrlClick = e.ctrlKey;\n\n    // single click or click+drag is for selection & moving\n    if (isFirstClick && !isCtrlClick) {\n      const clickObject = args.objects[0];\n      this.selectObject(clickObject && clickObject.object);\n      return this.onChange();\n    }\n\n    // ctrl+click always inserts a point\n    if (isCtrlClick) {\n      this.pushPoint(point);\n      return this.onChange();\n    }\n\n    // if mouse was down & we have a non-control click, close the active polygon\n    this.closeActivePolygon();\n    return this.onChange();\n  };\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { Regl, TriangleList } from \"../types\";\nimport {\n  defaultBlend,\n  getVertexColors,\n  pointToVec3Array,\n  shouldConvert,\n  toRGBA,\n  withPose,\n} from \"../utils/commandUtils\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport withRenderStateOverrides from \"../utils/withRenderStateOverrides\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\n// TODO(Audrey): default to the actual regl defaults before 1.x release\nconst defaultSingleColorDepth = { enable: true, mask: false };\nconst defaultVetexColorDepth = {\n  enable: true,\n  mask: true,\n  func: \"<=\",\n};\n\nconst singleColor = (regl) =>\n  withPose({\n    primitive: \"triangles\",\n    vert: `\n  precision mediump float;\n\n  attribute vec3 point;\n\n  uniform mat4 projection, view;\n\n  #WITH_POSE\n\n  void main () {\n    vec3 pos = applyPose(point);\n    gl_Position = projection * view * vec4(pos, 1);\n  }\n  `,\n    frag: `\n  precision mediump float;\n  uniform vec4 color;\n  void main () {\n    gl_FragColor = color;\n  }\n  `,\n    attributes: {\n      point: (context, props) => {\n        if (shouldConvert(props.points)) {\n          return pointToVec3Array(props.points);\n        }\n        return props.points;\n      },\n    },\n    uniforms: {\n      color: (context, props) => {\n        if (shouldConvert(props.color)) {\n          return toRGBA(props.color);\n        }\n        return props.color;\n      },\n    },\n    // can pass in { enable: true, depth: false } to turn off depth to prevent flicker\n    // because multiple items are rendered to the same z plane\n    depth: {\n      enable: (context, props) => {\n        return (props.depth && props.depth.enable) || defaultSingleColorDepth.enable;\n      },\n      mask: (context, props) => {\n        return (props.depth && props.depth.mask) || defaultSingleColorDepth.mask;\n      },\n    },\n    blend: defaultBlend,\n\n    count: (context, props) => props.points.length,\n  });\n\nconst vertexColors = (regl) =>\n  withPose({\n    primitive: \"triangles\",\n    vert: `\n  precision mediump float;\n\n  attribute vec3 point;\n  attribute vec4 color;\n\n  uniform mat4 projection, view;\n\n  varying vec4 vColor;\n\n  #WITH_POSE\n\n  void main () {\n    vec3 pos = applyPose(point);\n    vColor = color;\n    gl_Position = projection * view * vec4(pos, 1);\n  }\n  `,\n    frag: `\n  precision mediump float;\n  varying vec4 vColor;\n  void main () {\n    gl_FragColor = vColor;\n  }\n  `,\n    attributes: {\n      point: (context, props) => {\n        if (shouldConvert(props.points)) {\n          return pointToVec3Array(props.points);\n        }\n        return props.points;\n      },\n      color: (context, props) => {\n        if (!props.colors || !props.colors.length) {\n          throw new Error(`Invalid empty or null prop \"colors\" when rendering triangles using vertex colors`);\n        }\n        if (shouldConvert(props.colors)) {\n          return getVertexColors(props);\n        }\n        return props.colors;\n      },\n    },\n\n    depth: {\n      enable: (context, props) => {\n        return (props.depth && props.depth.enable) || defaultVetexColorDepth.enable;\n      },\n      mask: (context, props) => {\n        return (props.depth && props.depth.mask) || defaultVetexColorDepth.mask;\n      },\n    },\n    blend: defaultBlend,\n\n    count: (context, props) => props.points.length,\n  });\n\n// command to render triangle lists optionally supporting vertex colors for each triangle\nconst triangles = (regl: Regl) => {\n  const single = withRenderStateOverrides(singleColor)(regl);\n  const vertex = withRenderStateOverrides(vertexColors)(regl);\n  return (props: any, isHitmap: boolean) => {\n    const items: TriangleList[] = Array.isArray(props) ? props : [props];\n    const singleColorItems = [];\n    const vertexColorItems = [];\n    items.forEach((item) => {\n      // If the item has onlyRenderInHitmap set, only render it in the hitmap.\n      if (isHitmap || !item.onlyRenderInHitmap) {\n        if (item.colors && item.colors.length) {\n          vertexColorItems.push(item);\n        } else {\n          singleColorItems.push(item);\n        }\n      }\n    });\n\n    single(singleColorItems);\n    vertex(vertexColorItems);\n  };\n};\n\nexport const makeTrianglesCommand = () => {\n  return triangles;\n};\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(3);\nexport default function Triangles(props: { ...CommonCommandProps, children: TriangleList[] }) {\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={triangles} />;\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport earcut from \"earcut\";\nimport React from \"react\";\n\nimport type { Vec3, Point, PolygonType } from \"../types\";\nimport { shouldConvert, pointToVec3 } from \"../utils/commandUtils\";\nimport { getChildrenForHitmapWithOriginalMarker } from \"../utils/getChildrenForHitmapDefaults\";\nimport Triangles, { makeTrianglesCommand } from \"./Triangles\";\n\nconst NO_POSE = {\n  position: { x: 0, y: 0, z: 0 },\n  orientation: { x: 0, y: 0, z: 0, w: 0 },\n};\n\nconst DEFAULT_SCALE = { x: 1, y: 1, z: 1 };\n\nfunction flatten3D(points: Vec3[]): Float32Array {\n  const array = new Float32Array(points.length * 3);\n  for (let i = 0; i < points.length; i++) {\n    const [x, y, z] = points[i];\n    array[i * 3] = x;\n    array[i * 3 + 1] = y;\n    array[i * 3 + 2] = z;\n  }\n  return array;\n}\n\nfunction getEarcutPoints(points: Vec3[]): (Vec3 | Point)[] {\n  const flattenedPoints = flatten3D(points);\n  const indices = earcut(flattenedPoints, null, 3);\n  const newPoints = [];\n  for (let i = 0; i < indices.length; i++) {\n    const originalIndex = indices[i];\n    newPoints.push(points[originalIndex]);\n  }\n  return newPoints;\n}\n\ntype Props = {\n  children: PolygonType[],\n};\n\nconst generateTriangles = (polygons: PolygonType[]) => {\n  return polygons.map((poly) => {\n    // $FlowFixMe flow doesn't know how shouldConvert works\n    const points: Vec3[] = shouldConvert(poly.points) ? poly.points.map(pointToVec3) : poly.points;\n    const pose = poly.pose ? poly.pose : NO_POSE;\n    const earcutPoints = getEarcutPoints(points);\n    return {\n      ...poly,\n      points: earcutPoints,\n      pose,\n      scale: DEFAULT_SCALE,\n      originalMarker: poly,\n    };\n  });\n};\n\nexport const makeFilledPolygonsCommand = () => (regl: any) => {\n  const trianglesCommand = makeTrianglesCommand()(regl);\n  return (props: any) => {\n    trianglesCommand(generateTriangles(props), false);\n  };\n};\n\n// command to draw a filled polygon\nfunction FilledPolygons({ children: polygons = [], ...rest }: Props) {\n  const triangles = generateTriangles(polygons);\n\n  // Overwrite the triangle's default getChildrenForHitmap because we want to event as if each triangle is a single\n  // polygon.\n  return (\n    <Triangles getChildrenForHitmap={getChildrenForHitmapWithOriginalMarker} {...rest}>\n      {triangles}\n    </Triangles>\n  );\n}\n\nexport default FilledPolygons;\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React from \"react\";\n\nimport type { Point, CameraCommand, Dimensions, Color, Pose, Scale, Vec4 } from \"../types\";\nimport { getCSSColor, toColor } from \"../utils/commandUtils\";\nimport { type WorldviewContextType } from \"../WorldviewContext\";\nimport WorldviewReactContext from \"../WorldviewReactContext\";\n\nconst BG_COLOR_LIGHT = \"#ffffff\";\nconst BG_COLOR_DARK = \"rgba(0,0,0,0.8)\";\nconst BRIGHTNESS_THRESHOLD = 128;\nconst DEFAULT_TEXT_COLOR = { r: 1, g: 1, b: 1, a: 1 };\nconst DEFAULT_BG_COLOR = { r: 0, g: 0, b: 0, a: 0.8 };\n\nexport type TextMarker = {\n  name?: string,\n  pose: Pose,\n  scale: Scale,\n  color?: Color | Vec4,\n  colors?: (Color | Vec4)[],\n  text: string,\n};\n\nlet cssHasBeenInserted = false;\nfunction insertGlobalCss() {\n  if (cssHasBeenInserted) {\n    return;\n  }\n  const style = document.createElement(\"style\");\n  style.innerHTML = `\n    .regl-worldview-text-wrapper {\n      position: absolute;\n      white-space: nowrap;\n      z-index: 100;\n      pointer-events: none;\n      top: 0;\n      left: 0;\n      will-change: transform;\n    }\n    .regl-worldview-text-inner {\n      position: relative;\n      left: -50%;\n      top: -0.5em;\n      white-space: pre-line;\n    }\n  `;\n  if (document.body) {\n    document.body.appendChild(style);\n  }\n  cssHasBeenInserted = true;\n}\n\nexport function isColorDark({ r, g, b }: Color): boolean {\n  // ITU-R BT.709 https://en.wikipedia.org/wiki/Rec._709\n  // 0.2126 * 255 * r + 0.7152 * 255 * g + 0.0722 * 255 * b\n  const luma = 54.213 * r + 182.376 * g + 18.411 * b;\n  return luma < BRIGHTNESS_THRESHOLD;\n}\n\nfunction isColorEqual(a: Color, b: Color): boolean {\n  return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;\n}\n\nclass TextElement {\n  wrapper = document.createElement(\"span\");\n  _inner = document.createElement(\"span\");\n  _text = document.createTextNode(\"\");\n  // store prev colors to improve perf\n  _prevTextColor: Color = DEFAULT_TEXT_COLOR;\n  _prevBgColor: ?Color = DEFAULT_BG_COLOR;\n  _prevAutoBackgroundColor: ?boolean = null;\n\n  constructor() {\n    insertGlobalCss();\n    this.wrapper.className = \"regl-worldview-text-wrapper\";\n    this._inner.className = \"regl-worldview-text-inner\";\n    this.wrapper.appendChild(this._inner);\n    this._inner.appendChild(this._text);\n    this.wrapper.style.color = getCSSColor(DEFAULT_TEXT_COLOR);\n  }\n\n  update(marker: TextMarker, left: number, top: number, autoBackgroundColor?: boolean) {\n    this.wrapper.style.transform = `translate(${left.toFixed()}px,${top.toFixed()}px)`;\n    const { color, colors = [] } = marker;\n    const hasBgColor = colors.length >= 2;\n    const textColor = toColor(hasBgColor ? colors[0] : color || [0, 0, 0, 1]);\n\n    if (textColor) {\n      const backgroundColor = toColor(colors[1]);\n      if (!isColorEqual(this._prevTextColor, textColor)) {\n        this._prevTextColor = textColor;\n        this.wrapper.style.color = getCSSColor(textColor);\n      }\n\n      if (!autoBackgroundColor && autoBackgroundColor !== this._prevAutoBackgroundColor) {\n        // remove background color if autoBackgroundColor has changed\n        this._inner.style.background = \"transparent\";\n        this._prevBgColor = null;\n      } else {\n        if (\n          autoBackgroundColor &&\n          (!this._prevBgColor || (this._prevBgColor && !isColorEqual(textColor, this._prevBgColor)))\n        ) {\n          // update background color with automatic dark/light color\n          this._prevBgColor = textColor;\n          const isTextColorDark = isColorDark(textColor);\n          const hexBgColor = isTextColorDark ? BG_COLOR_LIGHT : BG_COLOR_DARK;\n          this._inner.style.background = hexBgColor;\n        } else if (hasBgColor && this._prevBgColor && !isColorEqual(backgroundColor, this._prevBgColor)) {\n          // update background color with colors[1] data\n          this._prevBgColor = backgroundColor;\n          this._inner.style.background = getCSSColor(backgroundColor);\n        }\n      }\n    }\n    this._prevAutoBackgroundColor = autoBackgroundColor;\n\n    if (this._text.textContent !== marker.text) {\n      this._text.textContent = marker.text || \"\";\n    }\n  }\n}\n\ntype Props = {\n  children: TextMarker[],\n  autoBackgroundColor?: boolean,\n};\n\n// Render text on a scene using DOM nodes, similar to the Overlay command.\n// Implementation uses manual DOM manipulation to avoid the performance hit from React tree reconciliation.\nexport default class Text extends React.Component<Props> {\n  _context: ?WorldviewContextType;\n  _textComponents: Map<string | TextMarker, TextElement> = new Map();\n  _textContainerRef: { current: HTMLDivElement | null } = React.createRef();\n\n  static defaultProps = {\n    children: [],\n  };\n\n  componentDidMount() {\n    if (this._context) {\n      this._context.registerPaintCallback(this.paint);\n    }\n  }\n\n  componentWillUnmount = () => {\n    if (this._context) {\n      this._context.unregisterPaintCallback(this.paint);\n    }\n  };\n\n  paint = () => {\n    const context = this._context;\n    const textComponents = this._textComponents;\n    const { children: markers, autoBackgroundColor } = this.props;\n    const { current: textContainer } = this._textContainerRef;\n    const initializedData = context && context.initializedData;\n\n    if (!textContainer || !context || !initializedData) {\n      return;\n    }\n    const {\n      dimension,\n      dimension: { width, height },\n    } = context;\n    const { camera } = initializedData;\n\n    const componentsToRemove = new Set(textComponents.keys());\n\n    for (const marker of markers) {\n      const { pose, name } = marker;\n      const { position } = pose;\n      const coord = this.project(position, camera, dimension);\n      if (!coord) {\n        continue;\n      }\n\n      const [left, top] = coord;\n      if (left < -10 || top < -10 || left > width + 10 || top > height + 10) {\n        continue;\n      }\n\n      let el = textComponents.get(name || marker);\n      if (el) {\n        componentsToRemove.delete(name || marker);\n      } else {\n        el = new TextElement();\n        textComponents.set(name || marker, el);\n        textContainer.appendChild(el.wrapper);\n      }\n\n      el.update(marker, left, top, autoBackgroundColor);\n    }\n\n    for (const key of componentsToRemove) {\n      const el = textComponents.get(key);\n      if (!el) {\n        continue;\n      }\n      el.wrapper.remove();\n      textComponents.delete(key);\n    }\n  };\n\n  project = (point: Point, camera: CameraCommand, dimension: Dimensions) => {\n    const vec = [point.x, point.y, point.z];\n    const { left, top, width, height } = dimension;\n    const viewport = [left, top, width, height];\n    return camera.toScreenCoord(viewport, vec);\n  };\n\n  render() {\n    return (\n      <React.Fragment>\n        <div ref={this._textContainerRef} />\n        <WorldviewReactContext.Consumer>\n          {(ctx: ?WorldviewContextType) => {\n            if (ctx) {\n              this._context = ctx;\n            }\n            return null;\n          }}\n        </WorldviewReactContext.Consumer>\n      </React.Fragment>\n    );\n  }\n}\n","// @flow\n\nimport TinySDF from \"@mapbox/tiny-sdf\";\nimport difference from \"lodash/difference\";\nimport memoizeOne from \"memoize-one\";\nimport React, { useState } from \"react\";\n\nimport type { Color } from \"../types\";\nimport { defaultBlend, defaultDepth, toColor } from \"../utils/commandUtils\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport Command, { type CommonCommandProps } from \"./Command\";\nimport { isColorDark, type TextMarker } from \"./Text\";\n\n// HACK: TinySDF doesn't agree with workers. Until support is added, hack this to make it work.\n// TODO(steel): Upstream the fix in memoizedCreateCanvas.\nif (!self.document) {\n  // $FlowFixMe: Flow doesn't know about OffscreenCanvas.\n  self.document = { createElement: () => new OffscreenCanvas(0, 0) };\n}\n\n// The GLText command renders text from a Signed Distance Field texture.\n// There are many external resources about SDFs and text rendering in WebGL, including:\n// https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf\n// https://blog.mapbox.com/drawing-text-with-signed-distance-fields-in-mapbox-gl-b0933af6f817\n// http://hack.chrons.me/opengl-text-rendering/\n// https://stackoverflow.com/questions/25956272/better-quality-text-in-webgl\n//\n// Approach\n// ========\n// Characters from the font are measured using a <canvas> and the SDFs are drawn into a texture up front\n// (and whenever new characters are being rendered). Then one instanced draw call is made with an instance\n// per character which reads from the corresponding place in the texture atlas.\n//\n// Possible future improvements\n// ============================\n// - Allow customization of font style, maybe highlight ranges.\n// - Consider a solid rectangular background instead of an outline. This is challenging because the\n//   instances currently overlap, so there will be z-fighting, but might be possible using the stencil buffer and multiple draw calls.\n// - Somehow support kerning and more advanced font metrics. However, the web font APIs may not\n//   provide support for this. Some font info could be generated/stored offline, possibly including the atlas.\n// - Explore multi-channel SDFs.\n\ntype CharacterLocations = {\n  [char: string]: {|\n    x: number,\n    y: number,\n    width: number,\n    height: number,\n    yOffset: number,\n  |},\n};\n\nexport type GeneratedAtlas = {|\n  charInfo: CharacterLocations,\n  textureWidth: number,\n  textureHeight: number,\n  textureData: Uint8Array,\n|};\n\nexport type AtlasConfig = {|\n  fontSize: number,\n  fontFamily: string,\n  charSet: Set<string>,\n|};\n\ntype TextMarkerProps = TextMarker & {\n  billboard?: ?boolean,\n  highlightedIndices?: Array<number>,\n  highlightColor?: ?Color,\n};\n\ntype GLTextProps = {|\n  autoBackgroundColor?: boolean,\n  scaleInvariantFontSize?: number,\n  resolution?: number,\n  alphabet?: string[],\n  textAtlas?: GeneratedAtlas,\n  borderRadius?: number,\n  paddingScale?: [number, number],\n|};\n\ntype Props = {\n  // $FlowFixMe: flow does not know how to handle the indexed property in CommonCommandProps\n  ...CommonCommandProps,\n  ...GLTextProps,\n  children: $ReadOnlyArray<TextMarkerProps>,\n};\n\n// Font size used in rendering the atlas. This is independent of the `scale` of the rendered text.\nconst MIN_RESOLUTION = 40;\nconst DEFAULT_RESOLUTION = 160;\nconst SDF_RADIUS = 8;\nconst CUTOFF = 0.25;\nconst BUFFER = 10;\n\nconst BG_COLOR_LIGHT = Object.freeze({ r: 1, g: 1, b: 1, a: 1 });\nconst BG_COLOR_DARK = Object.freeze({ r: 0, g: 0, b: 0, a: 1 });\nconst BG_COLOR_TRANSPARENT = Object.freeze({ r: 0, b: 0, g: 0, a: 0 });\n\nconst hashMarkerPosition = (marker: TextMarker): string => {\n  const { x, y, z } = marker.pose.position;\n  // The hash is a simple string with all three components\n  return `x${x}y${y}z${z}`;\n};\n\nconst getMarkerYOffset = (offsets: Map<string, number>, marker: TextMarker) => {\n  return offsets.get(hashMarkerPosition(marker)) || 0;\n};\n\nconst setMarkerYOffset = (offsets: Map<string, number>, marker: TextMarker, yOffset: number) => {\n  offsets.set(hashMarkerPosition(marker), yOffset);\n};\n\n// Build a single font atlas: a texture containing all characters from all atlasConfigs\nexport const generateAtlas = (atlasConfigs: AtlasConfig[], maxAtlasWidth: number): GeneratedAtlas => {\n  // Render and measure each character using tinySDF\n  const sdfDataByChar = {};\n  atlasConfigs.forEach((atlasConfig) => {\n    const { charSet, fontSize, fontFamily } = atlasConfig;\n    const tinySDF = new TinySDF({\n      fontSize, // Font size in pixels\n      fontFamily: fontFamily || \"sans-serif\", // CSS font-family\n      fontWeight: \"normal\", // CSS font-weight\n      fontStyle: \"normal\", // CSS font-style\n      buffer: BUFFER, // Whitespace buffer around a glyph in pixels\n      radius: SDF_RADIUS, // How many pixels around the glyph shape to use for encoding distance\n      cutoff: CUTOFF, // How much of the radius (relative) is used for the inside part of the glyph\n    });\n    charSet.forEach((char) => (sdfDataByChar[char] = tinySDF.draw(char)));\n  });\n\n  // Compute positions for every character in the atlas\n  const charInfo = {};\n\n  let x = 0;\n  let y = 0;\n  let maxHeight = 0;\n  let textureWidth = 0;\n  atlasConfigs.forEach(({ charSet, fontSize }) => {\n    for (const char of charSet) {\n      const { height, width, glyphAdvance, glyphTop, glyphHeight } = sdfDataByChar[char];\n      const lineHeight = height;\n\n      const dx = Math.ceil(width);\n      if (x + dx + glyphAdvance > maxAtlasWidth) {\n        x = 0;\n        y += Math.max(maxHeight, fontSize);\n        maxHeight = lineHeight;\n      }\n      charInfo[char] = { x, y, height: glyphHeight, width: glyphAdvance, yOffset: fontSize - glyphTop };\n      x += dx;\n      textureWidth = Math.max(textureWidth, x);\n      maxHeight = Math.max(maxHeight, lineHeight);\n    }\n  });\n\n  // Copy each character's SDF image into a single texture\n  const textureHeight = y + Math.max(maxHeight);\n  const textureData = new Uint8Array(textureWidth * textureHeight);\n\n  atlasConfigs.forEach(({ charSet }) => {\n    for (const char of charSet) {\n      const { x, y } = charInfo[char];\n      const { data, width, height } = sdfDataByChar[char];\n\n      for (let i = 0; i < height; i++) {\n        for (let j = 0; j < width; j++) {\n          // if this character is near the right edge, we don't actually copy the whole square of data\n          if (x + j < textureWidth) {\n            textureData[textureWidth * (y + i) + x + j] = data[i * width + j];\n          }\n        }\n      }\n    }\n  });\n\n  return {\n    charInfo,\n    textureWidth,\n    textureHeight,\n    textureData,\n  };\n};\n\nconst createMemoizedGenerateAtlasConfigs = () =>\n  memoizeOne((charSet, charSetSize, fontSize, fontFamily) => [\n    {\n      charSet,\n      fontSize,\n      fontFamily,\n    },\n  ]);\n\n// Build a single font atlas: a texture containing all characters and position/size data for each character.\n// We update charSet mutably but monotonically. Pass in the size to invalidate the cache.\nconst createMemoizedGenerateAtlas = () => memoizeOne(generateAtlas);\n\nconst createMemoizedDrawAtlasTexture = () =>\n  memoizeOne((textAtlas: GeneratedAtlas, atlasTexture: any) => {\n    atlasTexture({\n      data: textAtlas.textureData,\n      width: textAtlas.textureWidth,\n      height: textAtlas.textureHeight,\n      format: \"alpha\",\n      wrap: \"clamp\",\n      mag: \"linear\",\n      min: \"linear\",\n    });\n  });\n\nconst vert = `\n  precision mediump float;\n\n  uniform mat4 projection, view, billboardRotation;\n  uniform float fontSize;\n  uniform vec2 atlasSize;\n  uniform bool scaleInvariant;\n  uniform float scaleInvariantSize;\n  uniform float viewportHeight;\n  uniform float viewportWidth;\n  uniform bool isPerspective;\n  uniform float cameraFovY;\n  uniform float cutoff;\n\n  // per-vertex attributes\n  attribute vec2 texCoord;\n  attribute vec2 position;\n\n  // per-instance (character) attributes\n  attribute vec2 srcOffset;\n  attribute vec2 charOffset;\n  attribute vec2 srcSize;\n  attribute vec2 roundedBackgroundSize;\n  attribute vec2 backgroundDestSize;\n  attribute vec2 destOffset;\n\n  // per-marker attributes\n  attribute float billboard;\n  attribute vec2 alignmentOffset;\n  attribute vec3 posePosition;\n  attribute vec3 scale;\n  attribute vec4 textColor;\n  attribute vec4 poseOrientation;\n  attribute vec4 backgroundColor;\n\n  varying vec2 vLineSize;\n\n  varying vec2 vCharBackgroundCoord;\n  varying vec2 vTextAtlasCoord;\n  varying vec4 vTextColor;\n  varying float vBillboard;\n  varying vec2 vCharOffset;\n  varying float vLineBackgroundRadiusRatio;\n  varying vec2 vCharToBackgroundSizeRatio;\n  varying vec2 vLineBackgroundCoord;\n  varying vec4 vBackgroundColor;\n\n  // rotate a 3d point v by a rotation quaternion q\n  // like applyPose(), but we need to use a custom per-instance pose\n  vec3 rotate(vec3 v, vec4 q) {\n    vec3 temp = cross(q.xyz, v) + q.w * v;\n    return v + (2.0 * cross(q.xyz, temp));\n  }\n\n  vec4 computeVertexPosition(vec3 markerPos) {\n    vec3 pos;\n    if (billboard == 1.0) {\n      pos = (billboardRotation * vec4(markerPos, 1.0)).xyz + posePosition;\n    } else {\n      pos = rotate(markerPos, poseOrientation) + posePosition;\n    }\n    return projection * view * vec4(pos, 1.0);\n  }\n\n  void main () {\n    // Scale invariance only works for billboards\n    bool scaleInvariantEnabled = scaleInvariant && billboard == 1.0;\n    vec3 markerSpacePos = vec3((position * backgroundDestSize + destOffset + alignmentOffset) / fontSize, 0);\n\n    if (!scaleInvariantEnabled) {\n      // Apply marker scale only when scale invariance is disabled\n      markerSpacePos *= scale;\n    } else {\n      // If scale invariance is enabled, the text will be rendered at a constant\n      // scale regardless of the zoom level.\n      // The given scaleInvariantSize is in pixels. We need to scale it based on\n      // the current canvas resolution to get the proper dimensions later in NDC\n      float scaleInvariantFactor = scaleInvariantSize / viewportHeight;\n      if (isPerspective) {\n        // When using a perspective projection, the effect is achieved by using\n        // the w-component for scaling, which is obtained by first projecting\n        // the marker position into clip space.\n        gl_Position = computeVertexPosition(markerSpacePos);\n        scaleInvariantFactor *= gl_Position.w;\n        // We also need to take into account the camera's half vertical FOV\n        scaleInvariantFactor *= cameraFovY;\n      } else {\n        // Compute inverse aspect ratio\n        float invAspect = viewportHeight / viewportWidth;\n        // When using orthographic projection, the scaling factor is obtained from\n        // the camera projection itself.\n        // We also need applied the inverse aspect ratio\n        scaleInvariantFactor *= 2.0 * invAspect / length(projection[0].xyz);\n      }\n      // Apply scale invariant factor\n      markerSpacePos *= scaleInvariantFactor;\n    }\n\n    // Compute final vertex position\n    gl_Position = computeVertexPosition(markerSpacePos);\n\n    // Compute additions offsets for the char within the background char within the atlas\n    vec2 charOffsetCoord = vec2(0.5) - ((backgroundDestSize - srcSize) / 2. + charOffset) / backgroundDestSize;\n    vec2 textAtlasCoord = (charOffset + srcOffset + texCoord * backgroundDestSize) / atlasSize;\n\n    // Compute the coords for the full line\n    vec2 lineCoord = (texCoord * backgroundDestSize + destOffset) / roundedBackgroundSize;\n    vLineBackgroundCoord = vec2(lineCoord.x, texCoord.y) * 2. - 1.; // Transform from [0,1] to [-1,1]\n\n    vCharToBackgroundSizeRatio = (srcSize + ${(BUFFER / 2).toFixed(1)}) / backgroundDestSize;\n    vLineBackgroundRadiusRatio = roundedBackgroundSize.y / roundedBackgroundSize.x;\n    \n    vBackgroundColor = backgroundColor;\n    vBillboard = billboard;\n    vCharOffset = charOffsetCoord;\n    vCharBackgroundCoord = texCoord;\n    vTextColor = textColor;\n    vTextAtlasCoord = textAtlasCoord;\n  }\n`;\n\nconst frag = `\n  #extension GL_OES_standard_derivatives : enable\n  precision mediump float;\n\n  uniform bool isHitmap;\n  uniform bool scaleInvariant;\n  uniform float borderRadiusSize;\n  uniform float cutoff;\n  uniform float scaleInvariantSize;\n  uniform sampler2D atlas;\n  uniform float viewportHeight;\n  uniform float viewportWidth;\n  \n  varying float vBillboard;\n  varying float vLineBackgroundRadiusRatio;\n  varying vec2 vCharBackgroundCoord;\n  varying vec2 vCharOffset;\n  varying vec2 vCharToBackgroundSizeRatio;\n  varying vec2 vLineBackgroundCoord;\n  varying vec2 vLineSize;\n  varying vec2 vTextAtlasCoord;\n  varying vec4 vBackgroundColor;\n  varying vec4 vTextColor;\n\n  // fwidth(dist) is used to provide some anti-aliasing. However it's currently only used\n  // when the solid background is enabled, because the alpha blending and\n  // depth test don't work together nicely for partially-transparent pixels.\n  float getAntialisedStep(float dist, float cutoff) {\n    return smoothstep(1. - cutoff - fwidth(dist), 1. - cutoff, dist);\n  }\n\n  float rectangleMask(vec2 uv, vec2 position, vec2 size) {\n    float t = 0.;\n    if ((uv.x > position.x - size.x / 2.) && (uv.x < position.x + size.x / 2.)\n      && (uv.y > position.y - size.y / 2.) && (uv.y < position.y + size.y / 2.)) {\n      t = 1.;\n    }\n    return t;\n  }\n\n  float roundedRectangleMask(vec2 position, vec2 size, float radius) {\n    vec2 q = abs(position) - size + radius;\n    float borderRadius = min(max(q.x,q.y), 0.) + length(max(q, 0.)) - radius;\n    return getAntialisedStep(1. - borderRadius, 0.);\n  }\n\n  void main() {\n    float dist = texture2D(atlas, vTextAtlasCoord).a;\n    float charEdgeStep = getAntialisedStep(dist, cutoff); \n\n    bool skipInterpolate = scaleInvariant && vBillboard == 1. && scaleInvariantSize <= 20.;\n    if (skipInterpolate) {\n      // If scale invariant is enabled and scaleInvariantSize is \"too small\", do not interpolate\n      // the raw distance value since at such small scale, the SDF approach causes some\n      // visual artifacts.\n      // The value used for checking if scaleInvariantSize is \"too small\" is arbitrary and\n      // was defined after some experimentation.\n      charEdgeStep = dist;\n    }\n\n    // Since the background can be bigger than the character from the atlas,\n    // mask out parts of the atlas that fall outside of the character bounds\n    float charMask = rectangleMask(vCharBackgroundCoord, vCharOffset, vCharToBackgroundSizeRatio);\n    vec4 finalColor = mix(vBackgroundColor, vTextColor, charEdgeStep * charMask);\n\n    // Apply rounded corners\n    // Shrink the size of the background by a pixel on each end to help avoid hard edges\n    vec2 pixelEdgeScale = 1. - 2. * vec2(1./viewportWidth, 1./viewportHeight);\n    vec2 backgroundSize = vec2(1., vLineBackgroundRadiusRatio) * pixelEdgeScale;\n    vec2 backgroundPosition = vec2(vLineBackgroundCoord.x, vLineBackgroundCoord.y * vLineBackgroundRadiusRatio);\n    float roundedCornerMask = roundedRectangleMask(backgroundPosition, backgroundSize, borderRadiusSize * vLineBackgroundRadiusRatio);\n    \n    if (!isHitmap) {\n      gl_FragColor = vec4(finalColor.rgb, finalColor.a * roundedCornerMask);\n    } else {\n      gl_FragColor = vTextColor;\n    }\n\n    if (gl_FragColor.a == 0.) {\n      discard;\n    }\n  }\n`;\n\nfunction makeTextCommand(alphabet?: string[]) {\n  // Keep the set of rendered characters around so we don't have to rebuild the font atlas too often.\n  const charSet = new Set(alphabet || []);\n  const memoizedGetAtlasConfig = createMemoizedGenerateAtlasConfigs();\n  const memoizedGenerateAtlas = createMemoizedGenerateAtlas();\n  const memoizedDrawAtlasTexture = createMemoizedDrawAtlasTexture();\n\n  const command = (regl: any) => {\n    if (!regl) {\n      throw new Error(\"Invalid regl instance\");\n    }\n\n    const atlasTexture = regl.texture();\n\n    const drawText = regl({\n      // When using scale invariance, we want the text to be drawn on top\n      // of other elements. This is achieved by disabling depth testing\n      // In addition, make sure the <GLText /> command is the last one\n      // being rendered.\n      depth: {\n        enable: (ctx, props) => (props.scaleInvariant ? false : defaultDepth.enable(ctx, props)),\n        mask: (ctx, props) => (props.scaleInvariant ? false : defaultDepth.mask(ctx, props)),\n      },\n      blend: defaultBlend,\n      primitive: \"triangle strip\",\n      vert,\n      frag,\n      uniforms: {\n        atlas: atlasTexture,\n        atlasSize: () => [atlasTexture.width, atlasTexture.height],\n        fontSize: regl.prop(\"resolution\"),\n        cutoff: CUTOFF,\n        scaleInvariant: regl.prop(\"scaleInvariant\"),\n        scaleInvariantSize: regl.prop(\"scaleInvariantSize\"),\n        borderRadiusSize: regl.prop(\"borderRadiusSize\"),\n        isHitmap: regl.prop(\"isHitmap\"),\n        viewportHeight: regl.context(\"viewportHeight\"),\n        viewportWidth: regl.context(\"viewportWidth\"),\n        isPerspective: regl.context(\"isPerspective\"),\n        cameraFovY: regl.context(\"fovy\"),\n      },\n      instances: regl.prop(\"instances\"),\n      count: 4,\n      attributes: {\n        position: [[0, 0], [0, -1], [1, 0], [1, -1]],\n        texCoord: [[0, 0], [0, 1], [1, 0], [1, 1]], // flipped\n        srcOffset: (ctx, props) => ({ buffer: props.srcOffsets, divisor: 1 }),\n        charOffset: (ctx, props) => ({ buffer: props.charOffsets, divisor: 1 }),\n        destOffset: (ctx, props) => ({ buffer: props.destOffsets, divisor: 1 }),\n        srcSize: (ctx, props) => ({ buffer: props.srcSizes, divisor: 1 }),\n        roundedBackgroundSize: (ctx, props) => ({ buffer: props.lineSizes, divisor: 1 }),\n        backgroundDestSize: (ctx, props) => ({ buffer: props.backgroundDestSizes, divisor: 1 }),\n        scale: (ctx, props) => ({ buffer: props.scale, divisor: 1 }),\n        alignmentOffset: (ctx, props) => ({ buffer: props.alignmentOffset, divisor: 1 }),\n        billboard: (ctx, props) => ({ buffer: props.billboard, divisor: 1 }),\n        textColor: (ctx, props) => ({ buffer: props.textColor, divisor: 1 }),\n        backgroundColor: (ctx, props) => ({ buffer: props.backgroundColor, divisor: 1 }),\n        posePosition: (ctx, props) => ({ buffer: props.posePosition, divisor: 1 }),\n        poseOrientation: (ctx, props) => ({ buffer: props.poseOrientation, divisor: 1 }),\n      },\n    });\n\n    return (props: $ReadOnlyArray<TextMarkerProps>, isHitmap: boolean) => {\n      // Split the text into lines\n      let estimatedInstances = 0;\n      const markersWithSplitText = props.map((marker) => {\n        const { text } = marker;\n        if (typeof text !== \"string\") {\n          throw new Error(`Expected typeof 'text' to be a string. But got type '${typeof text}' instead.`);\n        }\n\n        const charsByLine = text.split(\"\\n\").map((line) => Array.from(line));\n        charsByLine.forEach((line) => {\n          for (const char of text) {\n            ++estimatedInstances;\n            charSet.add(char);\n          }\n        });\n        return { marker, charsByLine };\n      });\n\n      let maybeGeneratedAtlas: ?GeneratedAtlas = command.textAtlas;\n      const generatedAtlasChars = maybeGeneratedAtlas ? Object.keys(maybeGeneratedAtlas.charInfo) : [];\n      const textChars = Array.from(charSet);\n      const generatedAtlasHasAllChars = difference(textChars, generatedAtlasChars).length === 0;\n      if (!maybeGeneratedAtlas || !generatedAtlasHasAllChars) {\n        // See http://webglstats.com/webgl/parameter/MAX_TEXTURE_SIZE - everyone has at least min 2048 texture size, and\n        // almost everyone has at least 4096. With a 2048 width we have ~900 height with a full character set.\n        const maxAtlasWidth: number = regl.limits.maxTextureSize || 2048;\n        const atlasConfigs = memoizedGetAtlasConfig(charSet, charSet.size, command.resolution, \"sans-serif\");\n        maybeGeneratedAtlas = memoizedGenerateAtlas(atlasConfigs, maxAtlasWidth);\n      }\n      if (!maybeGeneratedAtlas) {\n        return; // Make flow happy\n      }\n      const generatedAtlas: GeneratedAtlas = maybeGeneratedAtlas;\n      memoizedDrawAtlasTexture(generatedAtlas, atlasTexture);\n\n      const destOffsets = new Float32Array(estimatedInstances * 2);\n      const backgroundDestSizes = new Float32Array(estimatedInstances * 2);\n      const srcSizes = new Float32Array(estimatedInstances * 2);\n      const srcOffsets = new Float32Array(estimatedInstances * 2);\n      const charOffsets = new Float32Array(estimatedInstances * 2);\n      const lineSizes = new Float32Array(estimatedInstances * 2);\n\n      // These don't vary across characters within a marker, but the divisor can't be dynamic so we have to duplicate the data for each character.\n      const alignmentOffset = new Float32Array(estimatedInstances * 2);\n      const scale = new Float32Array(estimatedInstances * 3);\n      const textColor = new Float32Array(estimatedInstances * 4);\n      const backgroundColor = new Float32Array(estimatedInstances * 4);\n      const billboard = new Float32Array(estimatedInstances);\n      const posePosition = new Float32Array(estimatedInstances * 3);\n      const poseOrientation = new Float32Array(estimatedInstances * 4);\n\n      let totalInstances = 0;\n\n      // Markers sharing the same position will be rendered in multiple lines.\n      // We keep track of offsets for the y-coordinate.\n      // We cannot use same value comparison here, so the\n      // key of the map is a hash based on the marker's position\n      // (see hashMarkerPosition() above).\n      const yOffsets = new Map<string, number>();\n\n      for (const { marker, charsByLine } of markersWithSplitText) {\n        let totalWidth = 0;\n        let x = 0;\n        let y = getMarkerYOffset(yOffsets, marker);\n        let markerInstances = 0;\n\n        // If we need to render text for hitmap framebuffer, we only render the polygons using\n        // the foreground color (which needs to be converted to RGBA since it's a vec4).\n        // See comment on fragment shader above\n        const fgColor = toColor(\n          isHitmap ? marker.color || [0, 0, 0, 1] : marker.colors?.[0] || marker.color || BG_COLOR_LIGHT\n        );\n        const bgColor = toColor(\n          marker.colors?.[1] ||\n            (command.autoBackgroundColor && (isColorDark(fgColor) ? BG_COLOR_LIGHT : BG_COLOR_DARK)) ||\n            BG_COLOR_TRANSPARENT\n        );\n        const hlColor = marker?.highlightColor || { r: 1, b: 0, g: 1, a: 1 };\n        const hlColorText = isColorDark(hlColor) ? BG_COLOR_LIGHT : BG_COLOR_DARK;\n\n        const paddingScaleX = command.paddingScale?.[0] ?? 1;\n        const paddingScaleY = command.paddingScale?.[1] ?? paddingScaleX;\n\n        const paddingX = ((paddingScaleX - 1) * command.resolution) / 2;\n        const paddingY = ((paddingScaleY - 1) * command.resolution) / 2;\n\n        const lineHeight = command.resolution + paddingY * 2;\n\n        // In order to make sure there's enough room for glyphs' descenders (i.e. 'g'),\n        // we need to apply an extra offset based on the font resolution.\n        // The value used to compute the offset is a result of experimentation.\n        const charDescenderLineShift = -0.25 * command.resolution;\n\n        let runningGlyphCount = 0;\n        for (let lineIndex = 0; lineIndex < charsByLine.length; lineIndex++) {\n          const chars = charsByLine[lineIndex];\n\n          // Calculate the entire line's width ahead of time in order to calculate the rounded corners properly\n          const totalLineWidth = chars.reduce((total, char) => {\n            const info = generatedAtlas.charInfo[char];\n            return total + info.width;\n          }, paddingX * 2);\n\n          for (let i = 0; i < chars.length; i++) {\n            const char = chars[i];\n            const info = generatedAtlas.charInfo[char];\n            const index = totalInstances + markerInstances;\n\n            const firstCharOnLine = i === 0;\n            const lastCharOnLine = i === chars.length - 1;\n\n            const charIndex = runningGlyphCount + lineIndex + i;\n            const charHighlighted =\n              !isHitmap && marker.highlightedIndices && marker.highlightedIndices.includes(charIndex);\n            const charTextColor = charHighlighted ? hlColorText : fgColor;\n            const charBackgroundColor = charHighlighted ? hlColor : bgColor;\n\n            // Calculate per-character attributes\n            destOffsets[2 * index + 0] = x;\n            destOffsets[2 * index + 1] = -y;\n\n            // The offset from the top-left of the atlas to the top-left corner of each character\n            srcOffsets[2 * index + 0] = info.x + BUFFER;\n            srcOffsets[2 * index + 1] = info.y + BUFFER;\n\n            // Size of each character in the atlas in pixels\n            srcSizes[2 * index + 0] = info.width;\n            srcSizes[2 * index + 1] = info.height;\n\n            // The size of the background rectangle in pixels\n            backgroundDestSizes[2 * index + 0] =\n              info.width + (firstCharOnLine ? paddingX : 0) + (lastCharOnLine ? paddingX : 0);\n            backgroundDestSizes[2 * index + 1] = lineHeight;\n\n            // The size of all characters in the line in pixels. Used for rounded corners\n            lineSizes[2 * index + 0] = totalLineWidth;\n            lineSizes[2 * index + 1] = lineHeight;\n\n            // Additional offset for each character within the background rectangle in pixels\n            charOffsets[2 * index + 0] = firstCharOnLine ? -paddingX : 0;\n            charOffsets[2 * index + 1] = -(info.yOffset ?? 0) - charDescenderLineShift - paddingY;\n\n            x += backgroundDestSizes[2 * index + 0];\n            totalWidth = Math.max(totalWidth, x);\n\n            // Copy per-marker attributes. These are duplicated per character so that we can draw\n            // all characters from all markers in a single draw call.\n\n            billboard[index] = Number(marker.billboard ?? true);\n\n            scale[3 * index + 0] = marker.scale.x;\n            scale[3 * index + 1] = marker.scale.y;\n            scale[3 * index + 2] = marker.scale.z;\n\n            posePosition[3 * index + 0] = marker.pose.position.x;\n            posePosition[3 * index + 1] = marker.pose.position.y;\n            posePosition[3 * index + 2] = marker.pose.position.z;\n\n            poseOrientation[4 * index + 0] = marker.pose.orientation.x;\n            poseOrientation[4 * index + 1] = marker.pose.orientation.y;\n            poseOrientation[4 * index + 2] = marker.pose.orientation.z;\n            poseOrientation[4 * index + 3] = marker.pose.orientation.w;\n\n            textColor[4 * index + 0] = charTextColor.r;\n            textColor[4 * index + 1] = charTextColor.g;\n            textColor[4 * index + 2] = charTextColor.b;\n            textColor[4 * index + 3] = charTextColor.a;\n\n            backgroundColor[4 * index + 0] = charBackgroundColor.r;\n            backgroundColor[4 * index + 1] = charBackgroundColor.g;\n            backgroundColor[4 * index + 2] = charBackgroundColor.b;\n            backgroundColor[4 * index + 3] = charBackgroundColor.a;\n\n            ++markerInstances;\n          }\n\n          // Reset values for the next line\n          x = 0;\n          y += lineHeight;\n          runningGlyphCount += chars.length;\n        }\n        y -= lineHeight;\n\n        const totalHeight = y + command.resolution;\n        for (let i = 0; i < markerInstances; i++) {\n          alignmentOffset[2 * (totalInstances + i) + 0] = -totalWidth / 2;\n          alignmentOffset[2 * (totalInstances + i) + 1] = totalHeight / 2;\n        }\n\n        // Compute the y-coordinate's offset for the next overlapped marker, if any.\n        // Basically, we add as many offsets as numbers of lines in the marker's text.\n        // Since the y-coordinate is inverted when computing destOffset[] a few lines above\n        // we need an additional command.resolution offset (precomputed in totalHeight).\n        setMarkerYOffset(yOffsets, marker, totalHeight + charsByLine.length * command.resolution);\n\n        totalInstances += markerInstances;\n      }\n\n      drawText({\n        instances: totalInstances,\n\n        isHitmap: !!isHitmap,\n        resolution: command.resolution,\n        borderRadiusSize: command.borderRadius || 0,\n        scaleInvariant: command.scaleInvariant,\n        scaleInvariantSize: command.scaleInvariantSize,\n\n        // per-character\n        srcOffsets,\n        charOffsets,\n        destOffsets,\n        srcSizes,\n        lineSizes,\n        backgroundDestSizes,\n        textColor,\n        backgroundColor,\n\n        // per-marker\n        alignmentOffset,\n        billboard,\n        poseOrientation,\n        posePosition,\n        scale,\n      });\n    };\n  };\n  command.autoBackgroundColor = false;\n  return command;\n}\n\nexport const makeGLTextCommand = (props: GLTextProps) => {\n  const command = makeTextCommand(props.alphabet);\n  // HACK: Worldview doesn't provide an easy way to pass a command-level prop into the regl commands,\n  // so just attach it to the command object for now.\n  command.autoBackgroundColor = props.autoBackgroundColor;\n  command.resolution = Math.max(MIN_RESOLUTION, props.resolution || DEFAULT_RESOLUTION);\n  command.scaleInvariant = props.scaleInvariantFontSize != null;\n  command.scaleInvariantSize = props.scaleInvariantFontSize ?? 0;\n  command.textAtlas = props.textAtlas;\n  command.borderRadius = props.borderRadius;\n  command.paddingScale = props.paddingScale;\n\n  return command;\n};\n\nexport default function GLText(props: Props) {\n  const [command] = useState(() => makeGLTextCommand(props));\n  const getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\n\n  return <Command getChildrenForHitmap={getChildrenForHitmap} reglCommand={command} {...props} />;\n}\n","// @flow\n\n//  Copyright (c) 2019-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport { mat4 } from \"gl-matrix\";\nimport memoizeWeak from \"memoize-weak\";\nimport React, { useContext, useState, useEffect, useCallback, useDebugValue } from \"react\";\n\nimport type { Pose, Scale, MouseHandler } from \"../types\";\nimport { defaultBlend, pointToVec3, orientationToVec4 } from \"../utils/commandUtils\";\nimport { getChildrenForHitmapWithOriginalMarker } from \"../utils/getChildrenForHitmapDefaults\";\nimport parseGLB, { type GLBModel } from \"../utils/parseGLB\";\nimport WorldviewReactContext from \"../WorldviewReactContext\";\nimport Command from \"./Command\";\n\nfunction glConstantToRegl(value: ?number): ?string {\n  if (value === undefined) {\n    return undefined;\n  }\n  // prettier-ignore\n  switch (value) {\n    // min/mag filters\n    case WebGLRenderingContext.NEAREST: return \"nearest\";\n    case WebGLRenderingContext.LINEAR: return \"linear\";\n    case WebGLRenderingContext.NEAREST_MIPMAP_NEAREST: return \"nearest mipmap nearest\";\n    case WebGLRenderingContext.NEAREST_MIPMAP_LINEAR: return \"nearest mipmap linear\";\n    case WebGLRenderingContext.LINEAR_MIPMAP_NEAREST: return \"linear mipmap nearest\";\n    case WebGLRenderingContext.LINEAR_MIPMAP_LINEAR: return \"linear mipmap linear\";\n    // texture wrapping modes\n    case WebGLRenderingContext.REPEAT: return \"repeat\";\n    case WebGLRenderingContext.CLAMP_TO_EDGE: return \"clamp\";\n    case WebGLRenderingContext.MIRRORED_REPEAT: return \"mirror\";\n  }\n  throw new Error(`unhandled constant value ${JSON.stringify(value)}`);\n}\n\n// Default sampler set based on GLTF recommendations:\n// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#texture\nconst getDefaultSampler = () => ({\n  minFilter: WebGLRenderingContext.NEAREST_MIPMAP_LINEAR,\n  magFilter: WebGLRenderingContext.LINEAR,\n  wrapS: WebGLRenderingContext.REPEAT,\n  wrapT: WebGLRenderingContext.REPEAT,\n});\n\nconst getSceneToDraw = ({ json }) => {\n  if (json.scene != null) {\n    return json.scene;\n  }\n  // Draw the first scene if the scene key is missing.\n  const keys = Object.keys(json.scenes ?? {});\n  if (keys.length === 0) {\n    throw new Error(\"No scenes to render\");\n  }\n  return keys[0];\n};\n\nconst drawModel = (regl) => {\n  if (!regl) {\n    throw new Error(\"Invalid regl instance\");\n  }\n\n  const command = regl({\n    primitive: \"triangles\",\n    blend: defaultBlend,\n    uniforms: {\n      globalAlpha: regl.context(\"globalAlpha\"),\n      poseMatrix: regl.context(\"poseMatrix\"),\n\n      baseColorTexture: regl.prop(\"baseColorTexture\"),\n      baseColorFactor: regl.prop(\"baseColorFactor\"),\n      nodeMatrix: regl.prop(\"nodeMatrix\"),\n      \"light.direction\": [0, 0, -1],\n      \"light.ambientIntensity\": 0.5,\n      \"light.diffuseIntensity\": 0.5,\n      hitmapColor: regl.context(\"hitmapColor\"),\n      isHitmap: regl.context(\"isHitmap\"),\n    },\n    attributes: {\n      position: regl.prop(\"positions\"),\n      normal: regl.prop(\"normals\"),\n      texCoord: regl.prop(\"texCoords\"),\n    },\n    elements: regl.prop(\"indices\"),\n    vert: `\n  uniform mat4 projection, view;\n  uniform mat4 nodeMatrix;\n  uniform mat4 poseMatrix;\n  attribute vec3 position, normal;\n  varying vec3 vNormal;\n  attribute vec2 texCoord;\n  varying vec2 vTexCoord;\n\n  void main() {\n    // using the projection matrix for normals breaks lighting for orthographic mode\n    mat4 mv = view * poseMatrix * nodeMatrix;\n    vNormal = normalize((mv * vec4(normal, 0)).xyz);\n    vTexCoord = texCoord;\n    gl_Position = projection * mv * vec4(position, 1);\n  }\n  `,\n    frag: `\n  precision mediump float;\n  uniform bool isHitmap;\n  uniform vec4 hitmapColor;\n  uniform float globalAlpha;\n  uniform sampler2D baseColorTexture;\n  uniform vec4 baseColorFactor;\n  varying mediump vec2 vTexCoord;\n  varying mediump vec3 vNormal;\n\n  // Basic directional lighting from:\n  // http://ogldev.atspace.co.uk/www/tutorial18/tutorial18.html\n  struct DirectionalLight {\n    mediump vec3 direction;\n    lowp float ambientIntensity;\n    lowp float diffuseIntensity;\n  };\n  uniform DirectionalLight light;\n\n  void main() {\n    vec4 baseColor = texture2D(baseColorTexture, vTexCoord) * baseColorFactor;\n    float diffuse = light.diffuseIntensity * max(0.0, dot(vNormal, -light.direction));\n    gl_FragColor = isHitmap ? hitmapColor : vec4((light.ambientIntensity + diffuse) * baseColor.rgb, baseColor.a * globalAlpha);\n  }\n  `,\n  });\n\n  // default values for when baseColorTexture is not specified\n  const singleTexCoord = regl.buffer([0, 0]);\n  const whiteTexture = regl.texture({\n    data: [255, 255, 255, 255],\n    width: 1,\n    height: 1,\n  });\n\n  // build the draw calls needed to draw the model. This will happen whenever the model changes.\n  const getDrawCalls = memoizeWeak((model: GLBModel) => {\n    // upload textures to the GPU\n    const { accessors } = model;\n    const textures =\n      model.json.textures &&\n      model.json.textures.map((textureInfo) => {\n        const sampler = textureInfo.sampler ? model.json.samplers[textureInfo.sampler] : getDefaultSampler();\n        const bitmap = model.images && model.images[textureInfo.source];\n        const texture = regl.texture({\n          data: bitmap,\n          min: glConstantToRegl(sampler.minFilter),\n          mag: glConstantToRegl(sampler.magFilter),\n          wrapS: glConstantToRegl(sampler.wrapS),\n          wrapT: glConstantToRegl(sampler.wrapT),\n        });\n        return texture;\n      });\n    if (model.images) {\n      model.images.forEach((bitmap: ImageBitmap) => bitmap.close());\n    }\n\n    const drawCalls = [];\n    // helper to draw the primitives comprising a mesh\n    function drawMesh(mesh, nodeMatrix) {\n      for (const primitive of mesh.primitives) {\n        const material = model.json.materials[primitive.material];\n        const texInfo = material.pbrMetallicRoughness.baseColorTexture;\n\n        let primitiveAccessors = accessors;\n        const { extensions = {} } = primitive;\n        const dracoCompressionEXT = extensions.KHR_draco_mesh_compression;\n        if (dracoCompressionEXT) {\n          // If mesh contains compressed data, accessors will be available inside\n          // the draco extension. See `parseGLB.js` and `draco.js` files.\n          primitiveAccessors = dracoCompressionEXT.accessors;\n        }\n        if (!primitiveAccessors) {\n          throw new Error(\"Error decoding GLB model: Missing `accessors` in JSON data\");\n        }\n\n        drawCalls.push({\n          indices: primitiveAccessors[primitive.indices],\n          positions: primitiveAccessors[primitive.attributes.POSITION],\n          normals: primitiveAccessors[primitive.attributes.NORMAL],\n          texCoords: texInfo\n            ? primitiveAccessors[primitive.attributes[`TEXCOORD_${texInfo.texCoord || 0}`]]\n            : { divisor: 1, buffer: singleTexCoord },\n          baseColorTexture: texInfo ? textures[texInfo.index] : whiteTexture,\n          baseColorFactor: material.pbrMetallicRoughness.baseColorFactor || [1, 1, 1, 1],\n          nodeMatrix,\n        });\n      }\n    }\n\n    // helper to draw all the meshes contained in a node and its child nodes\n    function drawNode(node, parentMatrix) {\n      const nodeMatrix = node.matrix\n        ? mat4.clone(node.matrix)\n        : mat4.fromRotationTranslationScale(\n            mat4.create(),\n            node.rotation || [0, 0, 0, 1],\n            node.translation || [0, 0, 0],\n            node.scale || [1, 1, 1]\n          );\n      mat4.mul(nodeMatrix, parentMatrix, nodeMatrix);\n      if (node.mesh != null) {\n        drawMesh(model.json.meshes[node.mesh], nodeMatrix);\n      }\n      if (node.children) {\n        for (const childIdx of node.children) {\n          drawNode(model.json.nodes[childIdx], nodeMatrix);\n        }\n      }\n    }\n\n    // finally, draw each of the main scene's nodes. Use the first scene if one isn't specified\n    // explicitly.\n    for (const nodeIdx of model.json.scenes[getSceneToDraw(model)].nodes) {\n      const rootTransform = mat4.create();\n      mat4.rotateX(rootTransform, rootTransform, Math.PI / 2);\n      mat4.rotateY(rootTransform, rootTransform, Math.PI / 2);\n      drawNode(model.json.nodes[nodeIdx], rootTransform);\n    }\n    return drawCalls;\n  });\n\n  // create a regl command to set the context for each draw call\n  const withContext = regl({\n    context: {\n      poseMatrix: (context, props) =>\n        mat4.fromRotationTranslationScale(\n          mat4.create(),\n          orientationToVec4(props.pose.orientation),\n          pointToVec3(props.pose.position),\n          props.scale ? pointToVec3(props.scale) : [1, 1, 1]\n        ),\n      globalAlpha: (context, props) => (props.alpha == null ? 1 : props.alpha),\n      hitmapColor: (context, props) => props.color || [0, 0, 0, 1],\n      isHitmap: (context, props) => !!props.isHitmap,\n    },\n  });\n\n  return (props, isHitmap) => {\n    const drawCalls = getDrawCalls(props.model);\n    withContext(isHitmap ? { ...props, isHitmap } : props, () => {\n      command(drawCalls);\n    });\n  };\n};\n\ntype Props = {|\n  model: string | (() => Promise<GLBModel>),\n  onClick?: MouseHandler,\n  onDoubleClick?: MouseHandler,\n  onMouseDown?: MouseHandler,\n  onMouseMove?: MouseHandler,\n  onMouseUp?: MouseHandler,\n  children: {\n    pose: Pose,\n    scale: Scale,\n    alpha?: ?number,\n  },\n|};\n\nfunction useAsyncValue<T>(fn: () => Promise<T>, deps: ?(any[])): ?T {\n  const [value, setValue] = useState<?T>();\n  useEffect(\n    useCallback(() => {\n      let unloaded = false;\n      fn().then((result) => {\n        if (!unloaded) {\n          setValue(result);\n        }\n      });\n      return () => {\n        unloaded = true;\n        setValue(undefined);\n      };\n    }, deps || [fn]),\n    deps || [fn]\n  );\n  return value;\n}\n\nfunction useModel(model: string | (() => Promise<GLBModel>)): ?GLBModel {\n  useDebugValue(model);\n  return useAsyncValue(async () => {\n    if (typeof model === \"function\") {\n      return model();\n    }\n    if (typeof model === \"string\") {\n      const response = await fetch(model);\n      if (!response.ok) {\n        throw new Error(`failed to fetch GLTF model: ${response.status}`);\n      }\n      return parseGLB(await response.arrayBuffer());\n    }\n\n    /*:: (model: empty) */\n    throw new Error(`unsupported model prop: ${typeof model}`);\n  }, [model]);\n}\n\nexport default function GLTFScene(props: Props) {\n  const { children, model, ...rest } = props;\n\n  const context = useContext(WorldviewReactContext);\n  const loadedModel = useModel(model);\n  useEffect(() => {\n    if (context) {\n      context.onDirty();\n    }\n  }, [context, loadedModel]);\n\n  if (!loadedModel) {\n    return null;\n  }\n\n  return (\n    <Command {...rest} reglCommand={drawModel} getChildrenForHitmap={getChildrenForHitmapWithOriginalMarker}>\n      {{ ...children, model: loadedModel, originalMarker: children }}\n    </Command>\n  );\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React from \"react\";\n\nimport { withPose } from \"../utils/commandUtils\";\nimport { nonInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\nconst DEFAULT_GRID_COLOR = [0.3, 0.3, 0.3, 1];\n\nexport function grid() {\n  return withPose({\n    vert: `\n    precision mediump float;\n    uniform mat4 projection, view;\n\n    attribute vec3 point;\n    attribute vec4 color;\n    varying vec4 fragColor;\n\n    void main () {\n      fragColor = color;\n      vec3 p = point;\n      gl_Position = projection * view * vec4(p, 1);\n    }\n    `,\n    frag: `\n      precision mediump float;\n      varying vec4 fragColor;\n      void main () {\n        gl_FragColor = fragColor;\n      }\n    `,\n    primitive: \"lines\",\n    attributes: {\n      point: (context, props) => {\n        const points = [];\n        const bound = props.count;\n        for (let i = -props.count; i < props.count; i++) {\n          points.push([-bound, i, 0]);\n          points.push([bound, i, 0]);\n          points.push([i, -bound, 0]);\n          points.push([i, bound, 0]);\n        }\n        return points;\n      },\n      color: (context, props) => {\n        const color = props.color || DEFAULT_GRID_COLOR;\n        return new Array(props.count * 4 * 2).fill(color);\n      },\n    },\n    count: (context, props) => {\n      // 8 points per count\n      const count = props.count * 4 * 2;\n      return count;\n    },\n  });\n}\n\ntype Props = {\n  ...CommonCommandProps,\n  count: number,\n};\n\n// useful for rendering a grid for debugging in stories\n\nexport default function Grid({ count, ...rest }: Props) {\n  const children = { count };\n  return (\n    <Command getChildrenForHitmap={nonInstancedGetChildrenForHitmap} {...rest} reglCommand={grid}>\n      {children}\n    </Command>\n  );\n}\n\nGrid.defaultProps = { count: 6 };\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport * as React from \"react\";\n\nimport type { Point, Vec3, Dimensions, Pose } from \"../types\";\nimport { type WorldviewContextType } from \"../WorldviewContext\";\nimport WorldviewReactContext from \"../WorldviewReactContext\";\n\ntype PoseObj = { pose: Pose };\ntype RenderItemInput<T: PoseObj> = {\n  item: T,\n  coordinates: ?Vec3,\n  index: number,\n  dimension: Dimensions,\n};\n\ntype Props<T: PoseObj> = {\n  children: T[],\n  renderItem: (RenderItemInput<T>) => React.Node,\n};\n\ntype State = {\n  items: React.Node[],\n};\n\n// A command that renders arbitrary DOM nodes on top of the Worldview 3D scene.\n// It supplies coordinates to the `renderItem` prop for positioning DOM nodes relative to the canvas.\nexport default class Overlay<T: PoseObj> extends React.Component<Props<T>, State> {\n  _context: ?WorldviewContextType;\n  state = { items: [] };\n\n  componentDidMount() {\n    if (this._context) {\n      this._context.registerPaintCallback(this.paint);\n    }\n  }\n\n  componentWillUnmount = () => {\n    if (this._context) {\n      this._context.unregisterPaintCallback(this.paint);\n    }\n  };\n\n  paint = () => {\n    const context = this._context;\n    const dimension = context && context.dimension;\n    const { renderItem, children } = this.props;\n    if (!context || !dimension) {\n      return;\n    }\n    const items = children.map((item, index) => {\n      const coordinates = this.project(item.pose.position, context);\n      return renderItem({ item, index, coordinates, dimension });\n    });\n    this.setState({ items });\n  };\n\n  project = (point: Point, context: ?WorldviewContextType): ?Vec3 => {\n    if (!context || !context.initializedData) {\n      return;\n    }\n    const { dimension } = context;\n    const { camera } = context.initializedData;\n\n    const vec = [point.x, point.y, point.z];\n    const { left, top, width, height } = dimension;\n    const viewport = [left, top, width, height];\n    return camera.toScreenCoord(viewport, vec);\n  };\n\n  render() {\n    return (\n      <React.Fragment>\n        <WorldviewReactContext.Consumer>\n          {(ctx: ?WorldviewContextType) => {\n            if (ctx) {\n              this._context = ctx;\n            }\n            return this.state.items;\n          }}\n        </WorldviewReactContext.Consumer>\n      </React.Fragment>\n    );\n  }\n}\n","// @flow\n\n//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React, { useState } from \"react\";\n\nimport type { PointType, Regl } from \"../types\";\nimport { getVertexColors, pointToVec3, withPose } from \"../utils/commandUtils\";\nimport { createInstancedGetChildrenForHitmap } from \"../utils/getChildrenForHitmapDefaults\";\nimport Command, { type CommonCommandProps } from \"./Command\";\n\ntype PointsProps = {|\n  useWorldSpaceSize?: boolean,\n|};\n\ntype Props = {\n  // $FlowFixMe: flow does not know how to handle the indexed property in CommonCommandProps\n  ...CommonCommandProps,\n  ...PointsProps,\n  children: $ReadOnlyArray<PointType>,\n};\n\nexport const makePointsCommand = ({ useWorldSpaceSize }: PointsProps) => {\n  return (regl: Regl) => {\n    if (!regl) {\n      throw new Error(\"Invalid regl instance\");\n    }\n\n    const [minLimitPointSize, maxLimitPointSize] = regl.limits.pointSizeDims;\n    return withPose({\n      primitive: \"points\",\n      vert: `\n    precision mediump float;\n\n    #WITH_POSE\n\n    uniform mat4 projection, view;\n    uniform float pointSize;\n    uniform bool useWorldSpaceSize;\n    uniform float viewportWidth;\n    uniform float viewportHeight;\n    uniform float minPointSize;\n    uniform float maxPointSize;\n\n    attribute vec3 point;\n    attribute vec4 color;\n    varying vec4 fragColor;\n    void main () {\n      vec3 pos = applyPose(point);\n      gl_Position = projection * view * vec4(pos, 1);\n      fragColor = color;\n\n      if (useWorldSpaceSize) {\n        // Calculate the point size based on world dimensions:\n        // First, we need to compute a new point that is one unit away from\n        // the center of the current point being rendered. We do it in view space\n        // in order to make sure the new point is always one unit up and it's not\n        // affected by view rotation.\n        vec4 up = projection * (view * vec4(pos, 1.0) + vec4(0.0, 1.0, 0.0, 0.0));\n\n        // Then, we compute the distance between both points in clip space, dividing\n        // by the w-component to account for distance in perspective projection.\n        float d = length(up.xyz / up.w - gl_Position.xyz / gl_Position.w);\n\n        // Finally, the point size is calculated using the size of the render target\n        // and it's aspect ratio. We multiply it by 0.5 since distance in clip space\n        // is in range [0, 2] (because clip space's range is [-1, 1]) and\n        // we need it to be [0, 1].\n        float invAspect = viewportHeight / viewportWidth;\n        gl_PointSize = pointSize * 0.5 * d * viewportWidth * invAspect;\n      } else {\n        gl_PointSize = pointSize;\n      }\n\n      // Finally, ensure the calculated point size is within the limits.\n      gl_PointSize = min(maxPointSize, max(minPointSize, gl_PointSize));\n    }\n    `,\n      frag: `\n    precision mediump float;\n    varying vec4 fragColor;\n    void main () {\n      gl_FragColor = vec4(fragColor.x, fragColor.y, fragColor.z, 1);\n    }\n    `,\n      attributes: {\n        point: (context, props) => {\n          return props.points.map((point) => (Array.isArray(point) ? point : pointToVec3(point)));\n        },\n        color: (context, props) => {\n          const colors = getVertexColors(props);\n          return colors;\n        },\n      },\n\n      uniforms: {\n        pointSize: (context, props) => {\n          return props.scale.x || 1;\n        },\n        useWorldSpaceSize: !!useWorldSpaceSize,\n        viewportWidth: regl.context(\"viewportWidth\"),\n        viewportHeight: regl.context(\"viewportHeight\"),\n        minPointSize: minLimitPointSize,\n        maxPointSize: maxLimitPointSize,\n      },\n\n      count: regl.prop(\"points.length\"),\n    });\n  };\n};\n\nconst getChildrenForHitmap = createInstancedGetChildrenForHitmap(1);\nexport default function Points(props: Props) {\n  const [command] = useState(() => makePointsCommand(props));\n  return <Command getChildrenForHitmap={getChildrenForHitmap} {...props} reglCommand={command} />;\n}\n","//  Copyright (c) 2018-present, GM Cruise LLC\n//\n//  This source code is licensed under the Apache License, Version 2.0,\n//  found in the LICENSE file in the root directory of this source tree.\n//  You may not use this file except in compliance with the License.\n\nimport React, { useLayoutEffect } from \"react\";\n\nimport { generateAtlas } from \"../commands/GLText\";\n\nconst MAX_ATLAS_WIDTH = 2048;\n\nconst SDFGenerator = ({ atlasConfigs }) => {\n  const canvasRef = React.useRef();\n  const atlasData = React.useRef({ textureWidth: MAX_ATLAS_WIDTH, textureHeight: MAX_ATLAS_WIDTH });\n\n  const regenerateAtlas = React.useCallback(async () => {\n    const canEl = canvasRef.current;\n    if (canEl) {\n      const { charInfo, textureWidth, textureHeight, textureData } = generateAtlas(atlasConfigs, MAX_ATLAS_WIDTH);\n      atlasData.current = { charInfo, textureData, textureWidth, textureHeight };\n\n      const ctx = canEl.getContext(\"2d\");\n      canEl.width = textureWidth;\n      canEl.height = textureHeight;\n      ctx.clearRect(0, 0, canEl.width, canEl.height);\n      ctx.putImageData(makeRGBAImageData(ctx, textureData, textureWidth, textureHeight), 0, 0);\n    }\n  }, [atlasConfigs]);\n\n  const downloadAtlasFiles = React.useCallback(() => {\n    const canEl = canvasRef.current;\n    if (canEl) {\n      const { charInfo, textureWidth, textureHeight, textureData } = atlasData.current;\n      const textAtlasJson = {\n        charInfo,\n        textureWidth,\n        textureHeight,\n      };\n      const textAtlasJsonStr = JSON.stringify(textAtlasJson, null, 2);\n      const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(textAtlasJsonStr)}`;\n      downloadURL(dataStr, \"textAtlas.json\");\n\n      const blob = new Blob([textureData], { type: \"application/octet-stream\" });\n      const url = window.URL.createObjectURL(blob);\n      downloadURL(url, \"textureAtlasData.bin\");\n      setTimeout(() => window.URL.revokeObjectURL(url));\n    }\n  }, []);\n\n  // Regenerate the atlas once all fonts have loaded\n  useLayoutEffect(() => {\n    // $FlowFixMe - Flow doesn't understand document.fonts\n    document.fonts.ready.then(() => {\n      regenerateAtlas();\n    });\n  }, []);\n\n  return (\n    <div style={{ margin: 16 }}>\n      <button style={{ margin: 16 }} onClick={regenerateAtlas}>\n        Regenerate atlas\n      </button>\n      <button style={{ margin: 16 }} onClick={downloadAtlasFiles}>\n        Download atlas files\n      </button>\n      <canvas\n        ref={canvasRef}\n        width={atlasData.current.textureWidth}\n        height={atlasData.current.textureHeight}\n        style={{ backgroundColor: \"white\" }}\n      />\n    </div>\n  );\n};\n\n// Convert alpha-only to RGBA so we can use `putImageData` for building the composite bitmap\nfunction makeRGBAImageData(ctx, alphaChannel, width, height) {\n  const imageData = ctx.createImageData(width, height);\n  for (let i = 0; i < alphaChannel.length; i++) {\n    imageData.data[4 * i + 0] = alphaChannel[i];\n    imageData.data[4 * i + 1] = alphaChannel[i];\n    imageData.data[4 * i + 2] = alphaChannel[i];\n    imageData.data[4 * i + 3] = 255;\n  }\n  return imageData;\n}\n\nfunction downloadURL(data, fileName) {\n  const a = Object.assign(document.createElement(\"a\"), {\n    href: data,\n    download: fileName,\n  });\n  if (document.body) {\n    document.body.appendChild(a);\n  }\n  a.style.display = \"none\";\n  a.click();\n  a.remove();\n}\n\nexport default SDFGenerator;\n"]}